blob: 16ce1e4f137edbaf664c22fff4cdd2fc6249ef80 [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>
Prabir Pradhana37bad12023-08-18 15:55:32 +000035#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000036#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070037#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010038#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070039#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080040
Michael Wright44753b12020-07-08 13:48:11 +010041#include <cerrno>
42#include <cinttypes>
43#include <climits>
44#include <cstddef>
45#include <ctime>
46#include <queue>
47#include <sstream>
48
Asmita Poddardd9a6cd2023-09-26 15:35:12 +000049#include "../InputDeviceMetricsSource.h"
50
Michael Wright44753b12020-07-08 13:48:11 +010051#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000052#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070053#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010054
Michael Wrightd02c5b62014-02-10 15:10:22 -080055#define INDENT " "
56#define INDENT2 " "
57#define INDENT3 " "
58#define INDENT4 " "
59
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080060using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070061using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080062using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000063using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080064using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070065using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050066using android::gui::FocusRequest;
67using android::gui::TouchOcclusionMode;
68using android::gui::WindowInfo;
69using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080070using android::os::InputEventInjectionResult;
71using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080072
Garfield Tane84e6f92019-08-29 17:28:41 -070073namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080074
Prabir Pradhancef936d2021-07-21 16:17:52 +000075namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000076// Temporarily releases a held mutex for the lifetime of the instance.
77// Named to match std::scoped_lock
78class scoped_unlock {
79public:
80 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
81 ~scoped_unlock() { mMutex.lock(); }
82
83private:
84 std::mutex& mMutex;
85};
86
Michael Wrightd02c5b62014-02-10 15:10:22 -080087// Default input dispatching timeout if there is no focused application or paused window
88// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080089const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
90 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
91 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
93// Amount of time to allow for all pending events to be processed when an app switch
94// key is on the way. This is used to preempt input dispatch and drop input events
95// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000096constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080098const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100// 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 +0000101constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
102
103// Log a warning when an interception call takes longer than this to process.
104constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700106// Additional key latency in case a connection is still processing some motion events.
107// This will help with the case when a user touched a button that opens a new window,
108// and gives us the chance to dispatch the key to this new window.
109constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
110
Michael Wrightd02c5b62014-02-10 15:10:22 -0800111// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000112constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
113
Antonio Kantekea47acb2021-12-23 12:41:25 -0800114// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000115constexpr int LOGTAG_INPUT_INTERACTION = 62000;
116constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000117constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000118
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000119const ui::Transform kIdentityTransform;
120
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000121inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800122 return systemTime(SYSTEM_TIME_MONOTONIC);
123}
124
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -0700125bool isEmpty(const std::stringstream& ss) {
126 return ss.rdbuf()->in_avail() == 0;
127}
128
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700129inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000130 if (binder == nullptr) {
131 return "<null>";
132 }
133 return StringPrintf("%p", binder.get());
134}
135
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000136static std::string uidString(const gui::Uid& uid) {
137 return uid.toString();
138}
139
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700140Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700142 case AKEY_EVENT_ACTION_DOWN:
143 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700144 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700145 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700146 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 }
148}
149
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700150Result<void> validateKeyEvent(int32_t action) {
151 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800152}
153
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700154Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800155 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700157 case AMOTION_EVENT_ACTION_UP: {
158 if (pointerCount != 1) {
159 return Error() << "invalid pointer count " << pointerCount;
160 }
161 return {};
162 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700163 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700164 case AMOTION_EVENT_ACTION_HOVER_ENTER:
165 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700166 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
167 if (pointerCount < 1) {
168 return Error() << "invalid pointer count " << pointerCount;
169 }
170 return {};
171 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800172 case AMOTION_EVENT_ACTION_CANCEL:
173 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700175 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 case AMOTION_EVENT_ACTION_POINTER_DOWN:
177 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800178 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700179 if (index < 0) {
180 return Error() << "invalid index " << index << " for "
181 << MotionEvent::actionToString(action);
182 }
183 if (index >= pointerCount) {
184 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
185 }
186 if (pointerCount <= 1) {
187 return Error() << "invalid pointer count " << pointerCount << " for "
188 << MotionEvent::actionToString(action);
189 }
190 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700191 }
192 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700193 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
194 if (actionButton == 0) {
195 return Error() << "action button should be nonzero for "
196 << MotionEvent::actionToString(action);
197 }
198 return {};
199 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700200 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700201 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 }
203}
204
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000205int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500206 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
207}
208
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700209Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
210 const PointerProperties* pointerProperties) {
211 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
212 if (!actionCheck.ok()) {
213 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 }
215 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700216 return Error() << "Motion event has invalid pointer count " << pointerCount
217 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800219 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 for (size_t i = 0; i < pointerCount; i++) {
221 int32_t id = pointerProperties[i].id;
222 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700223 return Error() << "Motion event has invalid pointer id " << id
224 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800225 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800226 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700227 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800229 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700231 return {};
232}
233
234Result<void> validateInputEvent(const InputEvent& event) {
235 switch (event.getType()) {
236 case InputEventType::KEY: {
237 const KeyEvent& key = static_cast<const KeyEvent&>(event);
238 const int32_t action = key.getAction();
239 return validateKeyEvent(action);
240 }
241 case InputEventType::MOTION: {
242 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
243 const int32_t action = motion.getAction();
244 const size_t pointerCount = motion.getPointerCount();
245 const PointerProperties* pointerProperties = motion.getPointerProperties();
246 const int32_t actionButton = motion.getActionButton();
247 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
248 }
249 default: {
250 return {};
251 }
252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253}
254
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000255std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000257 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258 }
259
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000260 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261 bool first = true;
262 Region::const_iterator cur = region.begin();
263 Region::const_iterator const tail = region.end();
264 while (cur != tail) {
265 if (first) {
266 first = false;
267 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800268 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800270 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800271 cur++;
272 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000273 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800274}
275
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000276std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
277 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500278 constexpr size_t maxEntries = 50; // max events to print
279 constexpr size_t skipBegin = maxEntries / 2;
280 const size_t skipEnd = queue.size() - maxEntries / 2;
281 // skip from maxEntries / 2 ... size() - maxEntries/2
282 // only print from 0 .. skipBegin and then from skipEnd .. size()
283
284 std::string dump;
285 for (size_t i = 0; i < queue.size(); i++) {
286 const DispatchEntry& entry = *queue[i];
287 if (i >= skipBegin && i < skipEnd) {
288 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
289 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
290 continue;
291 }
292 dump.append(INDENT4);
293 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800294 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
295 "ms",
296 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500297 ns2ms(currentTime - entry.eventEntry->eventTime));
298 if (entry.deliveryTime != 0) {
299 // This entry was delivered, so add information on how long we've been waiting
300 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
301 }
302 dump.append("\n");
303 }
304 return dump;
305}
306
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700307/**
308 * Find the entry in std::unordered_map by key, and return it.
309 * If the entry is not found, return a default constructed entry.
310 *
311 * Useful when the entries are vectors, since an empty vector will be returned
312 * if the entry is not found.
313 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
314 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700315template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000316V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700317 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700318 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800319}
320
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000321bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700322 if (first == second) {
323 return true;
324 }
325
326 if (first == nullptr || second == nullptr) {
327 return false;
328 }
329
330 return first->getToken() == second->getToken();
331}
332
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000333bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000334 if (first == nullptr || second == nullptr) {
335 return false;
336 }
337 return first->applicationInfo.token != nullptr &&
338 first->applicationInfo.token == second->applicationInfo.token;
339}
340
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800341template <typename T>
342size_t firstMarkedBit(T set) {
343 // TODO: replace with std::countr_zero from <bit> when that's available
344 LOG_ALWAYS_FATAL_IF(set.none());
345 size_t i = 0;
346 while (!set.test(i)) {
347 i++;
348 }
349 return i;
350}
351
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800352std::unique_ptr<DispatchEntry> createDispatchEntry(
353 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
354 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700355 if (inputTarget.useDefaultPointerTransform()) {
356 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700357 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700358 inputTarget.displayTransform,
359 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000360 }
361
362 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
363 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
364
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700365 std::vector<PointerCoords> pointerCoords;
366 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000367
368 // Use the first pointer information to normalize all other pointers. This could be any pointer
369 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700370 // uses the transform for the normalized pointer.
371 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800372 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700373 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000374
375 // Iterate through all pointers in the event to normalize against the first.
376 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
377 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
378 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700379 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000380
381 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700382 // First, apply the current pointer's transform to update the coordinates into
383 // window space.
384 pointerCoords[pointerIndex].transform(currTransform);
385 // Next, apply the inverse transform of the normalized coordinates so the
386 // current coordinates are transformed into the normalized coordinate space.
387 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000388 }
389
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700390 std::unique_ptr<MotionEntry> combinedMotionEntry =
391 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
392 motionEntry.deviceId, motionEntry.source,
393 motionEntry.displayId, motionEntry.policyFlags,
394 motionEntry.action, motionEntry.actionButton,
395 motionEntry.flags, motionEntry.metaState,
396 motionEntry.buttonState, motionEntry.classification,
397 motionEntry.edgeFlags, motionEntry.xPrecision,
398 motionEntry.yPrecision, motionEntry.xCursorPosition,
399 motionEntry.yCursorPosition, motionEntry.downTime,
400 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000401 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000402
403 if (motionEntry.injectionState) {
404 combinedMotionEntry->injectionState = motionEntry.injectionState;
405 combinedMotionEntry->injectionState->refCount += 1;
406 }
407
408 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700409 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700410 firstPointerTransform, inputTarget.displayTransform,
411 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000412 return dispatchEntry;
413}
414
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000415status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
416 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700417 std::unique_ptr<InputChannel> uniqueServerChannel;
418 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
419
420 serverChannel = std::move(uniqueServerChannel);
421 return result;
422}
423
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500424template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000425bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500426 if (lhs == nullptr && rhs == nullptr) {
427 return true;
428 }
429 if (lhs == nullptr || rhs == nullptr) {
430 return false;
431 }
432 return *lhs == *rhs;
433}
434
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000435KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000436 KeyEvent event;
437 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
438 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
439 entry.repeatCount, entry.downTime, entry.eventTime);
440 return event;
441}
442
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000443bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000444 // Do not keep track of gesture monitors. They receive every event and would disproportionately
445 // affect the statistics.
446 if (connection.monitor) {
447 return false;
448 }
449 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
450 if (!connection.responsive) {
451 return false;
452 }
453 return true;
454}
455
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000456bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000457 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
458 const int32_t& inputEventId = eventEntry.id;
459 if (inputEventId != dispatchEntry.resolvedEventId) {
460 // Event was transmuted
461 return false;
462 }
463 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
464 return false;
465 }
466 // Only track latency for events that originated from hardware
467 if (eventEntry.isSynthesized()) {
468 return false;
469 }
470 const EventEntry::Type& inputEventEntryType = eventEntry.type;
471 if (inputEventEntryType == EventEntry::Type::KEY) {
472 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
473 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
474 return false;
475 }
476 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
477 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
478 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
479 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
480 return false;
481 }
482 } else {
483 // Not a key or a motion
484 return false;
485 }
486 if (!shouldReportMetricsForConnection(connection)) {
487 return false;
488 }
489 return true;
490}
491
Prabir Pradhancef936d2021-07-21 16:17:52 +0000492/**
493 * Connection is responsive if it has no events in the waitQueue that are older than the
494 * current time.
495 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000496bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000497 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000498 for (const auto& dispatchEntry : connection.waitQueue) {
499 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000500 return false;
501 }
502 }
503 return true;
504}
505
Antonio Kantekf16f2832021-09-28 04:39:20 +0000506// Returns true if the event type passed as argument represents a user activity.
507bool isUserActivityEvent(const EventEntry& eventEntry) {
508 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000509 case EventEntry::Type::CONFIGURATION_CHANGED:
510 case EventEntry::Type::DEVICE_RESET:
511 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000512 case EventEntry::Type::FOCUS:
513 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000514 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000515 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000516 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000517 case EventEntry::Type::KEY:
518 case EventEntry::Type::MOTION:
519 return true;
520 }
521}
522
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800523// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000524bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000525 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800526 const auto inputConfig = windowInfo.inputConfig;
527 if (windowInfo.displayId != displayId ||
528 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800529 return false;
530 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700531 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800532 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800533 return false;
534 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000535
536 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
537 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
538 // the window. Points on the right and bottom edges should not be inside the window, so we need
539 // to be careful about performing a hit test when the display is rotated, since the "right" and
540 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
541 // logical display in which WM determined the bounds. Perform the hit test in the logical
542 // display space to ensure these edges are considered correctly in all orientations.
543 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
544 const auto p = displayTransform.transform(x, y);
545 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800546 return false;
547 }
548 return true;
549}
550
Prabir Pradhand65552b2021-10-07 11:23:50 -0700551bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
552 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000553 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700554}
555
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800556// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000557// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
558// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
559// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800560// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000561bool canReceiveForegroundTouches(const WindowInfo& info) {
562 // A non-touchable window can still receive touch events (e.g. in the case of
563 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
564 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
565}
566
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000567bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700568 if (windowHandle == nullptr) {
569 return false;
570 }
571 const WindowInfo* windowInfo = windowHandle->getInfo();
572 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
573 return true;
574 }
575 return false;
576}
577
Prabir Pradhan5735a322022-04-11 17:23:34 +0000578// Checks targeted injection using the window's owner's uid.
579// Returns an empty string if an entry can be sent to the given window, or an error message if the
580// entry is a targeted injection whose uid target doesn't match the window owner.
581std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
582 const EventEntry& entry) {
583 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
584 // The event was not injected, or the injected event does not target a window.
585 return {};
586 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000587 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000588 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000589 return StringPrintf("No valid window target for injection into uid %s.",
590 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000591 }
592 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000593 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
594 "owned by uid %s.",
595 uid.toString().c_str(), window->getName().c_str(),
596 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000597 }
598 return {};
599}
600
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000601std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700602 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
603 // Always dispatch mouse events to cursor position.
604 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000605 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700606 }
607
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700608 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000609 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
610 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700611}
612
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700613std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
614 if (eventEntry.type == EventEntry::Type::KEY) {
615 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
616 return keyEntry.downTime;
617 } else if (eventEntry.type == EventEntry::Type::MOTION) {
618 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
619 return motionEntry.downTime;
620 }
621 return std::nullopt;
622}
623
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000624/**
625 * Compare the old touch state to the new touch state, and generate the corresponding touched
626 * windows (== input targets).
627 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
628 * If the pointer just entered the new window, produce HOVER_ENTER.
629 * For pointers remaining in the window, produce HOVER_MOVE.
630 */
631std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
632 const TouchState& newTouchState,
633 const MotionEntry& entry) {
634 std::vector<TouchedWindow> out;
635 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
636 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
637 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
638 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
639 // Not a hover event - don't need to do anything
640 return out;
641 }
642
643 // We should consider all hovering pointers here. But for now, just use the first one
644 const int32_t pointerId = entry.pointerProperties[0].id;
645
646 std::set<sp<WindowInfoHandle>> oldWindows;
647 if (oldState != nullptr) {
648 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
649 }
650
651 std::set<sp<WindowInfoHandle>> newWindows =
652 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
653
654 // If the pointer is no longer in the new window set, send HOVER_EXIT.
655 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
656 if (newWindows.find(oldWindow) == newWindows.end()) {
657 TouchedWindow touchedWindow;
658 touchedWindow.windowHandle = oldWindow;
659 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000660 out.push_back(touchedWindow);
661 }
662 }
663
664 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
665 TouchedWindow touchedWindow;
666 touchedWindow.windowHandle = newWindow;
667 if (oldWindows.find(newWindow) == oldWindows.end()) {
668 // Any windows that have this pointer now, and didn't have it before, should get
669 // HOVER_ENTER
670 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
671 } else {
672 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700673 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700674 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
675 if (entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
676 // The Accessibility injected touch exploration event stream
677 // has known inconsistencies, so log ERROR instead of
678 // crashing the device with FATAL.
679 // TODO(b/299977100): Move a11y severity back to FATAL.
680 severity = android::base::LogSeverity::ERROR;
681 }
682 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700683 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000684 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
685 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700686 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000687 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
688 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
689 }
690 out.push_back(touchedWindow);
691 }
692 return out;
693}
694
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800695template <typename T>
696std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
697 left.insert(left.end(), right.begin(), right.end());
698 return left;
699}
700
Harry Cuttsb166c002023-05-09 13:06:05 +0000701// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
702// both.
703void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
704 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
705 if (!window.windowHandle->getInfo()->inputConfig.test(
706 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
707 // In addition to TouchState, erase this window from the input targets! We don't have a
708 // good way to do this today except by adding a nested loop.
709 // TODO(b/282025641): simplify this code once InputTargets are being identified
710 // separately from TouchedWindows.
711 std::erase_if(targets, [&](const InputTarget& target) {
712 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
713 });
714 return true;
715 }
716 return false;
717 });
718}
719
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700720/**
721 * In general, touch should be always split between windows. Some exceptions:
722 * 1. Don't split touch if all of the below is true:
723 * (a) we have an active pointer down *and*
724 * (b) a new pointer is going down that's from the same device *and*
725 * (c) the window that's receiving the current pointer does not support split touch.
726 * 2. Don't split mouse events
727 */
728bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
729 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
730 // We should never split mouse events
731 return false;
732 }
733 for (const TouchedWindow& touchedWindow : touchState.windows) {
734 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
735 // Spy windows should not affect whether or not touch is split.
736 continue;
737 }
738 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
739 continue;
740 }
741 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
742 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
743 // Wallpaper window should not affect whether or not touch is split
744 continue;
745 }
746
747 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
748 return false;
749 }
750 }
751 return true;
752}
753
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000754} // namespace
755
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756// --- InputDispatcher ---
757
Prabir Pradhana41d2442023-04-20 21:30:40 +0000758InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800759 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
760
Prabir Pradhana41d2442023-04-20 21:30:40 +0000761InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800762 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700763 : mPolicy(policy),
764 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700765 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800766 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700767 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700768 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700769 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800770 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700771 mDispatchEnabled(false),
772 mDispatchFrozen(false),
773 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100774 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000775 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800776 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800777 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000778 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000779 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700780 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800781 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800782
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700783 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700784#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700785 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700786#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700787 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788}
789
790InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000791 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792
Prabir Pradhancef936d2021-07-21 16:17:52 +0000793 resetKeyRepeatLocked();
794 releasePendingEventLocked();
795 drainInboundQueueLocked();
796 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000798 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700799 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000800 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801 }
802}
803
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700804status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700805 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700806 return ALREADY_EXISTS;
807 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700808 mThread = std::make_unique<InputThread>(
809 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
810 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700811}
812
813status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700814 if (mThread && mThread->isCallingThread()) {
815 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700816 return INVALID_OPERATION;
817 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700818 mThread.reset();
819 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700820}
821
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700823 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800825 std::scoped_lock _l(mLock);
826 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827
828 // Run a dispatch loop if there are no pending commands.
829 // The dispatch loop might enqueue commands to run afterwards.
830 if (!haveCommandsLocked()) {
831 dispatchOnceInnerLocked(&nextWakeupTime);
832 }
833
834 // Run all pending commands if there are any.
835 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000836 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700837 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800839
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700840 // If we are still waiting for ack on some events,
841 // we might have to wake up earlier to check if an app is anr'ing.
842 const nsecs_t nextAnrCheck = processAnrsLocked();
843 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
844
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800845 // We are about to enter an infinitely long sleep, because we have no commands or
846 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700847 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800848 mDispatcherEnteredIdle.notify_all();
849 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 } // release lock
851
852 // Wait for callback or timeout or wake. (make sure we round up, not down)
853 nsecs_t currentTime = now();
854 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
855 mLooper->pollOnce(timeoutMillis);
856}
857
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700858/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500859 * Raise ANR if there is no focused window.
860 * Before the ANR is raised, do a final state check:
861 * 1. The currently focused application must be the same one we are waiting for.
862 * 2. Ensure we still don't have a focused window.
863 */
864void InputDispatcher::processNoFocusedWindowAnrLocked() {
865 // Check if the application that we are waiting for is still focused.
866 std::shared_ptr<InputApplicationHandle> focusedApplication =
867 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
868 if (focusedApplication == nullptr ||
869 focusedApplication->getApplicationToken() !=
870 mAwaitedFocusedApplication->getApplicationToken()) {
871 // Unexpected because we should have reset the ANR timer when focused application changed
872 ALOGE("Waited for a focused window, but focused application has already changed to %s",
873 focusedApplication->getName().c_str());
874 return; // The focused application has changed.
875 }
876
chaviw98318de2021-05-19 16:45:23 -0500877 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500878 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
879 if (focusedWindowHandle != nullptr) {
880 return; // We now have a focused window. No need for ANR.
881 }
882 onAnrLocked(mAwaitedFocusedApplication);
883}
884
885/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700886 * Check if any of the connections' wait queues have events that are too old.
887 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
888 * Return the time at which we should wake up next.
889 */
890nsecs_t InputDispatcher::processAnrsLocked() {
891 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700892 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700893 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
894 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
895 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500896 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700897 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500898 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700899 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700900 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500901 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700902 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
903 }
904 }
905
906 // Check if any connection ANRs are due
907 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
908 if (currentTime < nextAnrCheck) { // most likely scenario
909 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
910 }
911
912 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700913 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700914 if (connection == nullptr) {
915 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
916 return nextAnrCheck;
917 }
918 connection->responsive = false;
919 // Stop waking up for this unresponsive connection
920 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000921 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700922 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700923}
924
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800925std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700926 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800927 if (connection->monitor) {
928 return mMonitorDispatchingTimeout;
929 }
930 const sp<WindowInfoHandle> window =
931 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700932 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500933 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700934 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500935 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700936}
937
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
939 nsecs_t currentTime = now();
940
Jeff Browndc5992e2014-04-11 01:27:26 -0700941 // Reset the key repeat timer whenever normal dispatch is suspended while the
942 // device is in a non-interactive state. This is to ensure that we abort a key
943 // repeat if the device is just coming out of sleep.
944 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 resetKeyRepeatLocked();
946 }
947
948 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
949 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100950 if (DEBUG_FOCUS) {
951 ALOGD("Dispatch frozen. Waiting some more.");
952 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800953 return;
954 }
955
956 // Optimize latency of app switches.
957 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
958 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
959 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
960 if (mAppSwitchDueTime < *nextWakeupTime) {
961 *nextWakeupTime = mAppSwitchDueTime;
962 }
963
964 // Ready to start a new event.
965 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700966 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700967 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 if (isAppSwitchDue) {
969 // The inbound queue is empty so the app switch key we were waiting
970 // for will never arrive. Stop waiting for it.
971 resetPendingAppSwitchLocked(false);
972 isAppSwitchDue = false;
973 }
974
975 // Synthesize a key repeat if appropriate.
976 if (mKeyRepeatState.lastKeyEntry) {
977 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
978 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
979 } else {
980 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
981 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
982 }
983 }
984 }
985
986 // Nothing to do if there is no pending event.
987 if (!mPendingEvent) {
988 return;
989 }
990 } else {
991 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700992 mPendingEvent = mInboundQueue.front();
993 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 traceInboundQueueLengthLocked();
995 }
996
997 // Poke user activity for this event.
998 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700999 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
1002
1003 // Now we have an event to dispatch.
1004 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001005 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001007 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001009 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001011 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 }
1013
1014 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001015 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016 }
1017
1018 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001019 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001020 const ConfigurationChangedEntry& typedEntry =
1021 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001023 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001024 break;
1025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001027 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001028 const DeviceResetEntry& typedEntry =
1029 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001031 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001032 break;
1033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001034
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001035 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001036 std::shared_ptr<FocusEntry> typedEntry =
1037 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001038 dispatchFocusLocked(currentTime, typedEntry);
1039 done = true;
1040 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1041 break;
1042 }
1043
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001044 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1045 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1046 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1047 done = true;
1048 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1049 break;
1050 }
1051
Prabir Pradhan99987712020-11-10 18:43:05 -08001052 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1053 const auto typedEntry =
1054 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1055 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1056 done = true;
1057 break;
1058 }
1059
arthurhungb89ccb02020-12-30 16:19:01 +08001060 case EventEntry::Type::DRAG: {
1061 std::shared_ptr<DragEntry> typedEntry =
1062 std::static_pointer_cast<DragEntry>(mPendingEvent);
1063 dispatchDragLocked(currentTime, typedEntry);
1064 done = true;
1065 break;
1066 }
1067
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001068 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001069 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001070 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001071 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 resetPendingAppSwitchLocked(true);
1073 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001074 } else if (dropReason == DropReason::NOT_DROPPED) {
1075 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001076 }
1077 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001078 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001079 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001080 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001081 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1082 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001083 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001084 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001085 break;
1086 }
1087
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001088 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001089 std::shared_ptr<MotionEntry> motionEntry =
1090 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001091 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1092 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001094 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001095 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001096 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001097 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1098 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001099 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001100 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 }
Chris Yef59a2f42020-10-16 12:55:26 -07001103
1104 case EventEntry::Type::SENSOR: {
1105 std::shared_ptr<SensorEntry> sensorEntry =
1106 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1107 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1108 dropReason = DropReason::APP_SWITCH;
1109 }
1110 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1111 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1112 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1113 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1114 dropReason = DropReason::STALE;
1115 }
1116 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1117 done = true;
1118 break;
1119 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 }
1121
1122 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001123 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001124 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 }
Michael Wright3a981722015-06-10 15:26:13 +01001126 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001127
1128 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001129 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 }
1131}
1132
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001133bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1134 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1135}
1136
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001137/**
1138 * Return true if the events preceding this incoming motion event should be dropped
1139 * Return false otherwise (the default behaviour)
1140 */
1141bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001142 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001143 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001144
1145 // Optimize case where the current application is unresponsive and the user
1146 // decides to touch a window in a different application.
1147 // If the application takes too long to catch up then we drop all events preceding
1148 // the touch into the other window.
1149 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001150 const int32_t displayId = motionEntry.displayId;
1151 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001152 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001153
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001154 sp<WindowInfoHandle> touchedWindowHandle =
1155 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001156 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001157 touchedWindowHandle->getApplicationToken() !=
1158 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001159 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001160 ALOGI("Pruning input queue because user touched a different application while waiting "
1161 "for %s",
1162 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001163 return true;
1164 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001165
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001166 // Alternatively, maybe there's a spy window that could handle this event.
1167 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1168 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1169 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001170 const std::shared_ptr<Connection> connection =
1171 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001172 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001173 // This spy window could take more input. Drop all events preceding this
1174 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001175 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001176 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001177 mAwaitedFocusedApplication->getName().c_str());
1178 return true;
1179 }
1180 }
1181 }
1182
1183 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1184 // yet been processed by some connections, the dispatcher will wait for these motion
1185 // events to be processed before dispatching the key event. This is because these motion events
1186 // may cause a new window to be launched, which the user might expect to receive focus.
1187 // To prevent waiting forever for such events, just send the key to the currently focused window
1188 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1189 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1190 "just send the pending key event to the focused window.");
1191 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001192 }
1193 return false;
1194}
1195
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001196bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001197 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001198 mInboundQueue.push_back(std::move(newEntry));
1199 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 traceInboundQueueLengthLocked();
1201
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001202 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001203 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001204 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1205 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001206 // Optimize app switch latency.
1207 // If the application takes too long to catch up then we drop all events preceding
1208 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001209 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001210 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001211 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001212 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001213 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001215 if (DEBUG_APP_SWITCH) {
1216 ALOGD("App switch is pending!");
1217 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001218 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001219 mAppSwitchSawKeyDown = false;
1220 needWake = true;
1221 }
1222 }
1223 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001224
1225 // If a new up event comes in, and the pending event with same key code has been asked
1226 // to try again later because of the policy. We have to reset the intercept key wake up
1227 // time for it may have been handled in the policy and could be dropped.
1228 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1229 mPendingEvent->type == EventEntry::Type::KEY) {
1230 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1231 if (pendingKey.keyCode == keyEntry.keyCode &&
1232 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001233 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1234 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001235 pendingKey.interceptKeyWakeupTime = 0;
1236 needWake = true;
1237 }
1238 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239 break;
1240 }
1241
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001242 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001243 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1244 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001245 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1246 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001247 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001249 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001251 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001252 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1253 break;
1254 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001255 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001256 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001257 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001258 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001259 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1260 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001261 // nothing to do
1262 break;
1263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 }
1265
1266 return needWake;
1267}
1268
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001269void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001270 // Do not store sensor event in recent queue to avoid flooding the queue.
1271 if (entry->type != EventEntry::Type::SENSOR) {
1272 mRecentQueue.push_back(entry);
1273 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001274 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001275 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 }
1277}
1278
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001279sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1280 bool isStylus,
1281 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001283 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001284 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001285 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001286 continue;
1287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001289 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001290 if (!info.isSpy() &&
1291 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001292 return windowHandle;
1293 }
1294 }
1295 return nullptr;
1296}
1297
1298std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001299 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001300 if (touchedWindow == nullptr) {
1301 return {};
1302 }
1303 // Traverse windows from front to back until we encounter the touched window.
1304 std::vector<InputTarget> outsideTargets;
1305 const auto& windowHandles = getWindowHandlesLocked(displayId);
1306 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1307 if (windowHandle == touchedWindow) {
1308 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1309 // below the touched window will not get ACTION_OUTSIDE event.
1310 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001311 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001312
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001313 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001314 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001315 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1316 pointerIds.set(pointerId);
1317 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE, pointerIds,
1318 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319 }
1320 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001321 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322}
1323
Prabir Pradhand65552b2021-10-07 11:23:50 -07001324std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001325 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001326 // Traverse windows from front to back and gather the touched spy windows.
1327 std::vector<sp<WindowInfoHandle>> spyWindows;
1328 const auto& windowHandles = getWindowHandlesLocked(displayId);
1329 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1330 const WindowInfo& info = *windowHandle->getInfo();
1331
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001332 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001333 continue;
1334 }
1335 if (!info.isSpy()) {
1336 // The first touched non-spy window was found, so return the spy windows touched so far.
1337 return spyWindows;
1338 }
1339 spyWindows.push_back(windowHandle);
1340 }
1341 return spyWindows;
1342}
1343
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001344void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 const char* reason;
1346 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001347 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001348 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001349 ALOGD("Dropped event because policy consumed it.");
1350 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001351 reason = "inbound event was dropped because the policy consumed it";
1352 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001353 case DropReason::DISABLED:
1354 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001355 ALOGI("Dropped event because input dispatch is disabled.");
1356 }
1357 reason = "inbound event was dropped because input dispatch is disabled";
1358 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001359 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001360 ALOGI("Dropped event because of pending overdue app switch.");
1361 reason = "inbound event was dropped because of pending overdue app switch";
1362 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001363 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001364 ALOGI("Dropped event because the current application is not responding and the user "
1365 "has started interacting with a different application.");
1366 reason = "inbound event was dropped because the current application is not responding "
1367 "and the user has started interacting with a different application";
1368 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001369 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001370 ALOGI("Dropped event because it is stale.");
1371 reason = "inbound event was dropped because it is stale";
1372 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001373 case DropReason::NO_POINTER_CAPTURE:
1374 ALOGI("Dropped event because there is no window with Pointer Capture.");
1375 reason = "inbound event was dropped because there is no window with Pointer Capture";
1376 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001377 case DropReason::NOT_DROPPED: {
1378 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001379 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001380 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381 }
1382
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001383 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001384 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001385 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001387 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001389 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001390 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1391 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001392 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001393 synthesizeCancelationEventsForAllConnectionsLocked(options);
1394 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001395 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1396 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001397 synthesizeCancelationEventsForAllConnectionsLocked(options);
1398 }
1399 break;
1400 }
Chris Yef59a2f42020-10-16 12:55:26 -07001401 case EventEntry::Type::SENSOR: {
1402 break;
1403 }
arthurhungb89ccb02020-12-30 16:19:01 +08001404 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1405 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001406 break;
1407 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001408 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001409 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001410 case EventEntry::Type::CONFIGURATION_CHANGED:
1411 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001412 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001413 break;
1414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 }
1416}
1417
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001418static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001419 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1420 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421}
1422
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001423bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1424 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1425 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1426 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427}
1428
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001429bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001430 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431}
1432
1433void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001434 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001436 if (DEBUG_APP_SWITCH) {
1437 if (handled) {
1438 ALOGD("App switch has arrived.");
1439 } else {
1440 ALOGD("App switch was abandoned.");
1441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443}
1444
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001446 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447}
1448
Prabir Pradhancef936d2021-07-21 16:17:52 +00001449bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001450 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001451 return false;
1452 }
1453
1454 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001455 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001456 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001457 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1458 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001459 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 return true;
1461}
1462
Prabir Pradhancef936d2021-07-21 16:17:52 +00001463void InputDispatcher::postCommandLocked(Command&& command) {
1464 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465}
1466
1467void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001468 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001469 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001470 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001471 releaseInboundEventLocked(entry);
1472 }
1473 traceInboundQueueLengthLocked();
1474}
1475
1476void InputDispatcher::releasePendingEventLocked() {
1477 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001479 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 }
1481}
1482
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001483void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001485 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001486 if (DEBUG_DISPATCH_CYCLE) {
1487 ALOGD("Injected inbound event was dropped.");
1488 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001489 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 }
1491 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001492 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 }
1494 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495}
1496
1497void InputDispatcher::resetKeyRepeatLocked() {
1498 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001499 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 }
1501}
1502
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001503std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1504 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505
Michael Wright2e732952014-09-24 13:26:59 -07001506 uint32_t policyFlags = entry->policyFlags &
1507 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001509 std::shared_ptr<KeyEntry> newEntry =
1510 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1511 entry->source, entry->displayId, policyFlags, entry->action,
1512 entry->flags, entry->keyCode, entry->scanCode,
1513 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001515 newEntry->syntheticRepeat = true;
1516 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001518 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519}
1520
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001521bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001522 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001523 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1524 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526
1527 // Reset key repeating in case a keyboard device was added or removed or something.
1528 resetKeyRepeatLocked();
1529
1530 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001531 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1532 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001533 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001534 };
1535 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 return true;
1537}
1538
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001539bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1540 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001541 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1542 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1543 entry.deviceId);
1544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545
liushenxiang42232912021-05-21 20:24:09 +08001546 // Reset key repeating in case a keyboard device was disabled or enabled.
1547 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1548 resetKeyRepeatLocked();
1549 }
1550
Michael Wrightfb04fd52022-11-24 22:31:11 +00001551 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001552 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001554
1555 // Remove all active pointers from this device
1556 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1557 touchState.removeAllPointersForDevice(entry.deviceId);
1558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001559 return true;
1560}
1561
Vishnu Nairad321cd2020-08-20 16:40:21 -07001562void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001563 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001564 if (mPendingEvent != nullptr) {
1565 // Move the pending event to the front of the queue. This will give the chance
1566 // for the pending event to get dispatched to the newly focused window
1567 mInboundQueue.push_front(mPendingEvent);
1568 mPendingEvent = nullptr;
1569 }
1570
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001571 std::unique_ptr<FocusEntry> focusEntry =
1572 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1573 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001574
1575 // This event should go to the front of the queue, but behind all other focus events
1576 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001577 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001578 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001579 [](const std::shared_ptr<EventEntry>& event) {
1580 return event->type == EventEntry::Type::FOCUS;
1581 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001582
1583 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001584 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001585}
1586
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001587void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001588 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001589 if (channel == nullptr) {
1590 return; // Window has gone away
1591 }
1592 InputTarget target;
1593 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001594 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001595 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001596 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1597 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001598 std::string reason = std::string("reason=").append(entry->reason);
1599 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001600 dispatchEventLocked(currentTime, entry, {target});
1601}
1602
Prabir Pradhan99987712020-11-10 18:43:05 -08001603void InputDispatcher::dispatchPointerCaptureChangedLocked(
1604 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1605 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001606 dropReason = DropReason::NOT_DROPPED;
1607
Prabir Pradhan99987712020-11-10 18:43:05 -08001608 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001609 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001610
1611 if (entry->pointerCaptureRequest.enable) {
1612 // Enable Pointer Capture.
1613 if (haveWindowWithPointerCapture &&
1614 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001615 // This can happen if pointer capture is disabled and re-enabled before we notify the
1616 // app of the state change, so there is no need to notify the app.
1617 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1618 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001619 }
1620 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001621 // This can happen if a window requests capture and immediately releases capture.
1622 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001623 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001624 return;
1625 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001626 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1627 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1628 return;
1629 }
1630
Vishnu Nairc519ff72021-01-21 08:23:08 -08001631 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001632 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1633 mWindowTokenWithPointerCapture = token;
1634 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001635 // Disable Pointer Capture.
1636 // We do not check if the sequence number matches for requests to disable Pointer Capture
1637 // for two reasons:
1638 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1639 // to disable capture with the same sequence number: one generated by
1640 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1641 // Capture being disabled in InputReader.
1642 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1643 // actual Pointer Capture state that affects events being generated by input devices is
1644 // in InputReader.
1645 if (!haveWindowWithPointerCapture) {
1646 // Pointer capture was already forcefully disabled because of focus change.
1647 dropReason = DropReason::NOT_DROPPED;
1648 return;
1649 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001650 token = mWindowTokenWithPointerCapture;
1651 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001652 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001653 setPointerCaptureLocked(false);
1654 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001655 }
1656
1657 auto channel = getInputChannelLocked(token);
1658 if (channel == nullptr) {
1659 // Window has gone away, clean up Pointer Capture state.
1660 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001661 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001662 setPointerCaptureLocked(false);
1663 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001664 return;
1665 }
1666 InputTarget target;
1667 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001668 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001669 entry->dispatchInProgress = true;
1670 dispatchEventLocked(currentTime, entry, {target});
1671
1672 dropReason = DropReason::NOT_DROPPED;
1673}
1674
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001675void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1676 const std::shared_ptr<TouchModeEntry>& entry) {
1677 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001678 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001679 if (windowHandles.empty()) {
1680 return;
1681 }
1682 const std::vector<InputTarget> inputTargets =
1683 getInputTargetsFromWindowHandlesLocked(windowHandles);
1684 if (inputTargets.empty()) {
1685 return;
1686 }
1687 entry->dispatchInProgress = true;
1688 dispatchEventLocked(currentTime, entry, inputTargets);
1689}
1690
1691std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1692 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1693 std::vector<InputTarget> inputTargets;
1694 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001695 const sp<IBinder>& token = handle->getToken();
1696 if (token == nullptr) {
1697 continue;
1698 }
1699 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1700 if (channel == nullptr) {
1701 continue; // Window has gone away
1702 }
1703 InputTarget target;
1704 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001705 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001706 inputTargets.push_back(target);
1707 }
1708 return inputTargets;
1709}
1710
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001711bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001712 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001714 if (!entry->dispatchInProgress) {
1715 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1716 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1717 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1718 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001719 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 // We have seen two identical key downs in a row which indicates that the device
1721 // driver is automatically generating key repeats itself. We take note of the
1722 // repeat here, but we disable our own next key repeat timer since it is clear that
1723 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001724 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1725 // Make sure we don't get key down from a different device. If a different
1726 // device Id has same key pressed down, the new device Id will replace the
1727 // current one to hold the key repeat with repeat count reset.
1728 // In the future when got a KEY_UP on the device id, drop it and do not
1729 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1731 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001732 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 } else {
1734 // Not a repeat. Save key down state in case we do see a repeat later.
1735 resetKeyRepeatLocked();
1736 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1737 }
1738 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001739 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1740 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001741 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001742 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001743 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1744 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001745 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 resetKeyRepeatLocked();
1747 }
1748
1749 if (entry->repeatCount == 1) {
1750 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1751 } else {
1752 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1753 }
1754
1755 entry->dispatchInProgress = true;
1756
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001757 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001758 }
1759
1760 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001761 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 if (currentTime < entry->interceptKeyWakeupTime) {
1763 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1764 *nextWakeupTime = entry->interceptKeyWakeupTime;
1765 }
1766 return false; // wait until next wakeup
1767 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001768 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769 entry->interceptKeyWakeupTime = 0;
1770 }
1771
1772 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001773 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001775 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001776 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001777
1778 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1779 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1780 };
1781 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001782 // Poke user activity for keys not passed to user
1783 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 return false; // wait for the command to run
1785 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001786 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001788 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001789 if (*dropReason == DropReason::NOT_DROPPED) {
1790 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 }
1792 }
1793
1794 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001795 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001796 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001797 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1798 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001799 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001800 // Poke user activity for undispatched keys
1801 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 return true;
1803 }
1804
1805 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001806 InputEventInjectionResult injectionResult;
1807 sp<WindowInfoHandle> focusedWindow =
1808 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1809 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001810 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811 return false;
1812 }
1813
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001814 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001815 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 return true;
1817 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001818 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1819
1820 std::vector<InputTarget> inputTargets;
1821 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001822 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001823 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001825 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001826 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827
1828 // Dispatch the key.
1829 dispatchEventLocked(currentTime, entry, inputTargets);
1830 return true;
1831}
1832
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001833void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001834 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1835 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1836 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1837 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1838 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1839 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1840 entry.metaState, entry.repeatCount, entry.downTime);
1841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842}
1843
Prabir Pradhancef936d2021-07-21 16:17:52 +00001844void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1845 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001846 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001847 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1848 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1849 "source=0x%x, sensorType=%s",
1850 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001851 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001852 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001853 auto command = [this, entry]() REQUIRES(mLock) {
1854 scoped_unlock unlock(mLock);
1855
1856 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001857 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001858 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001859 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1860 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001861 };
1862 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001863}
1864
1865bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001866 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1867 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001868 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001869 }
Chris Yef59a2f42020-10-16 12:55:26 -07001870 { // acquire lock
1871 std::scoped_lock _l(mLock);
1872
1873 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1874 std::shared_ptr<EventEntry> entry = *it;
1875 if (entry->type == EventEntry::Type::SENSOR) {
1876 it = mInboundQueue.erase(it);
1877 releaseInboundEventLocked(entry);
1878 }
1879 }
1880 }
1881 return true;
1882}
1883
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001884bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001885 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001886 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001887 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001888 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 entry->dispatchInProgress = true;
1890
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001891 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 }
1893
1894 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001895 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001896 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001897 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1898 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 return true;
1900 }
1901
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001902 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903
1904 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001905 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906
1907 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001908 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 if (isPointerEvent) {
1910 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001911
1912 if (mDragState &&
1913 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1914 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1915 pilferPointersLocked(mDragState->dragWindow->getToken());
1916 }
1917
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001918 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001919 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001920 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001921 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1922 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 } else {
1924 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001925 sp<WindowInfoHandle> focusedWindow =
1926 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1927 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1928 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1929 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001930 InputTarget::Flags::FOREGROUND |
1931 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001932 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 return false;
1937 }
1938
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001939 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001940 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001941 return true;
1942 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001943 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001944 CancelationOptions::Mode mode(
1945 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1946 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001947 CancelationOptions options(mode, "input event injection failed");
1948 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949 return true;
1950 }
1951
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001952 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001953 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954
1955 // Dispatch the motion.
1956 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001957 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001958 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 synthesizeCancelationEventsForAllConnectionsLocked(options);
1960 }
1961 dispatchEventLocked(currentTime, entry, inputTargets);
1962 return true;
1963}
1964
chaviw98318de2021-05-19 16:45:23 -05001965void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001966 bool isExiting, const int32_t rawX,
1967 const int32_t rawY) {
1968 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001969 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001970 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1971 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001972
1973 enqueueInboundEventLocked(std::move(dragEntry));
1974}
1975
1976void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1977 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1978 if (channel == nullptr) {
1979 return; // Window has gone away
1980 }
1981 InputTarget target;
1982 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001983 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001984 entry->dispatchInProgress = true;
1985 dispatchEventLocked(currentTime, entry, {target});
1986}
1987
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001988void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001989 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001990 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001991 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001992 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001993 "metaState=0x%x, buttonState=0x%x,"
1994 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001995 prefix, entry.eventTime, entry.deviceId,
1996 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1997 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1998 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1999 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002001 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002002 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002003 "x=%f, y=%f, pressure=%f, size=%f, "
2004 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2005 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002006 i, entry.pointerProperties[i].id,
2007 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002008 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2009 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2010 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2011 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2012 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2013 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2014 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2015 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2016 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019}
2020
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002021void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
2022 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002023 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002024 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002025 if (DEBUG_DISPATCH_CYCLE) {
2026 ALOGD("dispatchEventToCurrentInputTargets");
2027 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002029 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002030
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2032
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002033 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002035 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002036 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002037 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002038 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002039 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002041 if (DEBUG_FOCUS) {
2042 ALOGD("Dropping event delivery to target with channel '%s' because it "
2043 "is no longer registered with the input dispatcher.",
2044 inputTarget.inputChannel->getName().c_str());
2045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002046 }
2047 }
2048}
2049
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002050void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002051 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2052 // If the policy decides to close the app, we will get a channel removal event via
2053 // unregisterInputChannel, and will clean up the connection that way. We are already not
2054 // sending new pointers to the connection when it blocked, but focused events will continue to
2055 // pile up.
2056 ALOGW("Canceling events for %s because it is unresponsive",
2057 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002058 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002059 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002060 "application not responding");
2061 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 }
2063}
2064
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002065void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002066 if (DEBUG_FOCUS) {
2067 ALOGD("Resetting ANR timeouts.");
2068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069
2070 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002071 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002072 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073}
2074
Tiger Huang721e26f2018-07-24 22:26:19 +08002075/**
2076 * Get the display id that the given event should go to. If this event specifies a valid display id,
2077 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2078 * Focused display is the display that the user most recently interacted with.
2079 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002080int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002081 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002082 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002083 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002084 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2085 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002086 break;
2087 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002088 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002089 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2090 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002091 break;
2092 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002093 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002094 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002095 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002096 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002097 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002098 case EventEntry::Type::SENSOR:
2099 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002100 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002101 return ADISPLAY_ID_NONE;
2102 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002103 }
2104 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2105}
2106
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2108 const char* focusedWindowName) {
2109 if (mAnrTracker.empty()) {
2110 // already processed all events that we waited for
2111 mKeyIsWaitingForEventsTimeout = std::nullopt;
2112 return false;
2113 }
2114
2115 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2116 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002117 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002118 mKeyIsWaitingForEventsTimeout = currentTime +
2119 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2120 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002121 return true;
2122 }
2123
2124 // We still have pending events, and already started the timer
2125 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2126 return true; // Still waiting
2127 }
2128
2129 // Waited too long, and some connection still hasn't processed all motions
2130 // Just send the key to the focused window
2131 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2132 focusedWindowName);
2133 mKeyIsWaitingForEventsTimeout = std::nullopt;
2134 return false;
2135}
2136
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002137sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2138 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2139 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002140 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002141 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142
Tiger Huang721e26f2018-07-24 22:26:19 +08002143 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002144 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002145 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002146 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2147
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 // If there is no currently focused window and no focused application
2149 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002150 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2151 ALOGI("Dropping %s event because there is no focused window or focused application in "
2152 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002153 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002154 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
2156
Vishnu Nair062a8672021-09-03 16:07:44 -07002157 // Drop key events if requested by input feature
2158 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002159 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002160 }
2161
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002162 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2163 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2164 // start interacting with another application via touch (app switch). This code can be removed
2165 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2166 // an app is expected to have a focused window.
2167 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2168 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2169 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002170 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2171 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2172 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002173 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002174 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002175 ALOGW("Waiting because no window has focus but %s may eventually add a "
2176 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002177 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002178 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002179 outInjectionResult = InputEventInjectionResult::PENDING;
2180 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002181 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2182 // Already raised ANR. Drop the event
2183 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002184 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002185 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002186 } else {
2187 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002188 outInjectionResult = InputEventInjectionResult::PENDING;
2189 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002190 }
2191 }
2192
2193 // we have a valid, non-null focused window
2194 resetNoFocusedWindowTimeoutLocked();
2195
Prabir Pradhan5735a322022-04-11 17:23:34 +00002196 // Verify targeted injection.
2197 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2198 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002199 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2200 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 }
2202
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002203 if (focusedWindowHandle->getInfo()->inputConfig.test(
2204 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002205 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002206 outInjectionResult = InputEventInjectionResult::PENDING;
2207 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002208 }
2209
2210 // If the event is a key event, then we must wait for all previous events to
2211 // complete before delivering it because previous events may have the
2212 // side-effect of transferring focus to a different window and we want to
2213 // ensure that the following keys are sent to the new window.
2214 //
2215 // Suppose the user touches a button in a window then immediately presses "A".
2216 // If the button causes a pop-up window to appear then we want to ensure that
2217 // the "A" key is delivered to the new pop-up window. This is because users
2218 // often anticipate pending UI changes when typing on a keyboard.
2219 // To obtain this behavior, we must serialize key events with respect to all
2220 // prior input events.
2221 if (entry.type == EventEntry::Type::KEY) {
2222 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2223 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002224 outInjectionResult = InputEventInjectionResult::PENDING;
2225 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 }
2228
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002229 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2230 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231}
2232
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002233/**
2234 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2235 * that are currently unresponsive.
2236 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002237std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2238 const std::vector<Monitor>& monitors) const {
2239 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002240 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002241 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002242 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002243 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002244 if (connection == nullptr) {
2245 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002246 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002247 return false;
2248 }
2249 if (!connection->responsive) {
2250 ALOGW("Unresponsive monitor %s will not get the new gesture",
2251 connection->inputChannel->getName().c_str());
2252 return false;
2253 }
2254 return true;
2255 });
2256 return responsiveMonitors;
2257}
2258
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002259std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002260 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2261 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002262 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002264 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 // For security reasons, we defer updating the touch state until we are sure that
2266 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002267 const int32_t displayId = entry.displayId;
2268 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002269 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270
2271 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002272 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002273
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002274 // Copy current touch state into tempTouchState.
2275 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2276 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002277 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002278 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002279 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2280 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002281 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002282 }
2283
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002284 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002285 bool switchedDevice = false;
2286 if (oldState != nullptr) {
2287 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2288 const bool anotherDeviceIsActive =
2289 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2290 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002291 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002292
2293 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2294 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2295 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002296 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2297 // touchable windows.
2298 const bool wasDown = oldState != nullptr && oldState->isDown();
2299 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2300 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002301 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2302 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2303 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002304 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002305
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002306 // If pointers are already down, let's finish the current gesture and ignore the new events
2307 // from another device. However, if the new event is a down event, let's cancel the current
2308 // touch and let the new one take over.
2309 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002310 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002311 << " is already down in display " << displayId << ": " << entry.getDescription();
2312 // TODO(b/211379801): test multiple simultaneous input streams.
2313 outInjectionResult = InputEventInjectionResult::FAILED;
2314 return {}; // wrong device
2315 }
2316
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002318 // If a new gesture is starting, clear the touch state completely.
2319 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002321 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002322 ALOGI("Dropping move event because a pointer for a different device is already active "
2323 "in display %" PRId32,
2324 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002325 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002326 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002327 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 }
2329
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002330 if (isHoverAction) {
2331 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2332 // all of the existing hovering pointers and recompute.
2333 tempTouchState.clearHoveringPointers();
2334 }
2335
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2337 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002338 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002339 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002340 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002341 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2342 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002343 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002344 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002345 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002346
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002347 if (isDown) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002348 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002351 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002352 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002354 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002355 }
2356
Prabir Pradhan5735a322022-04-11 17:23:34 +00002357 // Verify targeted injection.
2358 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2359 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002360 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002361 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002362 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002363 }
2364
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002365 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002366 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002367 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2368 // New window supports splitting, but we should never split mouse events.
2369 isSplit = !isFromMouse;
2370 } else if (isSplit) {
2371 // New window does not support splitting but we have already split events.
2372 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002373 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2374 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002375 newTouchedWindowHandle = nullptr;
2376 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002377 } else {
2378 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002379 // be delivered to a new window which supports split touch. Pointers from a mouse device
2380 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002381 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002382 }
2383
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002384 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002385 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002386 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002387 // Process the foreground window first so that it is the first to receive the event.
2388 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002389 }
2390
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002391 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002392 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2393 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002394 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002395 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002396 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002397 }
2398
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002399 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002400 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002401 continue;
2402 }
2403
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002404 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2405 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002406 // The "windowHandle" is the target of this hovering pointer.
2407 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002408 }
2409
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002410 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002411 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002412
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002413 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2414 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002415 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002416 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002417
2418 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002419 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002420 }
2421 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002422 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002423 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002424 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002425 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002426
2427 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002428 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002429 if (!isHoverAction) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002430 pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002431 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002432
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002433 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2434 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2435
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002436 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2437 // still add a window to the touch state. We should avoid doing that, but some of the
2438 // later checks ("at least one foreground window") rely on this in order to dispatch
2439 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002440 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002441 isDownOrPointerDown
2442 ? std::make_optional(entry.eventTime)
2443 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002444
2445 // If this is the pointer going down and the touched window has a wallpaper
2446 // then also add the touched wallpaper windows so they are locked in for the duration
2447 // of the touch gesture.
2448 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2449 // engine only supports touch events. We would need to add a mechanism similar
2450 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002451 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002452 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2453 windowHandle->getInfo()->inputConfig.test(
2454 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2455 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2456 if (wallpaper != nullptr) {
2457 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2458 InputTarget::Flags::WINDOW_IS_OBSCURED |
2459 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2460 InputTarget::Flags::DISPATCH_AS_IS;
2461 if (isSplit) {
2462 wallpaperFlags |= InputTarget::Flags::SPLIT;
2463 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002464 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2465 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002466 }
2467 }
2468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002470
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002471 // If a window is already pilfering some pointers, give it this new pointer as well and
2472 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2473 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002474 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002475 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2476 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002477 // This window is already pilfering some pointers, and this new pointer is also
2478 // going to it. Therefore, take over this pointer and don't give it to anyone
2479 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002480 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002481 }
2482 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002483
2484 // Restrict all pilfered pointers to the pilfering windows.
2485 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 } else {
2487 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2488
2489 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002490 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002491 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2492 "dropped the pointer down event in display "
2493 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002494 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002495 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 }
2497
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002498 // If the pointer is not currently hovering, then ignore the event.
2499 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2500 const int32_t pointerId = entry.pointerProperties[0].id;
2501 if (oldState == nullptr ||
2502 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2503 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2504 "display "
2505 << displayId << ": " << entry.getDescription();
2506 outInjectionResult = InputEventInjectionResult::FAILED;
2507 return {};
2508 }
2509 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2510 }
2511
arthurhung6d4bed92021-03-17 11:59:33 +08002512 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002513
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002515 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002516 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002517 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002518 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002519 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002520 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002521 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002522 sp<WindowInfoHandle> newTouchedWindowHandle =
2523 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002524
Prabir Pradhan5735a322022-04-11 17:23:34 +00002525 // Verify targeted injection.
2526 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2527 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002528 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002529 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002530 }
2531
Vishnu Nair062a8672021-09-03 16:07:44 -07002532 // Drop touch events if requested by input feature
2533 if (newTouchedWindowHandle != nullptr &&
2534 shouldDropInput(entry, newTouchedWindowHandle)) {
2535 newTouchedWindowHandle = nullptr;
2536 }
2537
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002538 if (newTouchedWindowHandle != nullptr &&
2539 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002540 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2541 oldTouchedWindowHandle->getName().c_str(),
2542 newTouchedWindowHandle->getName().c_str(), displayId);
2543
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002545 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002546 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002547 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002548
2549 const TouchedWindow& touchedWindow =
2550 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2551 addWindowTargetLocked(oldTouchedWindowHandle,
2552 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002553 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554
2555 // Make a slippery entrance into the new window.
2556 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002557 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558 }
2559
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002560 ftl::Flags<InputTarget::Flags> targetFlags =
2561 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002562 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002563 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002566 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567 }
2568 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002569 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002570 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002571 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 }
2573
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002574 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2575 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002576
2577 // Check if the wallpaper window should deliver the corresponding event.
2578 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002579 tempTouchState, entry.deviceId, pointerId, targets);
2580 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2581 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 }
2583 }
Arthur Hung96483742022-11-15 03:30:48 +00002584
2585 // Update the pointerIds for non-splittable when it received pointer down.
2586 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2587 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002588 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002589 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2590 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2591 // Ignore drag window for it should just track one pointer.
2592 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2593 continue;
2594 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002595 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2596 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2597 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002598 }
2599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 }
2601
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002602 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002603 {
2604 std::vector<TouchedWindow> hoveringWindows =
2605 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2606 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002607 std::optional<InputTarget> target =
2608 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002609 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002610 if (!target) {
2611 continue;
2612 }
2613 // Hardcode to single hovering pointer for now.
2614 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2615 pointerIds.set(entry.pointerProperties[0].id);
2616 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2617 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620
Prabir Pradhan5735a322022-04-11 17:23:34 +00002621 // Ensure that all touched windows are valid for injection.
2622 if (entry.injectionState != nullptr) {
2623 std::string errs;
2624 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002625 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2626 if (err) errs += "\n - " + *err;
2627 }
2628 if (!errs.empty()) {
2629 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002630 "%s:%s",
2631 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002632 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002633 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002634 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002635 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002636
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002637 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2638 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002640 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002641 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002642 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002643 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002644 for (InputTarget& target : targets) {
2645 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2646 sp<WindowInfoHandle> targetWindow =
2647 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2648 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2649 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002650 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 }
2652 }
2653 }
2654 }
2655
Harry Cuttsb166c002023-05-09 13:06:05 +00002656 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2657 // only want the system UI to handle these gestures.
2658 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2659 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2660 if (isTouchpadNavGesture) {
2661 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2662 }
2663
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002664 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002665 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002666 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2667 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002668 // Windows with hovering pointers are getting persisted inside TouchState.
2669 // Do not send this event to those windows.
2670 continue;
2671 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002672
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002673 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002674 touchedWindow.getTouchingPointers(entry.deviceId),
2675 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002676 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002677
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002678 // During targeted injection, only allow owned targets to receive events
2679 std::erase_if(targets, [&](const InputTarget& target) {
2680 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2681 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2682 if (err) {
2683 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2684 << ": " << (*err);
2685 return true;
2686 }
2687 return false;
2688 });
2689
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002690 if (targets.empty()) {
2691 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2692 outInjectionResult = InputEventInjectionResult::FAILED;
2693 return {};
2694 }
2695
2696 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2697 // window that is actually receiving the entire gesture.
2698 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2699 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2700 })) {
2701 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2702 << entry.getDescription();
2703 outInjectionResult = InputEventInjectionResult::FAILED;
2704 return {};
2705 }
2706
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002707 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002708 // Drop the outside or hover touch windows since we will not care about them
2709 // in the next iteration.
2710 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002713 if (switchedDevice) {
2714 if (DEBUG_FOCUS) {
2715 ALOGD("Conflicting pointer actions: Switched to a different device.");
2716 }
2717 *outConflictingPointerActions = true;
2718 }
2719
2720 if (isHoverAction) {
2721 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002722 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002723 ALOGD_IF(DEBUG_FOCUS,
2724 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002725 *outConflictingPointerActions = true;
2726 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002727 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2728 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002729 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002730 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002731 // All pointers up or canceled.
2732 tempTouchState.reset();
2733 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2734 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002735 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2736 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002737 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002738 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002739 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2740 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002741 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2742 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2743 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 }
2745
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002746 // Save changes unless the action was scroll in which case the temporary touch
2747 // state was only valid for this one action.
2748 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002749 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002750 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002751 mTouchStatesByDisplay[displayId] = tempTouchState;
2752 } else {
2753 mTouchStatesByDisplay.erase(displayId);
2754 }
2755 }
2756
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002757 if (tempTouchState.windows.empty()) {
2758 mTouchStatesByDisplay.erase(displayId);
2759 }
2760
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002761 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762}
2763
arthurhung6d4bed92021-03-17 11:59:33 +08002764void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002765 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2766 // have an explicit reason to support it.
2767 constexpr bool isStylus = false;
2768
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002769 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002770 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002771 if (dropWindow) {
2772 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002773 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002774 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002775 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002776 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002777 }
2778 mDragState.reset();
2779}
2780
2781void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002782 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002783 return;
2784 }
2785
arthurhung6d4bed92021-03-17 11:59:33 +08002786 if (!mDragState->isStartDrag) {
2787 mDragState->isStartDrag = true;
2788 mDragState->isStylusButtonDownAtStart =
2789 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2790 }
2791
Arthur Hung54745652022-04-20 07:17:41 +00002792 // Find the pointer index by id.
2793 int32_t pointerIndex = 0;
2794 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2795 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2796 if (pointerProperties.id == mDragState->pointerId) {
2797 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002798 }
Arthur Hung54745652022-04-20 07:17:41 +00002799 }
arthurhung6d4bed92021-03-17 11:59:33 +08002800
Arthur Hung54745652022-04-20 07:17:41 +00002801 if (uint32_t(pointerIndex) == entry.pointerCount) {
2802 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002803 }
2804
2805 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2806 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2807 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2808
2809 switch (maskedAction) {
2810 case AMOTION_EVENT_ACTION_MOVE: {
2811 // Handle the special case : stylus button no longer pressed.
2812 bool isStylusButtonDown =
2813 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2814 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2815 finishDragAndDrop(entry.displayId, x, y);
2816 return;
2817 }
2818
2819 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2820 // until we have an explicit reason to support it.
2821 constexpr bool isStylus = false;
2822
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002823 sp<WindowInfoHandle> hoverWindowHandle =
2824 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2825 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002826 // enqueue drag exit if needed.
2827 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2828 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2829 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002830 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002831 y);
2832 }
2833 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2834 }
2835 // enqueue drag location if needed.
2836 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002837 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002838 }
2839 break;
2840 }
2841
2842 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002843 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002844 break;
2845 }
2846 // The drag pointer is up.
2847 [[fallthrough]];
2848 case AMOTION_EVENT_ACTION_UP:
2849 finishDragAndDrop(entry.displayId, x, y);
2850 break;
2851 case AMOTION_EVENT_ACTION_CANCEL: {
2852 ALOGD("Receiving cancel when drag and drop.");
2853 sendDropWindowCommandLocked(nullptr, 0, 0);
2854 mDragState.reset();
2855 break;
2856 }
arthurhungb89ccb02020-12-30 16:19:01 +08002857 }
2858}
2859
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002860std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2861 const sp<android::gui::WindowInfoHandle>& windowHandle,
2862 ftl::Flags<InputTarget::Flags> targetFlags,
2863 std::optional<nsecs_t> firstDownTimeInTarget) const {
2864 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2865 if (inputChannel == nullptr) {
2866 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2867 return {};
2868 }
2869 InputTarget inputTarget;
2870 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002871 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002872 inputTarget.flags = targetFlags;
2873 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2874 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2875 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2876 if (displayInfoIt != mDisplayInfos.end()) {
2877 inputTarget.displayTransform = displayInfoIt->second.transform;
2878 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002879 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002880 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2881 }
2882 return inputTarget;
2883}
2884
chaviw98318de2021-05-19 16:45:23 -05002885void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002886 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002887 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002888 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002889 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002890 std::vector<InputTarget>::iterator it =
2891 std::find_if(inputTargets.begin(), inputTargets.end(),
2892 [&windowHandle](const InputTarget& inputTarget) {
2893 return inputTarget.inputChannel->getConnectionToken() ==
2894 windowHandle->getToken();
2895 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002896
chaviw98318de2021-05-19 16:45:23 -05002897 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002898
2899 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002900 std::optional<InputTarget> target =
2901 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2902 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002903 return;
2904 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002905 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002906 it = inputTargets.end() - 1;
2907 }
2908
2909 ALOG_ASSERT(it->flags == targetFlags);
2910 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2911
chaviw1ff3d1e2020-07-01 15:53:47 -07002912 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913}
2914
Michael Wright3dd60e22019-03-27 22:06:44 +00002915void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002916 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002917 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2918 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002919
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002920 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2921 InputTarget target;
2922 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002923 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002924 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2925 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002926 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2927 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002928 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002929 target.setDefaultPointerTransform(target.displayTransform);
2930 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 }
2932}
2933
Robert Carrc9bf1d32020-04-13 17:21:08 -07002934/**
2935 * Indicate whether one window handle should be considered as obscuring
2936 * another window handle. We only check a few preconditions. Actually
2937 * checking the bounds is left to the caller.
2938 */
chaviw98318de2021-05-19 16:45:23 -05002939static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2940 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002941 // Compare by token so cloned layers aren't counted
2942 if (haveSameToken(windowHandle, otherHandle)) {
2943 return false;
2944 }
2945 auto info = windowHandle->getInfo();
2946 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002947 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002948 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002949 } else if (otherInfo->alpha == 0 &&
2950 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002951 // Those act as if they were invisible, so we don't need to flag them.
2952 // We do want to potentially flag touchable windows even if they have 0
2953 // opacity, since they can consume touches and alter the effects of the
2954 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002955 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002956 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2957 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002958 } else if (info->ownerUid == otherInfo->ownerUid) {
2959 // If ownerUid is the same we don't generate occlusion events as there
2960 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002961 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002962 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002963 return false;
2964 } else if (otherInfo->displayId != info->displayId) {
2965 return false;
2966 }
2967 return true;
2968}
2969
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002970/**
2971 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2972 * untrusted, one should check:
2973 *
2974 * 1. If result.hasBlockingOcclusion is true.
2975 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2976 * BLOCK_UNTRUSTED.
2977 *
2978 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2979 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2980 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2981 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2982 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2983 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2984 *
2985 * If neither of those is true, then it means the touch can be allowed.
2986 */
2987InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002988 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2989 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002990 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002991 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002992 TouchOcclusionInfo info;
2993 info.hasBlockingOcclusion = false;
2994 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002995 info.obscuringUid = gui::Uid::INVALID;
2996 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002997 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002998 if (windowHandle == otherHandle) {
2999 break; // All future windows are below us. Exit early.
3000 }
chaviw98318de2021-05-19 16:45:23 -05003001 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003002 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3003 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003004 if (DEBUG_TOUCH_OCCLUSION) {
3005 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003006 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003007 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003008 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3009 // we perform the checks below to see if the touch can be propagated or not based on the
3010 // window's touch occlusion mode
3011 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3012 info.hasBlockingOcclusion = true;
3013 info.obscuringUid = otherInfo->ownerUid;
3014 info.obscuringPackage = otherInfo->packageName;
3015 break;
3016 }
3017 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003018 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003019 float opacity =
3020 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3021 // Given windows A and B:
3022 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3023 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3024 opacityByUid[uid] = opacity;
3025 if (opacity > info.obscuringOpacity) {
3026 info.obscuringOpacity = opacity;
3027 info.obscuringUid = uid;
3028 info.obscuringPackage = otherInfo->packageName;
3029 }
3030 }
3031 }
3032 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003033 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003034 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003035 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003036 return info;
3037}
3038
chaviw98318de2021-05-19 16:45:23 -05003039std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003040 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003041 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003042 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3043 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3044 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003045 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003046 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003047 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3048 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003049 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3050 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3051 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003052 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003053}
3054
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003055bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3056 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003057 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3058 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003059 return false;
3060 }
3061 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003062 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003063 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003064 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003065 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3066 return false;
3067 }
3068 return true;
3069}
3070
chaviw98318de2021-05-19 16:45:23 -05003071bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003072 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003074 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3075 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003076 if (windowHandle == otherHandle) {
3077 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078 }
chaviw98318de2021-05-19 16:45:23 -05003079 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003080 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003081 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082 return true;
3083 }
3084 }
3085 return false;
3086}
3087
chaviw98318de2021-05-19 16:45:23 -05003088bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003089 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003090 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3091 const WindowInfo* windowInfo = windowHandle->getInfo();
3092 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003093 if (windowHandle == otherHandle) {
3094 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003095 }
chaviw98318de2021-05-19 16:45:23 -05003096 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003097 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003098 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003099 return true;
3100 }
3101 }
3102 return false;
3103}
3104
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003105std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003106 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003107 if (applicationHandle != nullptr) {
3108 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003109 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110 } else {
3111 return applicationHandle->getName();
3112 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003113 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003114 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003116 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 }
3118}
3119
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003120void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003121 if (!isUserActivityEvent(eventEntry)) {
3122 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003123 return;
3124 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003125 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003126 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003127 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003128 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003129 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003130 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003131 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 }
3133 }
3134
3135 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003136 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003137 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003138 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3139 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003140 return;
3141 }
Josep del Riob3981622023-04-18 15:49:45 +00003142 if (windowDisablingUserActivityInfo != nullptr) {
3143 if (DEBUG_DISPATCH_CYCLE) {
3144 ALOGD("Not poking user activity: disabled by window '%s'.",
3145 windowDisablingUserActivityInfo->name.c_str());
3146 }
3147 return;
3148 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003149 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003150 eventType = USER_ACTIVITY_EVENT_TOUCH;
3151 }
3152 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003154 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003155 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3156 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003157 return;
3158 }
Josep del Riob3981622023-04-18 15:49:45 +00003159 // If the key code is unknown, we don't consider it user activity
3160 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3161 return;
3162 }
3163 // Don't inhibit events that were intercepted or are not passed to
3164 // the apps, like system shortcuts
3165 if (windowDisablingUserActivityInfo != nullptr &&
3166 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3167 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3168 if (DEBUG_DISPATCH_CYCLE) {
3169 ALOGD("Not poking user activity: disabled by window '%s'.",
3170 windowDisablingUserActivityInfo->name.c_str());
3171 }
3172 return;
3173 }
3174
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003175 eventType = USER_ACTIVITY_EVENT_BUTTON;
3176 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003178 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003179 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003180 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003181 break;
3182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 }
3184
Prabir Pradhancef936d2021-07-21 16:17:52 +00003185 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3186 REQUIRES(mLock) {
3187 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003188 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003189 };
3190 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191}
3192
3193void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003194 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003195 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003196 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003197 ATRACE_NAME_IF(ATRACE_ENABLED(),
3198 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3199 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003200 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003201 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003202 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003203 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003204 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003205 inputTarget.getPointerInfoString().c_str());
3206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207
3208 // Skip this event if the connection status is not normal.
3209 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003210 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003211 if (DEBUG_DISPATCH_CYCLE) {
3212 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003213 connection->getInputChannelName().c_str(),
3214 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 return;
3217 }
3218
3219 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003220 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003221 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003222 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003223 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003225 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003226 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003227 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3228 logDispatchStateLocked();
3229 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3230 "target on connection "
3231 << connection->getInputChannelName() << " for "
3232 << originalMotionEntry.getDescription();
3233 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003234 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003235 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3236 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 if (!splitMotionEntry) {
3238 return; // split event was dropped
3239 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003240 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3241 std::string reason = std::string("reason=pointer cancel on split window");
3242 android_log_event_list(LOGTAG_INPUT_CANCEL)
3243 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3244 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003245 if (DEBUG_FOCUS) {
3246 ALOGD("channel '%s' ~ Split motion event.",
3247 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003248 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003249 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003250 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3251 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252 return;
3253 }
3254 }
3255
3256 // Not splitting. Enqueue dispatch entries for the event as is.
3257 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3258}
3259
3260void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003261 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003262 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003263 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003264 ATRACE_NAME_IF(ATRACE_ENABLED(),
3265 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3266 connection->getInputChannelName().c_str(), eventEntry->id));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003267 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3268 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003269
hongzuo liu95785e22022-09-06 02:51:35 +00003270 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271
3272 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003273 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003274 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003275 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003276 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003277 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003278 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003279 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003280 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003281 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003282 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003283 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003284 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285
3286 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003287 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288 startDispatchCycleLocked(currentTime, connection);
3289 }
3290}
3291
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003292void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003293 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003294 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003295 ftl::Flags<InputTarget::Flags> dispatchMode) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003296 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3297 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298 return;
3299 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003300
3301 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3302 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303
3304 // This is a new event.
3305 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003306 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003307 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003309 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3310 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003311 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003313 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003314 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003315 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003316 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3317 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003318 LOG(WARNING) << "channel " << connection->getInputChannelName()
3319 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003320 return; // skip the inconsistent event
3321 }
3322 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003325 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003326 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003327 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3328 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3329 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3330 static_cast<int32_t>(IdGenerator::Source::OTHER);
3331 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003332 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003333 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003334 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003335 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003336 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003338 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003340 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003341 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3342 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003343 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003344 }
3345 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003346 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3347 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003348 if (DEBUG_DISPATCH_CYCLE) {
3349 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3350 "enter event",
3351 connection->getInputChannelName().c_str());
3352 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003353 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3354 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003355 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003358 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3359 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3360 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003361 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003362 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3363 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003364 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003365 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003368 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3369 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003370 LOG(WARNING) << "channel " << connection->getInputChannelName()
3371 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003372 return; // skip the inconsistent event
3373 }
3374
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003375 dispatchEntry->resolvedEventId =
3376 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3377 ? mIdGenerator.nextId()
3378 : motionEntry.id;
3379 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3380 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3381 ") to MotionEvent(id=0x%" PRIx32 ").",
3382 motionEntry.id, dispatchEntry->resolvedEventId);
3383 ATRACE_NAME(message.c_str());
3384 }
3385
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003386 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3387 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3388 // Skip reporting pointer down outside focus to the policy.
3389 break;
3390 }
3391
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003392 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003393 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003394
3395 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003397 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003398 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003399 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3400 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003401 break;
3402 }
Chris Yef59a2f42020-10-16 12:55:26 -07003403 case EventEntry::Type::SENSOR: {
3404 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3405 break;
3406 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003407 case EventEntry::Type::CONFIGURATION_CHANGED:
3408 case EventEntry::Type::DEVICE_RESET: {
3409 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003410 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003411 break;
3412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 }
3414
3415 // Remember that we are waiting for this dispatch to complete.
3416 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003417 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 }
3419
3420 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003421 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003422 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003423}
3424
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003425/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003426 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003427 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003428 * The first role is to log input interaction with windows, which helps determine what the user was
3429 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3430 * that user started interacting with launcher window, as well as any other window that received
3431 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3432 * when the set of tokens that received the event changes. It is not logged again as long as the
3433 * user is interacting with the same windows.
3434 *
3435 * The second role is to track input device activity for metrics collection. For each input event,
3436 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3437 * input_interaction logs, the device interaction is reported even when the set of interaction
3438 * tokens do not change.
3439 *
3440 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3441 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003442 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003443void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3444 const std::vector<InputTarget>& targets) {
3445 int32_t deviceId;
3446 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003447 // Skip ACTION_UP events, and all events other than keys and motions
3448 if (entry.type == EventEntry::Type::KEY) {
3449 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3450 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3451 return;
3452 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003453 deviceId = keyEntry.deviceId;
3454 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003455 } else if (entry.type == EventEntry::Type::MOTION) {
3456 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3457 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003458 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3459 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003460 return;
3461 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003462 deviceId = motionEntry.deviceId;
3463 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003464 } else {
3465 return; // Not a key or a motion
3466 }
3467
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003468 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003469 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003470 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003471 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003472 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003473 continue; // Skip windows that receive ACTION_OUTSIDE
3474 }
3475
3476 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003477 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003478 if (connection == nullptr) {
3479 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003480 }
3481 newConnectionTokens.insert(std::move(token));
3482 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003483 if (target.windowHandle) {
3484 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3485 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003486 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003487
3488 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3489 REQUIRES(mLock) {
3490 scoped_unlock unlock(mLock);
3491 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3492 };
3493 postCommandLocked(std::move(command));
3494
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003495 if (newConnectionTokens == mInteractionConnectionTokens) {
3496 return; // no change
3497 }
3498 mInteractionConnectionTokens = newConnectionTokens;
3499
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003500 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003501 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003502 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003503 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003504 std::string message = "Interaction with: " + targetList;
3505 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003506 message += "<none>";
3507 }
3508 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3509}
3510
chaviwfd6d3512019-03-25 13:23:49 -07003511void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003512 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003513 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003514 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3515 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003516 return;
3517 }
3518
Vishnu Nairc519ff72021-01-21 08:23:08 -08003519 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003520 if (focusedToken == token) {
3521 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003522 return;
3523 }
3524
Prabir Pradhancef936d2021-07-21 16:17:52 +00003525 auto command = [this, token]() REQUIRES(mLock) {
3526 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003527 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003528 };
3529 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530}
3531
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003532status_t InputDispatcher::publishMotionEvent(Connection& connection,
3533 DispatchEntry& dispatchEntry) const {
3534 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3535 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3536
3537 PointerCoords scaledCoords[MAX_POINTERS];
3538 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3539
3540 // Set the X and Y offset and X and Y scale depending on the input source.
3541 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003542 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003543 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3544 if (globalScaleFactor != 1.0f) {
3545 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3546 scaledCoords[i] = motionEntry.pointerCoords[i];
3547 // Don't apply window scale here since we don't want scale to affect raw
3548 // coordinates. The scale will be sent back to the client and applied
3549 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003550 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003551 }
3552 usingCoords = scaledCoords;
3553 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003554 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003555 // We don't want the dispatch target to know the coordinates
3556 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3557 scaledCoords[i].clear();
3558 }
3559 usingCoords = scaledCoords;
3560 }
3561
3562 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3563
3564 // Publish the motion event.
3565 return connection.inputPublisher
3566 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3567 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3568 std::move(hmac), dispatchEntry.resolvedAction,
3569 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3570 motionEntry.edgeFlags, motionEntry.metaState,
3571 motionEntry.buttonState, motionEntry.classification,
3572 dispatchEntry.transform, motionEntry.xPrecision,
3573 motionEntry.yPrecision, motionEntry.xCursorPosition,
3574 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3575 motionEntry.downTime, motionEntry.eventTime,
3576 motionEntry.pointerCount, motionEntry.pointerProperties,
3577 usingCoords);
3578}
3579
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003581 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003582 ATRACE_NAME_IF(ATRACE_ENABLED(),
3583 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3584 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003585 if (DEBUG_DISPATCH_CYCLE) {
3586 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3587 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003589 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003590 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003592 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003593 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594
3595 // Publish the event.
3596 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003597 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3598 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003599 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003600 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3601 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003602 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003603 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3604 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003607 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003608 status = connection->inputPublisher
3609 .publishKeyEvent(dispatchEntry->seq,
3610 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3611 keyEntry.source, keyEntry.displayId,
3612 std::move(hmac), dispatchEntry->resolvedAction,
3613 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3614 keyEntry.scanCode, keyEntry.metaState,
3615 keyEntry.repeatCount, keyEntry.downTime,
3616 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003617 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 }
3619
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003620 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003621 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003622 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3623 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003624 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003625 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003626 break;
3627 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003628
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003629 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003630 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003631 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003632 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003633 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003634 break;
3635 }
3636
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003637 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3638 const TouchModeEntry& touchModeEntry =
3639 static_cast<const TouchModeEntry&>(eventEntry);
3640 status = connection->inputPublisher
3641 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3642 touchModeEntry.inTouchMode);
3643
3644 break;
3645 }
3646
Prabir Pradhan99987712020-11-10 18:43:05 -08003647 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3648 const auto& captureEntry =
3649 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3650 status = connection->inputPublisher
3651 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003652 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003653 break;
3654 }
3655
arthurhungb89ccb02020-12-30 16:19:01 +08003656 case EventEntry::Type::DRAG: {
3657 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3658 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3659 dragEntry.id, dragEntry.x,
3660 dragEntry.y,
3661 dragEntry.isExiting);
3662 break;
3663 }
3664
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003665 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003666 case EventEntry::Type::DEVICE_RESET:
3667 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003668 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003669 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003670 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003671 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 }
3673
3674 // Check the result.
3675 if (status) {
3676 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003677 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003679 "This is unexpected because the wait queue is empty, so the pipe "
3680 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003681 "event to it, status=%s(%d)",
3682 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3683 status);
Harry Cutts33476232023-01-30 19:57:29 +00003684 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 } else {
3686 // Pipe is full and we are waiting for the app to finish process some events
3687 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003688 if (DEBUG_DISPATCH_CYCLE) {
3689 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3690 "waiting for the application to catch up",
3691 connection->getInputChannelName().c_str());
3692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 }
3694 } else {
3695 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003696 "status=%s(%d)",
3697 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3698 status);
Harry Cutts33476232023-01-30 19:57:29 +00003699 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 }
3701 return;
3702 }
3703
3704 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003705 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3706 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3707 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003708 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003709 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003710 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003711 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003712 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 }
3714}
3715
chaviw09c8d2d2020-08-24 15:48:26 -07003716std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3717 size_t size;
3718 switch (event.type) {
3719 case VerifiedInputEvent::Type::KEY: {
3720 size = sizeof(VerifiedKeyEvent);
3721 break;
3722 }
3723 case VerifiedInputEvent::Type::MOTION: {
3724 size = sizeof(VerifiedMotionEvent);
3725 break;
3726 }
3727 }
3728 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3729 return mHmacKeyManager.sign(start, size);
3730}
3731
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003732const std::array<uint8_t, 32> InputDispatcher::getSignature(
3733 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003734 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003735 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003736 // Only sign events up and down events as the purely move events
3737 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003738 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003739 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003740
3741 VerifiedMotionEvent verifiedEvent =
3742 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3743 verifiedEvent.actionMasked = actionMasked;
3744 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3745 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003746}
3747
3748const std::array<uint8_t, 32> InputDispatcher::getSignature(
3749 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3750 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3751 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3752 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003753 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003754}
3755
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003757 const std::shared_ptr<Connection>& connection,
3758 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003759 if (DEBUG_DISPATCH_CYCLE) {
3760 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3761 connection->getInputChannelName().c_str(), seq, toString(handled));
3762 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003764 if (connection->status == Connection::Status::BROKEN ||
3765 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 return;
3767 }
3768
3769 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003770 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3771 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3772 };
3773 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774}
3775
3776void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003777 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003778 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003779 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003780 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3781 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783
3784 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003785 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003786 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003787 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003788 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789
3790 // The connection appears to be unrecoverably broken.
3791 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003792 if (connection->status == Connection::Status::NORMAL) {
3793 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794
3795 if (notify) {
3796 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003797 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3798 connection->getInputChannelName().c_str());
3799
3800 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003801 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003802 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003803 };
3804 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 }
3806 }
3807}
3808
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003809void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003810 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003811 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003812 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 }
3814}
3815
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003816void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003818 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820}
3821
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003822int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3823 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003824 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003825 if (connection == nullptr) {
3826 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3827 connectionToken.get(), events);
3828 return 0; // remove the callback
3829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003831 bool notify;
3832 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3833 if (!(events & ALOOPER_EVENT_INPUT)) {
3834 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3835 "events=0x%x",
3836 connection->getInputChannelName().c_str(), events);
3837 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
3839
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003840 nsecs_t currentTime = now();
3841 bool gotOne = false;
3842 status_t status = OK;
3843 for (;;) {
3844 Result<InputPublisher::ConsumerResponse> result =
3845 connection->inputPublisher.receiveConsumerResponse();
3846 if (!result.ok()) {
3847 status = result.error().code();
3848 break;
3849 }
3850
3851 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3852 const InputPublisher::Finished& finish =
3853 std::get<InputPublisher::Finished>(*result);
3854 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3855 finish.consumeTime);
3856 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003857 if (shouldReportMetricsForConnection(*connection)) {
3858 const InputPublisher::Timeline& timeline =
3859 std::get<InputPublisher::Timeline>(*result);
3860 mLatencyTracker
3861 .trackGraphicsLatency(timeline.inputEventId,
3862 connection->inputChannel->getConnectionToken(),
3863 std::move(timeline.graphicsTimeline));
3864 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003865 }
3866 gotOne = true;
3867 }
3868 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003869 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003870 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 return 1;
3872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873 }
3874
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003875 notify = status != DEAD_OBJECT || !connection->monitor;
3876 if (notify) {
3877 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3878 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3879 status);
3880 }
3881 } else {
3882 // Monitor channels are never explicitly unregistered.
3883 // We do it automatically when the remote endpoint is closed so don't warn about them.
3884 const bool stillHaveWindowHandle =
3885 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3886 notify = !connection->monitor && stillHaveWindowHandle;
3887 if (notify) {
3888 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3889 connection->getInputChannelName().c_str(), events);
3890 }
3891 }
3892
3893 // Remove the channel.
3894 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3895 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896}
3897
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003898void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003900 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003901 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 }
3903}
3904
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003905void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003906 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003907 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003908 for (const Monitor& monitor : monitors) {
3909 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003910 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003911 }
3912}
3913
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003915 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003916 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003917 if (connection == nullptr) {
3918 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003920
3921 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922}
3923
3924void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003925 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003926 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003927 return;
3928 }
3929
3930 nsecs_t currentTime = now();
3931
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003932 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003933 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003935 if (cancelationEvents.empty()) {
3936 return;
3937 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003938 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3939 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003940 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003941 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003942 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003943 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003944
Arthur Hungb3307ee2021-10-14 10:57:37 +00003945 std::string reason = std::string("reason=").append(options.reason);
3946 android_log_event_list(LOGTAG_INPUT_CANCEL)
3947 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3948
Svet Ganov5d3bc372020-01-26 23:11:07 -08003949 InputTarget target;
Hu Guo771a7692023-09-17 20:51:08 +08003950 sp<WindowInfoHandle> windowHandle;
3951 if (options.displayId) {
3952 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken(),
3953 options.displayId.value());
3954 } else {
3955 windowHandle = getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3956 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003957 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003958 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003959 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003960 target.globalScaleFactor = windowInfo->globalScaleFactor;
3961 }
3962 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003963 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003964
hongzuo liu95785e22022-09-06 02:51:35 +00003965 const bool wasEmpty = connection->outboundQueue.empty();
3966
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003967 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003968 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003969 switch (cancelationEventEntry->type) {
3970 case EventEntry::Type::KEY: {
3971 logOutboundKeyDetails("cancel - ",
3972 static_cast<const KeyEntry&>(*cancelationEventEntry));
3973 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003975 case EventEntry::Type::MOTION: {
3976 logOutboundMotionDetails("cancel - ",
3977 static_cast<const MotionEntry&>(*cancelationEventEntry));
3978 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003980 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003981 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003982 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3983 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003984 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003985 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003986 break;
3987 }
3988 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003989 case EventEntry::Type::DEVICE_RESET:
3990 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003991 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003992 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003993 break;
3994 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 }
3996
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003997 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003998 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004000
hongzuo liu95785e22022-09-06 02:51:35 +00004001 // If the outbound queue was previously empty, start the dispatch cycle going.
4002 if (wasEmpty && !connection->outboundQueue.empty()) {
4003 startDispatchCycleLocked(currentTime, connection);
4004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005}
4006
Svet Ganov5d3bc372020-01-26 23:11:07 -08004007void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004008 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004009 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004010 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004011 return;
4012 }
4013
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004014 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004015 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004016
4017 if (downEvents.empty()) {
4018 return;
4019 }
4020
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004021 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004022 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4023 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004024 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004025
4026 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05004027 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004028 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
4029 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05004030 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07004031 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004032 target.globalScaleFactor = windowInfo->globalScaleFactor;
4033 }
4034 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00004035 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08004036
hongzuo liu95785e22022-09-06 02:51:35 +00004037 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004038 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004039 switch (downEventEntry->type) {
4040 case EventEntry::Type::MOTION: {
4041 logOutboundMotionDetails("down - ",
4042 static_cast<const MotionEntry&>(*downEventEntry));
4043 break;
4044 }
4045
4046 case EventEntry::Type::KEY:
4047 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004048 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004049 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004050 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004051 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004052 case EventEntry::Type::SENSOR:
4053 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004054 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004055 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004056 break;
4057 }
4058 }
4059
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004060 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004061 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004062 }
4063
hongzuo liu95785e22022-09-06 02:51:35 +00004064 // If the outbound queue was previously empty, start the dispatch cycle going.
4065 if (wasEmpty && !connection->outboundQueue.empty()) {
4066 startDispatchCycleLocked(downTime, connection);
4067 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004068}
4069
Arthur Hungc539dbb2022-12-08 07:45:36 +00004070void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4071 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4072 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004073 std::shared_ptr<Connection> wallpaperConnection =
4074 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004075 if (wallpaperConnection != nullptr) {
4076 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4077 }
4078 }
4079}
4080
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004081std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004082 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4083 nsecs_t splitDownTime) {
4084 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085
4086 uint32_t splitPointerIndexMap[MAX_POINTERS];
4087 PointerProperties splitPointerProperties[MAX_POINTERS];
4088 PointerCoords splitPointerCoords[MAX_POINTERS];
4089
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004090 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 uint32_t splitPointerCount = 0;
4092
4093 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004094 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004096 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004098 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07004100 splitPointerProperties[splitPointerCount] = pointerProperties;
4101 splitPointerCoords[splitPointerCount] =
4102 originalMotionEntry.pointerCoords[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 splitPointerCount += 1;
4104 }
4105 }
4106
4107 if (splitPointerCount != pointerIds.count()) {
4108 // This is bad. We are missing some of the pointers that we expected to deliver.
4109 // Most likely this indicates that we received an ACTION_MOVE events that has
4110 // different pointer ids than we expected based on the previous ACTION_DOWN
4111 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4112 // in this way.
4113 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004114 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004115 "a broken sequence of pointer ids from the input device: %s",
4116 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004117 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 }
4119
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004120 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004122 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4123 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004124 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004126 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004128 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 if (pointerIds.count() == 1) {
4130 // The first/last pointer went down/up.
4131 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004132 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004133 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4134 ? AMOTION_EVENT_ACTION_CANCEL
4135 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 } else {
4137 // A secondary pointer went down/up.
4138 uint32_t splitPointerIndex = 0;
4139 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4140 splitPointerIndex += 1;
4141 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004142 action = maskedAction |
4143 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 }
4145 } else {
4146 // An unrelated pointer changed.
4147 action = AMOTION_EVENT_ACTION_MOVE;
4148 }
4149 }
4150
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004151 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4152 logDispatchStateLocked();
4153 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4154 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4155 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004156 }
4157
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004158 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004159 ATRACE_NAME_IF(ATRACE_ENABLED(),
4160 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4161 ").",
4162 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004163 std::unique_ptr<MotionEntry> splitMotionEntry =
4164 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4165 originalMotionEntry.deviceId, originalMotionEntry.source,
4166 originalMotionEntry.displayId,
4167 originalMotionEntry.policyFlags, action,
4168 originalMotionEntry.actionButton,
4169 originalMotionEntry.flags, originalMotionEntry.metaState,
4170 originalMotionEntry.buttonState,
4171 originalMotionEntry.classification,
4172 originalMotionEntry.edgeFlags,
4173 originalMotionEntry.xPrecision,
4174 originalMotionEntry.yPrecision,
4175 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004176 originalMotionEntry.yCursorPosition, splitDownTime,
4177 splitPointerCount, splitPointerProperties,
4178 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004180 if (originalMotionEntry.injectionState) {
4181 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 splitMotionEntry->injectionState->refCount += 1;
4183 }
4184
4185 return splitMotionEntry;
4186}
4187
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004188void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4189 std::scoped_lock _l(mLock);
4190 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4191}
4192
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004193void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004194 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004195 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197
Antonio Kantekf16f2832021-09-28 04:39:20 +00004198 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004200 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004202 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004203 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004204 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 } // release lock
4206
4207 if (needWake) {
4208 mLooper->wake();
4209 }
4210}
4211
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004212void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004213 ALOGD_IF(debugInboundEventDetails(),
4214 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4215 ", deviceId=%d, source=%s, displayId=%" PRId32
4216 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4217 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004218 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4219 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4220 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004221 Result<void> keyCheck = validateKeyEvent(args.action);
4222 if (!keyCheck.ok()) {
4223 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224 return;
4225 }
4226
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004227 uint32_t policyFlags = args.policyFlags;
4228 int32_t flags = args.flags;
4229 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004230 // InputDispatcher tracks and generates key repeats on behalf of
4231 // whatever notifies it, so repeatCount should always be set to 0
4232 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4234 policyFlags |= POLICY_FLAG_VIRTUAL;
4235 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 if (policyFlags & POLICY_FLAG_FUNCTION) {
4238 metaState |= AMETA_FUNCTION_ON;
4239 }
4240
4241 policyFlags |= POLICY_FLAG_TRUSTED;
4242
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004243 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004245 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4246 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4247 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248
Michael Wright2b3c3302018-03-02 17:19:13 +00004249 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004250 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004251 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4252 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004253 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255
Antonio Kantekf16f2832021-09-28 04:39:20 +00004256 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 { // acquire lock
4258 mLock.lock();
4259
4260 if (shouldSendKeyToInputFilterLocked(args)) {
4261 mLock.unlock();
4262
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004263 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004264 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 return; // event was consumed by the filter
4266 }
4267
4268 mLock.lock();
4269 }
4270
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004271 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004272 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4273 args.displayId, policyFlags, args.action, flags, keyCode,
4274 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004276 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 mLock.unlock();
4278 } // release lock
4279
4280 if (needWake) {
4281 mLooper->wake();
4282 }
4283}
4284
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004285bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 return mInputFilterEnabled;
4287}
4288
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004289void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004290 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004291 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004292 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004293 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004294 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4295 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004296 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4297 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4298 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4299 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4300 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004301 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004302 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4303 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004304 i, args.pointerProperties[i].id,
4305 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4306 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4307 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4308 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4309 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4310 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4311 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4312 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4313 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4314 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004315 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004317
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004318 Result<void> motionCheck =
4319 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4320 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004321 if (!motionCheck.ok()) {
4322 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4323 return;
4324 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004326 if (DEBUG_VERIFY_EVENTS) {
4327 auto [it, _] =
4328 mVerifiersByDisplay.try_emplace(args.displayId,
4329 StringPrintf("display %" PRId32, args.displayId));
4330 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004331 it->second.processMovement(args.deviceId, args.source, args.action,
4332 args.getPointerCount(), args.pointerProperties.data(),
4333 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004334 if (!result.ok()) {
4335 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4336 }
4337 }
4338
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004339 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004341
4342 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004343 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004344 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4345 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004346 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004347 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348
Antonio Kantekf16f2832021-09-28 04:39:20 +00004349 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 { // acquire lock
4351 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004352 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4353 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4354 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004355 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004356 if (touchStateIt != mTouchStatesByDisplay.end()) {
4357 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004358 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004359 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4360 }
4361 }
4362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363
4364 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004365 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004366 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004367 displayTransform = it->second.transform;
4368 }
4369
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370 mLock.unlock();
4371
4372 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004373 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4374 args.action, args.actionButton, args.flags, args.edgeFlags,
4375 args.metaState, args.buttonState, args.classification,
4376 displayTransform, args.xPrecision, args.yPrecision,
4377 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004378 args.downTime, args.eventTime, args.getPointerCount(),
4379 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380
4381 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004382 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 return; // event was consumed by the filter
4384 }
4385
4386 mLock.lock();
4387 }
4388
4389 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004390 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004391 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4392 args.displayId, policyFlags, args.action,
4393 args.actionButton, args.flags, args.metaState,
4394 args.buttonState, args.classification, args.edgeFlags,
4395 args.xPrecision, args.yPrecision,
4396 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004397 args.downTime, args.getPointerCount(),
4398 args.pointerProperties.data(),
4399 args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004401 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4402 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004403 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004404 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004405 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4406 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4407 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004408 }
4409
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004410 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004411 mLock.unlock();
4412 } // release lock
4413
4414 if (needWake) {
4415 mLooper->wake();
4416 }
4417}
4418
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004419void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004420 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004421 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4422 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004423 args.id, args.eventTime, args.deviceId, args.source,
4424 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004425 }
Chris Yef59a2f42020-10-16 12:55:26 -07004426
Antonio Kantekf16f2832021-09-28 04:39:20 +00004427 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004428 { // acquire lock
4429 mLock.lock();
4430
4431 // Just enqueue a new sensor event.
4432 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004433 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4434 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4435 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004436
4437 needWake = enqueueInboundEventLocked(std::move(newEntry));
4438 mLock.unlock();
4439 } // release lock
4440
4441 if (needWake) {
4442 mLooper->wake();
4443 }
4444}
4445
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004446void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004447 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004448 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4449 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004450 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004451 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004452}
4453
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004454bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004455 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456}
4457
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004458void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004459 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004460 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4461 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004462 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004465 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004467 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468}
4469
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004470void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004471 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004472 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4473 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004474 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475
Antonio Kantekf16f2832021-09-28 04:39:20 +00004476 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004478 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004480 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004481 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004482 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004483
4484 for (auto& [_, verifier] : mVerifiersByDisplay) {
4485 verifier.resetDevice(args.deviceId);
4486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 } // release lock
4488
4489 if (needWake) {
4490 mLooper->wake();
4491 }
4492}
4493
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004494void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004495 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004496 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4497 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004498 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004499
Antonio Kantekf16f2832021-09-28 04:39:20 +00004500 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004501 { // acquire lock
4502 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004503 auto entry =
4504 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004505 needWake = enqueueInboundEventLocked(std::move(entry));
4506 } // release lock
4507
4508 if (needWake) {
4509 mLooper->wake();
4510 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004511}
4512
Prabir Pradhan5735a322022-04-11 17:23:34 +00004513InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004514 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004515 InputEventInjectionSync syncMode,
4516 std::chrono::milliseconds timeout,
4517 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004518 Result<void> eventValidation = validateInputEvent(*event);
4519 if (!eventValidation.ok()) {
4520 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4521 return InputEventInjectionResult::FAILED;
4522 }
4523
Prabir Pradhan65613802023-02-22 23:36:58 +00004524 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004525 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4526 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4527 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4528 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004529 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004530 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531
Prabir Pradhan5735a322022-04-11 17:23:34 +00004532 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004534 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004535 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4536 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4537 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4538 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4539 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004540 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004541 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004542 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004543 }
4544
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004545 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004547 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004548 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004549 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004550 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004551 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4552 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4553 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004554 int32_t keyCode = incomingKey.getKeyCode();
4555 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004556 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004557 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004558 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4559 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4560 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004562 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4563 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004564 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004565
4566 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4567 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004568 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004569 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4570 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4571 std::to_string(t.duration().count()).c_str());
4572 }
4573 }
4574
4575 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004576 std::unique_ptr<KeyEntry> injectedEntry =
4577 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004578 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004579 incomingKey.getDisplayId(), policyFlags, action,
4580 flags, keyCode, incomingKey.getScanCode(), metaState,
4581 incomingKey.getRepeatCount(),
4582 incomingKey.getDownTime());
4583 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004584 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585 }
4586
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004587 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004588 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004589 const bool isPointerEvent =
4590 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4591 // If a pointer event has no displayId specified, inject it to the default display.
4592 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4593 ? ADISPLAY_ID_DEFAULT
4594 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004595 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004596
4597 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004598 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004599 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004600 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004601 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4602 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4603 std::to_string(t.duration().count()).c_str());
4604 }
4605 }
4606
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004607 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4608 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4609 }
4610
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004611 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004612 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4613 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004614 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004615 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4616 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004617 displayId, policyFlags, motionEvent.getAction(),
4618 motionEvent.getActionButton(), flags,
4619 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004620 motionEvent.getButtonState(),
4621 motionEvent.getClassification(),
4622 motionEvent.getEdgeFlags(),
4623 motionEvent.getXPrecision(),
4624 motionEvent.getYPrecision(),
4625 motionEvent.getRawXCursorPosition(),
4626 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004627 motionEvent.getDownTime(),
4628 motionEvent.getPointerCount(),
4629 motionEvent.getPointerProperties(),
4630 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004631 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004632 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004633 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004634 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004635 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004636 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004637 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4638 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004639 displayId, policyFlags,
4640 motionEvent.getAction(),
4641 motionEvent.getActionButton(), flags,
4642 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004643 motionEvent.getButtonState(),
4644 motionEvent.getClassification(),
4645 motionEvent.getEdgeFlags(),
4646 motionEvent.getXPrecision(),
4647 motionEvent.getYPrecision(),
4648 motionEvent.getRawXCursorPosition(),
4649 motionEvent.getRawYCursorPosition(),
4650 motionEvent.getDownTime(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004651 motionEvent.getPointerCount(),
4652 motionEvent.getPointerProperties(),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004653 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004654 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4655 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004656 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004657 }
4658 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004661 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004662 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004663 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664 }
4665
Prabir Pradhan5735a322022-04-11 17:23:34 +00004666 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004667 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668 injectionState->injectionIsAsync = true;
4669 }
4670
4671 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004672 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673
4674 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004675 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004676 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004677 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004678 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004679 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004680 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 }
4682
4683 mLock.unlock();
4684
4685 if (needWake) {
4686 mLooper->wake();
4687 }
4688
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004689 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004691 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004693 if (syncMode == InputEventInjectionSync::NONE) {
4694 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695 } else {
4696 for (;;) {
4697 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004698 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699 break;
4700 }
4701
4702 nsecs_t remainingTimeout = endTime - now();
4703 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004704 if (DEBUG_INJECTION) {
4705 ALOGD("injectInputEvent - Timed out waiting for injection result "
4706 "to become available.");
4707 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004708 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709 break;
4710 }
4711
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004712 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 }
4714
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004715 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4716 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004718 if (DEBUG_INJECTION) {
4719 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4720 injectionState->pendingForegroundDispatches);
4721 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722 nsecs_t remainingTimeout = endTime - now();
4723 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004724 if (DEBUG_INJECTION) {
4725 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4726 "dispatches to finish.");
4727 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004728 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729 break;
4730 }
4731
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004732 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 }
4734 }
4735 }
4736
4737 injectionState->release();
4738 } // release lock
4739
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004740 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004741 LOG(INFO) << "injectInputEvent - Finished with result "
4742 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744
4745 return injectionResult;
4746}
4747
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004748std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004749 std::array<uint8_t, 32> calculatedHmac;
4750 std::unique_ptr<VerifiedInputEvent> result;
4751 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004752 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004753 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4754 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4755 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004756 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004757 break;
4758 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004759 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004760 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4761 VerifiedMotionEvent verifiedMotionEvent =
4762 verifiedMotionEventFromMotionEvent(motionEvent);
4763 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004764 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004765 break;
4766 }
4767 default: {
4768 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4769 return nullptr;
4770 }
4771 }
4772 if (calculatedHmac == INVALID_HMAC) {
4773 return nullptr;
4774 }
tyiu1573a672023-02-21 22:38:32 +00004775 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004776 return nullptr;
4777 }
4778 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004779}
4780
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004781void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004782 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004783 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004785 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004786 LOG(INFO) << "Setting input event injection result to "
4787 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004788 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004790 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791 // Log the outcome since the injector did not wait for the injection result.
4792 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004793 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004794 ALOGV("Asynchronous input event injection succeeded.");
4795 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004796 case InputEventInjectionResult::TARGET_MISMATCH:
4797 ALOGV("Asynchronous input event injection target mismatch.");
4798 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004799 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004800 ALOGW("Asynchronous input event injection failed.");
4801 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004802 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004803 ALOGW("Asynchronous input event injection timed out.");
4804 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004805 case InputEventInjectionResult::PENDING:
4806 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4807 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 }
4809 }
4810
4811 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004812 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 }
4814}
4815
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004816void InputDispatcher::transformMotionEntryForInjectionLocked(
4817 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004818 // Input injection works in the logical display coordinate space, but the input pipeline works
4819 // display space, so we need to transform the injected events accordingly.
4820 const auto it = mDisplayInfos.find(entry.displayId);
4821 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004822 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004823
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004824 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4825 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4826 const vec2 cursor =
4827 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4828 {entry.xCursorPosition, entry.yCursorPosition});
4829 entry.xCursorPosition = cursor.x;
4830 entry.yCursorPosition = cursor.y;
4831 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004832 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004833 entry.pointerCoords[i] =
4834 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4835 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004836 }
4837}
4838
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004839void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4840 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 if (injectionState) {
4842 injectionState->pendingForegroundDispatches += 1;
4843 }
4844}
4845
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004846void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4847 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 if (injectionState) {
4849 injectionState->pendingForegroundDispatches -= 1;
4850
4851 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004852 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 }
4854 }
4855}
4856
chaviw98318de2021-05-19 16:45:23 -05004857const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004858 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004859 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004860 auto it = mWindowHandlesByDisplay.find(displayId);
4861 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004862}
4863
chaviw98318de2021-05-19 16:45:23 -05004864sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004865 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004866 if (windowHandleToken == nullptr) {
4867 return nullptr;
4868 }
4869
Arthur Hungb92218b2018-08-14 12:00:21 +08004870 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004871 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4872 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004873 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004874 return windowHandle;
4875 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 }
4877 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004878 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879}
4880
chaviw98318de2021-05-19 16:45:23 -05004881sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4882 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004883 if (windowHandleToken == nullptr) {
4884 return nullptr;
4885 }
4886
chaviw98318de2021-05-19 16:45:23 -05004887 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004888 if (windowHandle->getToken() == windowHandleToken) {
4889 return windowHandle;
4890 }
4891 }
4892 return nullptr;
4893}
4894
chaviw98318de2021-05-19 16:45:23 -05004895sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4896 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004897 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004898 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4899 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004900 if (handle->getId() == windowHandle->getId() &&
4901 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004902 if (windowHandle->getInfo()->displayId != it.first) {
4903 ALOGE("Found window %s in display %" PRId32
4904 ", but it should belong to display %" PRId32,
4905 windowHandle->getName().c_str(), it.first,
4906 windowHandle->getInfo()->displayId);
4907 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004908 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910 }
4911 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004912 return nullptr;
4913}
4914
chaviw98318de2021-05-19 16:45:23 -05004915sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004916 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4917 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918}
4919
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004920ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4921 auto displayInfoIt = mDisplayInfos.find(displayId);
4922 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4923 : kIdentityTransform;
4924}
4925
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004926bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4927 const MotionEntry& motionEntry) const {
4928 const WindowInfo& info = *window->getInfo();
4929
4930 // Skip spy window targets that are not valid for targeted injection.
4931 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004932 return false;
4933 }
4934
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004935 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4936 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4937 return false;
4938 }
4939
4940 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4941 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4942 window->getName().c_str());
4943 return false;
4944 }
4945
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004946 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004947 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004948 ALOGW("Not sending touch to %s because there's no corresponding connection",
4949 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004950 return false;
4951 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004952
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004953 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004954 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004955 return false;
4956 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004957
4958 // Drop events that can't be trusted due to occlusion
4959 const auto [x, y] = resolveTouchedPosition(motionEntry);
4960 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4961 if (!isTouchTrustedLocked(occlusionInfo)) {
4962 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004963 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004964 for (const auto& log : occlusionInfo.debugInfo) {
4965 ALOGD("%s", log.c_str());
4966 }
4967 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004968 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
4969 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004970 return false;
4971 }
4972
4973 // Drop touch events if requested by input feature
4974 if (shouldDropInput(motionEntry, window)) {
4975 return false;
4976 }
4977
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004978 return true;
4979}
4980
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004981std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4982 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004983 auto connectionIt = mConnectionsByToken.find(token);
4984 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004985 return nullptr;
4986 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004987 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004988}
4989
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004990void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004991 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4992 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004993 // Remove all handles on a display if there are no windows left.
4994 mWindowHandlesByDisplay.erase(displayId);
4995 return;
4996 }
4997
4998 // Since we compare the pointer of input window handles across window updates, we need
4999 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005000 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5001 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5002 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005003 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005004 }
5005
chaviw98318de2021-05-19 16:45:23 -05005006 std::vector<sp<WindowInfoHandle>> newHandles;
5007 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005008 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005009 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005010 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005011 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005012 const bool canReceiveInput =
5013 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5014 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005015 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005016 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005017 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005018 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005019 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005020 }
5021
5022 if (info->displayId != displayId) {
5023 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5024 handle->getName().c_str(), displayId, info->displayId);
5025 continue;
5026 }
5027
Robert Carredd13602020-04-13 17:24:34 -07005028 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5029 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005030 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005031 oldHandle->updateFrom(handle);
5032 newHandles.push_back(oldHandle);
5033 } else {
5034 newHandles.push_back(handle);
5035 }
5036 }
5037
5038 // Insert or replace
5039 mWindowHandlesByDisplay[displayId] = newHandles;
5040}
5041
Arthur Hungb92218b2018-08-14 12:00:21 +08005042/**
5043 * Called from InputManagerService, update window handle list by displayId that can receive input.
5044 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5045 * If set an empty list, remove all handles from the specific display.
5046 * For focused handle, check if need to change and send a cancel event to previous one.
5047 * For removed handle, check if need to send a cancel event if already in touch.
5048 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005049void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005050 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005051 if (DEBUG_FOCUS) {
5052 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005053 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005054 windowList += iwh->getName() + " ";
5055 }
5056 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5057 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005058
Prabir Pradhand65552b2021-10-07 11:23:50 -07005059 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005060 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005061 const WindowInfo& info = *window->getInfo();
5062
5063 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005064 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005065 if (noInputWindow && window->getToken() != nullptr) {
5066 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5067 window->getName().c_str());
5068 window->releaseChannel();
5069 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005070
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005071 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005072 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5073 !info.inputConfig.test(
5074 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005075 "%s has feature SPY, but is not a trusted overlay.",
5076 window->getName().c_str());
5077
Prabir Pradhand65552b2021-10-07 11:23:50 -07005078 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005079 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5080 !info.inputConfig.test(
5081 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005082 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5083 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005084 }
5085
Arthur Hung72d8dc32020-03-28 00:48:39 +00005086 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005087 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005088
chaviw98318de2021-05-19 16:45:23 -05005089 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005090
chaviw98318de2021-05-19 16:45:23 -05005091 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005092
Vishnu Nairc519ff72021-01-21 08:23:08 -08005093 std::optional<FocusResolver::FocusChanges> changes =
5094 mFocusResolver.setInputWindows(displayId, windowHandles);
5095 if (changes) {
5096 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005099 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5100 mTouchStatesByDisplay.find(displayId);
5101 if (stateIt != mTouchStatesByDisplay.end()) {
5102 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005103 for (size_t i = 0; i < state.windows.size();) {
5104 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005105 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005106 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005107 ALOGD("Touched window was removed: %s in display %" PRId32,
5108 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005109 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005110 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005111 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5112 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005113 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005114 "touched window was removed");
5115 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005116 // Since we are about to drop the touch, cancel the events for the wallpaper as
5117 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005118 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005119 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5120 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005121 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005122 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005125 state.windows.erase(state.windows.begin() + i);
5126 } else {
5127 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128 }
5129 }
arthurhungb89ccb02020-12-30 16:19:01 +08005130
arthurhung6d4bed92021-03-17 11:59:33 +08005131 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005132 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005133 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005134 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005135 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005136 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5137 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005138 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005139 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005140 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005141
Arthur Hung72d8dc32020-03-28 00:48:39 +00005142 // Release information for windows that are no longer present.
5143 // This ensures that unused input channels are released promptly.
5144 // Otherwise, they might stick around until the window handle is destroyed
5145 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005146 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005147 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005148 if (DEBUG_FOCUS) {
5149 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005150 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005151 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005152 }
chaviw291d88a2019-02-14 10:33:58 -08005153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154}
5155
5156void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005157 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005158 if (DEBUG_FOCUS) {
5159 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5160 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5161 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005162 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005163 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005164 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165 } // release lock
5166
5167 // Wake up poll loop since it may need to make new input dispatching choices.
5168 mLooper->wake();
5169}
5170
Vishnu Nair599f1412021-06-21 10:39:58 -07005171void InputDispatcher::setFocusedApplicationLocked(
5172 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5173 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5174 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5175
5176 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5177 return; // This application is already focused. No need to wake up or change anything.
5178 }
5179
5180 // Set the new application handle.
5181 if (inputApplicationHandle != nullptr) {
5182 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5183 } else {
5184 mFocusedApplicationHandlesByDisplay.erase(displayId);
5185 }
5186
5187 // No matter what the old focused application was, stop waiting on it because it is
5188 // no longer focused.
5189 resetNoFocusedWindowTimeoutLocked();
5190}
5191
Tiger Huang721e26f2018-07-24 22:26:19 +08005192/**
5193 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5194 * the display not specified.
5195 *
5196 * We track any unreleased events for each window. If a window loses the ability to receive the
5197 * released event, we will send a cancel event to it. So when the focused display is changed, we
5198 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5199 * display. The display-specified events won't be affected.
5200 */
5201void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005202 if (DEBUG_FOCUS) {
5203 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5204 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005205 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005206 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005207
5208 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005209 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005210 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005211 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005212 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005213 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005214 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005215 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005216 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005217 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005218 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005219 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5220 }
5221 }
5222 mFocusedDisplayId = displayId;
5223
Chris Ye3c2d6f52020-08-09 10:39:48 -07005224 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005225 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005226 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005227
Vishnu Nairad321cd2020-08-20 16:40:21 -07005228 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005229 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005230 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005231 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005232 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005233 }
5234 }
5235 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005236 } // release lock
5237
5238 // Wake up poll loop since it may need to make new input dispatching choices.
5239 mLooper->wake();
5240}
5241
Michael Wrightd02c5b62014-02-10 15:10:22 -08005242void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005243 if (DEBUG_FOCUS) {
5244 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5245 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246
5247 bool changed;
5248 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005249 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250
5251 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5252 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005253 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005254 }
5255
5256 if (mDispatchEnabled && !enabled) {
5257 resetAndDropEverythingLocked("dispatcher is being disabled");
5258 }
5259
5260 mDispatchEnabled = enabled;
5261 mDispatchFrozen = frozen;
5262 changed = true;
5263 } else {
5264 changed = false;
5265 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266 } // release lock
5267
5268 if (changed) {
5269 // Wake up poll loop since it may need to make new input dispatching choices.
5270 mLooper->wake();
5271 }
5272}
5273
5274void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005275 if (DEBUG_FOCUS) {
5276 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278
5279 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005280 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281
5282 if (mInputFilterEnabled == enabled) {
5283 return;
5284 }
5285
5286 mInputFilterEnabled = enabled;
5287 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5288 } // release lock
5289
5290 // Wake up poll loop since there might be work to do to drop everything.
5291 mLooper->wake();
5292}
5293
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005294bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005295 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005296 bool needWake = false;
5297 {
5298 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005299 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005300 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005301 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005302 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5303 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005304 mTouchModePerDisplay.count(displayId) == 0
5305 ? "not set"
5306 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5307
Antonio Kantek15beb512022-06-13 22:35:41 +00005308 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5309 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005310 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005311 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005312 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005313 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5314 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005315 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005316 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005317 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005318 return false;
5319 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005320 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005321 mTouchModePerDisplay[displayId] = inTouchMode;
5322 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5323 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005324 needWake = enqueueInboundEventLocked(std::move(entry));
5325 } // release lock
5326
5327 if (needWake) {
5328 mLooper->wake();
5329 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005330 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005331}
5332
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005333bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005334 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5335 if (focusedToken == nullptr) {
5336 return false;
5337 }
5338 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5339 return isWindowOwnedBy(windowHandle, pid, uid);
5340}
5341
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005342bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005343 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5344 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5345 const sp<WindowInfoHandle> windowHandle =
5346 getWindowHandleLocked(connectionToken);
5347 return isWindowOwnedBy(windowHandle, pid, uid);
5348 }) != mInteractionConnectionTokens.end();
5349}
5350
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005351void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5352 if (opacity < 0 || opacity > 1) {
5353 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5354 return;
5355 }
5356
5357 std::scoped_lock lock(mLock);
5358 mMaximumObscuringOpacityForTouch = opacity;
5359}
5360
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005361std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5362InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005363 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5364 for (TouchedWindow& w : state.windows) {
5365 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005366 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005367 }
5368 }
5369 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005370 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005371}
5372
arthurhungb89ccb02020-12-30 16:19:01 +08005373bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5374 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005375 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005376 if (DEBUG_FOCUS) {
5377 ALOGD("Trivial transfer to same window.");
5378 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005379 return true;
5380 }
5381
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005383 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384
Arthur Hungabbb9d82021-09-01 14:52:30 +00005385 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005386 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005387
Arthur Hungabbb9d82021-09-01 14:52:30 +00005388 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005389 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005390 return false;
5391 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005392 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5393 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005394 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5395 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005396 return false;
5397 }
5398 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005399
Arthur Hungabbb9d82021-09-01 14:52:30 +00005400 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5401 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005402 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005403 return false;
5404 }
5405
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005406 if (DEBUG_FOCUS) {
5407 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005408 touchedWindow->windowHandle->getName().c_str(),
5409 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 }
5411
Arthur Hungabbb9d82021-09-01 14:52:30 +00005412 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005413 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005414 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005415 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005416 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005417
Arthur Hungabbb9d82021-09-01 14:52:30 +00005418 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005419 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005420 ftl::Flags<InputTarget::Flags> newTargetFlags =
5421 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005422 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005423 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005424 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005425 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5426 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005427
Arthur Hungabbb9d82021-09-01 14:52:30 +00005428 // Store the dragging window.
5429 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005430 if (pointerIds.count() != 1) {
5431 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5432 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005433 return false;
5434 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005435 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005436 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005437 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438 }
5439
Arthur Hungabbb9d82021-09-01 14:52:30 +00005440 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005441 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5442 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005443 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005444 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005445 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5446 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005448 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5449 newTargetFlags);
5450
5451 // Check if the wallpaper window should deliver the corresponding event.
5452 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005453 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455 } // release lock
5456
5457 // Wake up poll loop since it may need to make new input dispatching choices.
5458 mLooper->wake();
5459 return true;
5460}
5461
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005462/**
5463 * Get the touched foreground window on the given display.
5464 * Return null if there are no windows touched on that display, or if more than one foreground
5465 * window is being touched.
5466 */
5467sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5468 auto stateIt = mTouchStatesByDisplay.find(displayId);
5469 if (stateIt == mTouchStatesByDisplay.end()) {
5470 ALOGI("No touch state on display %" PRId32, displayId);
5471 return nullptr;
5472 }
5473
5474 const TouchState& state = stateIt->second;
5475 sp<WindowInfoHandle> touchedForegroundWindow;
5476 // If multiple foreground windows are touched, return nullptr
5477 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005478 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005479 if (touchedForegroundWindow != nullptr) {
5480 ALOGI("Two or more foreground windows: %s and %s",
5481 touchedForegroundWindow->getName().c_str(),
5482 window.windowHandle->getName().c_str());
5483 return nullptr;
5484 }
5485 touchedForegroundWindow = window.windowHandle;
5486 }
5487 }
5488 return touchedForegroundWindow;
5489}
5490
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005491// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005492bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005493 sp<IBinder> fromToken;
5494 { // acquire lock
5495 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005496 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005497 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005498 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5499 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005500 return false;
5501 }
5502
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005503 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5504 if (from == nullptr) {
5505 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5506 return false;
5507 }
5508
5509 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005510 } // release lock
5511
5512 return transferTouchFocus(fromToken, destChannelToken);
5513}
5514
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005516 if (DEBUG_FOCUS) {
5517 ALOGD("Resetting and dropping all events (%s).", reason);
5518 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519
Michael Wrightfb04fd52022-11-24 22:31:11 +00005520 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005521 synthesizeCancelationEventsForAllConnectionsLocked(options);
5522
5523 resetKeyRepeatLocked();
5524 releasePendingEventLocked();
5525 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005526 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005527
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005528 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005529 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530}
5531
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005532void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005533 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 dumpDispatchStateLocked(dump);
5535
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005536 std::istringstream stream(dump);
5537 std::string line;
5538
5539 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005540 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541 }
5542}
5543
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005544std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005545 std::string dump;
5546
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005547 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5548 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005549
5550 std::string windowName = "None";
5551 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005552 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005553 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5554 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5555 : "token has capture without window";
5556 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005557 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005558
5559 return dump;
5560}
5561
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005562void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005563 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5564 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5565 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005566 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005567
Tiger Huang721e26f2018-07-24 22:26:19 +08005568 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5569 dump += StringPrintf(INDENT "FocusedApplications:\n");
5570 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5571 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005572 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005573 const std::chrono::duration timeout =
5574 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005575 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005576 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005577 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005580 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005582
Vishnu Nairc519ff72021-01-21 08:23:08 -08005583 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005584 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005585
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005586 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005587 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005588 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005589 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5590 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005591 }
5592 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005593 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005594 }
5595
arthurhung6d4bed92021-03-17 11:59:33 +08005596 if (mDragState) {
5597 dump += StringPrintf(INDENT "DragState:\n");
5598 mDragState->dump(dump, INDENT2);
5599 }
5600
Arthur Hungb92218b2018-08-14 12:00:21 +08005601 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005602 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5603 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5604 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5605 const auto& displayInfo = it->second;
5606 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5607 displayInfo.logicalHeight);
5608 displayInfo.transform.dump(dump, "transform", INDENT4);
5609 } else {
5610 dump += INDENT2 "No DisplayInfo found!\n";
5611 }
5612
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005613 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005614 dump += INDENT2 "Windows:\n";
5615 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005616 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5617 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005619 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005620 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005621 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005622 "applicationInfo.name=%s, "
5623 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005624 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005625 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005626 windowInfo->displayId,
5627 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005628 windowInfo->alpha, windowInfo->frame.left,
5629 windowInfo->frame.top, windowInfo->frame.right,
5630 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005631 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005632 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005633 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005634 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005635 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005636 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005637 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005638 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005639 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005640 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005641 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005642 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005643 }
5644 } else {
5645 dump += INDENT2 "Windows: <none>\n";
5646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647 }
5648 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005649 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650 }
5651
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005652 if (!mGlobalMonitorsByDisplay.empty()) {
5653 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5654 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005655 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005658 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005659 }
5660
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005661 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005662
5663 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005664 if (!mRecentQueue.empty()) {
5665 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005666 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005667 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005668 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005669 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670 }
5671 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005672 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005673 }
5674
5675 // Dump event currently being dispatched.
5676 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005677 dump += INDENT "PendingEvent:\n";
5678 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005679 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005680 dump += StringPrintf(", age=%" PRId64 "ms\n",
5681 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005682 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005683 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684 }
5685
5686 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005687 if (!mInboundQueue.empty()) {
5688 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005689 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005690 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005691 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005692 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 }
5694 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005695 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696 }
5697
Prabir Pradhancef936d2021-07-21 16:17:52 +00005698 if (!mCommandQueue.empty()) {
5699 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5700 } else {
5701 dump += INDENT "CommandQueue: <empty>\n";
5702 }
5703
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005704 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005705 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005706 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005707 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005708 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005709 connection->inputChannel->getFd().get(),
5710 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005711 connection->getWindowName().c_str(),
5712 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005713 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005715 if (!connection->outboundQueue.empty()) {
5716 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5717 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005718 dump += dumpQueue(connection->outboundQueue, currentTime);
5719
Michael Wrightd02c5b62014-02-10 15:10:22 -08005720 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005721 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722 }
5723
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005724 if (!connection->waitQueue.empty()) {
5725 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5726 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005727 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005728 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005729 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005730 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005731 std::stringstream inputStateDump;
5732 inputStateDump << connection->inputState;
5733 if (!isEmpty(inputStateDump)) {
5734 dump += INDENT3 "InputState: ";
5735 dump += inputStateDump.str() + "\n";
5736 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005737 }
5738 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005739 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005740 }
5741
5742 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005743 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5744 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005745 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005746 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005747 }
5748
Antonio Kantek15beb512022-06-13 22:35:41 +00005749 if (!mTouchModePerDisplay.empty()) {
5750 dump += INDENT "TouchModePerDisplay:\n";
5751 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5752 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5753 std::to_string(touchMode).c_str());
5754 }
5755 } else {
5756 dump += INDENT "TouchModePerDisplay: <none>\n";
5757 }
5758
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005759 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005760 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5761 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5762 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005763 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005764 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005765}
5766
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005767void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005768 const size_t numMonitors = monitors.size();
5769 for (size_t i = 0; i < numMonitors; i++) {
5770 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005771 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005772 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5773 dump += "\n";
5774 }
5775}
5776
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005777class LooperEventCallback : public LooperCallback {
5778public:
5779 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5780 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5781
5782private:
5783 std::function<int(int events)> mCallback;
5784};
5785
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005786Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005787 if (DEBUG_CHANNEL_CREATION) {
5788 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5789 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005790
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005791 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005792 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005793 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005794
5795 if (result) {
5796 return base::Error(result) << "Failed to open input channel pair with name " << name;
5797 }
5798
Michael Wrightd02c5b62014-02-10 15:10:22 -08005799 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005800 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005801 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005802 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005803 std::shared_ptr<Connection> connection =
5804 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5805 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005806
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005807 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5808 ALOGE("Created a new connection, but the token %p is already known", token.get());
5809 }
5810 mConnectionsByToken.emplace(token, connection);
5811
5812 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5813 this, std::placeholders::_1, token);
5814
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005815 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5816 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817 } // release lock
5818
5819 // Wake the looper because some connections have changed.
5820 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005821 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005822}
5823
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005824Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005825 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005826 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005827 std::shared_ptr<InputChannel> serverChannel;
5828 std::unique_ptr<InputChannel> clientChannel;
5829 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5830 if (result) {
5831 return base::Error(result) << "Failed to open input channel pair with name " << name;
5832 }
5833
Michael Wright3dd60e22019-03-27 22:06:44 +00005834 { // acquire lock
5835 std::scoped_lock _l(mLock);
5836
5837 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005838 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5839 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005840 }
5841
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005842 std::shared_ptr<Connection> connection =
5843 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005844 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005845 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005846
5847 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5848 ALOGE("Created a new connection, but the token %p is already known", token.get());
5849 }
5850 mConnectionsByToken.emplace(token, connection);
5851 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5852 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005853
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005854 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005855
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005856 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5857 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005858 }
Garfield Tan15601662020-09-22 15:32:38 -07005859
Michael Wright3dd60e22019-03-27 22:06:44 +00005860 // Wake the looper because some connections have changed.
5861 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005862 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005863}
5864
Garfield Tan15601662020-09-22 15:32:38 -07005865status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005866 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005867 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005868
Harry Cutts33476232023-01-30 19:57:29 +00005869 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870 if (status) {
5871 return status;
5872 }
5873 } // release lock
5874
5875 // Wake the poll loop because removing the connection may have changed the current
5876 // synchronization state.
5877 mLooper->wake();
5878 return OK;
5879}
5880
Garfield Tan15601662020-09-22 15:32:38 -07005881status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5882 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005883 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005884 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005885 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005886 return BAD_VALUE;
5887 }
5888
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005889 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005890
Michael Wrightd02c5b62014-02-10 15:10:22 -08005891 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005892 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893 }
5894
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005895 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005896
5897 nsecs_t currentTime = now();
5898 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5899
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005900 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005901 return OK;
5902}
5903
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005904void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005905 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5906 auto& [displayId, monitors] = *it;
5907 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5908 return monitor.inputChannel->getConnectionToken() == connectionToken;
5909 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005910
Michael Wright3dd60e22019-03-27 22:06:44 +00005911 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005912 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005913 } else {
5914 ++it;
5915 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005916 }
5917}
5918
Michael Wright3dd60e22019-03-27 22:06:44 +00005919status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005920 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005921 return pilferPointersLocked(token);
5922}
Michael Wright3dd60e22019-03-27 22:06:44 +00005923
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005924status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005925 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5926 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005927 LOG(WARNING)
5928 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005929 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005930 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005931
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005932 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005933 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005934 LOG(WARNING)
5935 << "Attempted to pilfer points from a channel without any on-going pointer streams."
5936 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005937 return BAD_VALUE;
5938 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005939 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5940 if (deviceIds.size() != 1) {
5941 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5942 << " in window: " << windowPtr->dump();
5943 return BAD_VALUE;
5944 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005945
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005946 for (const DeviceId deviceId : deviceIds) {
5947 TouchState& state = *statePtr;
5948 TouchedWindow& window = *windowPtr;
5949 // Send cancel events to all the input channels we're stealing from.
5950 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5951 "input channel stole pointer stream");
5952 options.deviceId = deviceId;
5953 options.displayId = displayId;
5954 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
5955 options.pointerIds = pointerIds;
5956 std::string canceledWindows;
5957 for (const TouchedWindow& w : state.windows) {
5958 const std::shared_ptr<InputChannel> channel =
5959 getInputChannelLocked(w.windowHandle->getToken());
5960 if (channel != nullptr && channel->getConnectionToken() != token) {
5961 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5962 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5963 canceledWindows += channel->getName();
5964 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005965 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005966 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5967 LOG(INFO) << "Channel " << requestingChannel->getName()
5968 << " is stealing input gesture for device " << deviceId << " from "
5969 << canceledWindows;
5970
5971 // Prevent the gesture from being sent to any other windows.
5972 // This only blocks relevant pointers to be sent to other windows
5973 window.addPilferingPointers(deviceId, pointerIds);
5974
5975 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005976 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005977 return OK;
5978}
5979
Prabir Pradhan99987712020-11-10 18:43:05 -08005980void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5981 { // acquire lock
5982 std::scoped_lock _l(mLock);
5983 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005984 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005985 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5986 windowHandle != nullptr ? windowHandle->getName().c_str()
5987 : "token without window");
5988 }
5989
Vishnu Nairc519ff72021-01-21 08:23:08 -08005990 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005991 if (focusedToken != windowToken) {
5992 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5993 enabled ? "enable" : "disable");
5994 return;
5995 }
5996
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005997 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005998 ALOGW("Ignoring request to %s Pointer Capture: "
5999 "window has %s requested pointer capture.",
6000 enabled ? "enable" : "disable", enabled ? "already" : "not");
6001 return;
6002 }
6003
Christine Franksb768bb42021-11-29 12:11:31 -08006004 if (enabled) {
6005 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6006 mIneligibleDisplaysForPointerCapture.end(),
6007 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6008 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6009 return;
6010 }
6011 }
6012
Prabir Pradhan99987712020-11-10 18:43:05 -08006013 setPointerCaptureLocked(enabled);
6014 } // release lock
6015
6016 // Wake the thread to process command entries.
6017 mLooper->wake();
6018}
6019
Christine Franksb768bb42021-11-29 12:11:31 -08006020void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6021 { // acquire lock
6022 std::scoped_lock _l(mLock);
6023 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6024 if (!isEligible) {
6025 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6026 }
6027 } // release lock
6028}
6029
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006030std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006031 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006032 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006033 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006034 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006035 }
6036 }
6037 }
6038 return std::nullopt;
6039}
6040
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006041std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6042 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006043 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006044 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006045 }
6046
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006047 for (const auto& [token, connection] : mConnectionsByToken) {
6048 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006049 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006050 }
6051 }
Robert Carr4e670e52018-08-15 13:26:12 -07006052
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006053 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006054}
6055
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006056std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006057 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006058 if (connection == nullptr) {
6059 return "<nullptr>";
6060 }
6061 return connection->getInputChannelName();
6062}
6063
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006064void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006065 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006066 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006067}
6068
Prabir Pradhancef936d2021-07-21 16:17:52 +00006069void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006070 const std::shared_ptr<Connection>& connection,
6071 uint32_t seq, bool handled,
6072 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006073 // Handle post-event policy actions.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006074 bool restartEvent;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006075
6076 { // Start critical section
6077 auto dispatchEntryIt =
6078 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6079 [seq](auto& e) { return e->seq == seq; });
6080 if (dispatchEntryIt == connection->waitQueue.end()) {
6081 return;
6082 }
6083
6084 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6085
6086 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6087 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6088 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6089 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6090 }
6091 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6092 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6093 connection->inputChannel->getConnectionToken(),
6094 dispatchEntry.deliveryTime, consumeTime, finishTime);
6095 }
6096
6097 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
6098 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry.eventEntry));
6099 restartEvent =
6100 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6101 } else if (dispatchEntry.eventEntry->type == EventEntry::Type::MOTION) {
6102 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry.eventEntry));
6103 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry,
6104 motionEntry, handled);
6105 } else {
6106 restartEvent = false;
6107 }
6108 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006109
6110 // Dequeue the event and start the next cycle.
6111 // Because the lock might have been released, it is possible that the
6112 // contents of the wait queue to have been drained, so we need to double-check
6113 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006114 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6115 [seq](auto& e) { return e->seq == seq; });
6116 if (entryIt != connection->waitQueue.end()) {
6117 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6118 connection->waitQueue.erase(entryIt);
6119
Prabir Pradhancef936d2021-07-21 16:17:52 +00006120 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6121 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6122 if (!connection->responsive) {
6123 connection->responsive = isConnectionResponsive(*connection);
6124 if (connection->responsive) {
6125 // The connection was unresponsive, and now it's responsive.
6126 processConnectionResponsiveLocked(*connection);
6127 }
6128 }
6129 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006130 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006131 connection->outboundQueue.emplace_front(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006132 traceOutboundQueueLength(*connection);
6133 } else {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006134 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006135 }
6136 }
6137
6138 // Start the next dispatch cycle for this connection.
6139 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006140}
6141
Prabir Pradhancef936d2021-07-21 16:17:52 +00006142void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6143 const sp<IBinder>& newToken) {
6144 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6145 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006146 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006147 };
6148 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006149}
6150
Prabir Pradhancef936d2021-07-21 16:17:52 +00006151void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6152 auto command = [this, token, x, y]() REQUIRES(mLock) {
6153 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006154 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006155 };
6156 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006157}
6158
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006159void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006160 if (connection == nullptr) {
6161 LOG_ALWAYS_FATAL("Caller must check for nullness");
6162 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006163 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6164 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006165 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006166 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006167 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006168 return;
6169 }
6170 /**
6171 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6172 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6173 * has changed. This could cause newer entries to time out before the already dispatched
6174 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6175 * processes the events linearly. So providing information about the oldest entry seems to be
6176 * most useful.
6177 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006178 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6179 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006180 std::string reason =
6181 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006182 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006183 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006184 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006185 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006186 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006187
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006188 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6189
6190 // Stop waking up for events on this connection, it is already unresponsive
6191 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006192}
6193
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006194void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6195 std::string reason =
6196 StringPrintf("%s does not have a focused window", application->getName().c_str());
6197 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006198
Yabin Cui8eb9c552023-06-08 18:05:07 +00006199 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006200 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006201 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006202 };
6203 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006204}
6205
chaviw98318de2021-05-19 16:45:23 -05006206void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006207 const std::string& reason) {
6208 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6209 updateLastAnrStateLocked(windowLabel, reason);
6210}
6211
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006212void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6213 const std::string& reason) {
6214 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006215 updateLastAnrStateLocked(windowLabel, reason);
6216}
6217
6218void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6219 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006221 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006222 struct tm tm;
6223 localtime_r(&t, &tm);
6224 char timestr[64];
6225 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006226 mLastAnrState.clear();
6227 mLastAnrState += INDENT "ANR:\n";
6228 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006229 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6230 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006231 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006232}
6233
Prabir Pradhancef936d2021-07-21 16:17:52 +00006234void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6235 KeyEntry& entry) {
6236 const KeyEvent event = createKeyEvent(entry);
6237 nsecs_t delay = 0;
6238 { // release lock
6239 scoped_unlock unlock(mLock);
6240 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006241 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006242 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6243 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6244 std::to_string(t.duration().count()).c_str());
6245 }
6246 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006247
6248 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006249 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006250 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006251 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006252 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006253 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006254 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256}
6257
Prabir Pradhancef936d2021-07-21 16:17:52 +00006258void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006259 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006260 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006261 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006262 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006263 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006264 };
6265 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006266}
6267
Prabir Pradhanedd96402022-02-15 01:46:16 -08006268void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006269 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006270 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006271 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006272 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006273 };
6274 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006275}
6276
6277/**
6278 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6279 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6280 * command entry to the command queue.
6281 */
6282void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6283 std::string reason) {
6284 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006285 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006286 if (connection.monitor) {
6287 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6288 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006289 pid = findMonitorPidByTokenLocked(connectionToken);
6290 } else {
6291 // The connection is a window
6292 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6293 reason.c_str());
6294 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6295 if (handle != nullptr) {
6296 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006297 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006298 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006299 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006300}
6301
6302/**
6303 * Tell the policy that a connection has become responsive so that it can stop ANR.
6304 */
6305void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6306 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006307 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006308 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006309 pid = findMonitorPidByTokenLocked(connectionToken);
6310 } else {
6311 // The connection is a window
6312 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6313 if (handle != nullptr) {
6314 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006315 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006316 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006317 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006318}
6319
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006320bool InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006321 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006322 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006323 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006324 if (!handled) {
6325 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006326 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006327 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006328 return false;
6329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006330
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006331 // Get the fallback key state.
6332 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006333 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006334 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006335 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006336 connection->inputState.removeFallbackKey(originalKeyCode);
6337 }
6338
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006339 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006340 // If the application handles the original key for which we previously
6341 // generated a fallback or if the window is not a foreground window,
6342 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006343 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006344 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006345 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6346 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6347 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6348 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6349 keyEntry.policyFlags);
6350 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006351 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006352 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006353
6354 mLock.unlock();
6355
Prabir Pradhana41d2442023-04-20 21:30:40 +00006356 if (const auto unhandledKeyFallback =
6357 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6358 event, keyEntry.policyFlags);
6359 unhandledKeyFallback) {
6360 event = *unhandledKeyFallback;
6361 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006362
6363 mLock.lock();
6364
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006365 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006366 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006367 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006368 "application handled the original non-fallback key "
6369 "or is no longer a foreground target, "
6370 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006371 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006372 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006374 connection->inputState.removeFallbackKey(originalKeyCode);
6375 }
6376 } else {
6377 // If the application did not handle a non-fallback key, first check
6378 // that we are in a good state to perform unhandled key event processing
6379 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006380 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006381 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006382 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6383 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6384 "since this is not an initial down. "
6385 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6386 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6387 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006388 return false;
6389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006390
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006391 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006392 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6393 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6394 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6395 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6396 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006397 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006398
6399 mLock.unlock();
6400
Prabir Pradhana41d2442023-04-20 21:30:40 +00006401 bool fallback = false;
6402 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6403 event, keyEntry.policyFlags);
6404 fb) {
6405 fallback = true;
6406 event = *fb;
6407 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006408
6409 mLock.lock();
6410
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006411 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006412 connection->inputState.removeFallbackKey(originalKeyCode);
6413 return false;
6414 }
6415
6416 // Latch the fallback keycode for this key on an initial down.
6417 // The fallback keycode cannot change at any other point in the lifecycle.
6418 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006419 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006420 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006421 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006422 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006423 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006424 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006425 }
6426
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006427 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006428
6429 // Cancel the fallback key if the policy decides not to send it anymore.
6430 // We will continue to dispatch the key to the policy but we will no
6431 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006432 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6433 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006434 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6435 if (fallback) {
6436 ALOGD("Unhandled key event: Policy requested to send key %d"
6437 "as a fallback for %d, but on the DOWN it had requested "
6438 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006439 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006440 } else {
6441 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6442 "but on the DOWN it had requested to send %d. "
6443 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006444 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006445 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006446 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006447
Michael Wrightfb04fd52022-11-24 22:31:11 +00006448 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006449 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006450 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006451 synthesizeCancelationEventsForConnectionLocked(connection, options);
6452
6453 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006454 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006455 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006456 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006457 }
6458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006459
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006460 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6461 {
6462 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006463 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006464 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006465 for (const auto& [key, value] : fallbackKeys) {
6466 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006467 }
6468 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6469 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006470 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006471 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006472
6473 if (fallback) {
6474 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006475 keyEntry.eventTime = event.getEventTime();
6476 keyEntry.deviceId = event.getDeviceId();
6477 keyEntry.source = event.getSource();
6478 keyEntry.displayId = event.getDisplayId();
6479 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006480 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006481 keyEntry.scanCode = event.getScanCode();
6482 keyEntry.metaState = event.getMetaState();
6483 keyEntry.repeatCount = event.getRepeatCount();
6484 keyEntry.downTime = event.getDownTime();
6485 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006486
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006487 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6488 ALOGD("Unhandled key event: Dispatching fallback key. "
6489 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006490 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006491 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006492 return true; // restart the event
6493 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006494 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6495 ALOGD("Unhandled key event: No fallback key.");
6496 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006497
6498 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006499 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006500 }
6501 }
6502 return false;
6503}
6504
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006505bool InputDispatcher::afterMotionEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006506 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006507 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006508 return false;
6509}
6510
Michael Wrightd02c5b62014-02-10 15:10:22 -08006511void InputDispatcher::traceInboundQueueLengthLocked() {
6512 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006513 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006514 }
6515}
6516
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006517void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006518 if (ATRACE_ENABLED()) {
6519 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006520 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6521 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006522 }
6523}
6524
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006525void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006526 if (ATRACE_ENABLED()) {
6527 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006528 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6529 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006530 }
6531}
6532
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006533void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006534 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006535
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006536 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006537 dumpDispatchStateLocked(dump);
6538
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006539 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006540 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006541 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006542 }
6543}
6544
6545void InputDispatcher::monitor() {
6546 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006547 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006548 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006549 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006550}
6551
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006552/**
6553 * Wake up the dispatcher and wait until it processes all events and commands.
6554 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6555 * this method can be safely called from any thread, as long as you've ensured that
6556 * the work you are interested in completing has already been queued.
6557 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006558bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006559 /**
6560 * Timeout should represent the longest possible time that a device might spend processing
6561 * events and commands.
6562 */
6563 constexpr std::chrono::duration TIMEOUT = 100ms;
6564 std::unique_lock lock(mLock);
6565 mLooper->wake();
6566 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6567 return result == std::cv_status::no_timeout;
6568}
6569
Vishnu Naire798b472020-07-23 13:52:21 -07006570/**
6571 * Sets focus to the window identified by the token. This must be called
6572 * after updating any input window handles.
6573 *
6574 * Params:
6575 * request.token - input channel token used to identify the window that should gain focus.
6576 * request.focusedToken - the token that the caller expects currently to be focused. If the
6577 * specified token does not match the currently focused window, this request will be dropped.
6578 * If the specified focused token matches the currently focused window, the call will succeed.
6579 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6580 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6581 * when requesting the focus change. This determines which request gets
6582 * precedence if there is a focus change request from another source such as pointer down.
6583 */
Vishnu Nair958da932020-08-21 17:12:37 -07006584void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6585 { // acquire lock
6586 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006587 std::optional<FocusResolver::FocusChanges> changes =
6588 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6589 if (changes) {
6590 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006591 }
6592 } // release lock
6593 // Wake up poll loop since it may need to make new input dispatching choices.
6594 mLooper->wake();
6595}
6596
Vishnu Nairc519ff72021-01-21 08:23:08 -08006597void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6598 if (changes.oldFocus) {
6599 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006600 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006601 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006602 "focus left window");
6603 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006604 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006605 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006606 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006607 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006608 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006609 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006610 }
6611
Prabir Pradhan99987712020-11-10 18:43:05 -08006612 // If a window has pointer capture, then it must have focus. We need to ensure that this
6613 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6614 // If the window loses focus before it loses pointer capture, then the window can be in a state
6615 // where it has pointer capture but not focus, violating the contract. Therefore we must
6616 // dispatch the pointer capture event before the focus event. Since focus events are added to
6617 // the front of the queue (above), we add the pointer capture event to the front of the queue
6618 // after the focus events are added. This ensures the pointer capture event ends up at the
6619 // front.
6620 disablePointerCaptureForcedLocked();
6621
Vishnu Nairc519ff72021-01-21 08:23:08 -08006622 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006623 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006624 }
6625}
Vishnu Nair958da932020-08-21 17:12:37 -07006626
Prabir Pradhan99987712020-11-10 18:43:05 -08006627void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006628 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006629 return;
6630 }
6631
6632 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6633
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006634 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006635 setPointerCaptureLocked(false);
6636 }
6637
6638 if (!mWindowTokenWithPointerCapture) {
6639 // No need to send capture changes because no window has capture.
6640 return;
6641 }
6642
6643 if (mPendingEvent != nullptr) {
6644 // Move the pending event to the front of the queue. This will give the chance
6645 // for the pending event to be dropped if it is a captured event.
6646 mInboundQueue.push_front(mPendingEvent);
6647 mPendingEvent = nullptr;
6648 }
6649
6650 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006651 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006652 mInboundQueue.push_front(std::move(entry));
6653}
6654
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006655void InputDispatcher::setPointerCaptureLocked(bool enable) {
6656 mCurrentPointerCaptureRequest.enable = enable;
6657 mCurrentPointerCaptureRequest.seq++;
6658 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006659 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006660 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006661 };
6662 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006663}
6664
Vishnu Nair599f1412021-06-21 10:39:58 -07006665void InputDispatcher::displayRemoved(int32_t displayId) {
6666 { // acquire lock
6667 std::scoped_lock _l(mLock);
6668 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006669 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006670 setFocusedApplicationLocked(displayId, nullptr);
6671 // Call focus resolver to clean up stale requests. This must be called after input windows
6672 // have been removed for the removed display.
6673 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006674 // Reset pointer capture eligibility, regardless of previous state.
6675 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006676 // Remove the associated touch mode state.
6677 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006678 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006679 } // release lock
6680
6681 // Wake up poll loop since it may need to make new input dispatching choices.
6682 mLooper->wake();
6683}
6684
Patrick Williamsd828f302023-04-28 17:52:08 -05006685void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006686 // The listener sends the windows as a flattened array. Separate the windows by display for
6687 // more convenient parsing.
6688 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006689 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006690 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006691 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006692 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006693
6694 { // acquire lock
6695 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006696
6697 // Ensure that we have an entry created for all existing displays so that if a displayId has
6698 // no windows, we can tell that the windows were removed from the display.
6699 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6700 handlesPerDisplay[displayId];
6701 }
6702
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006703 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006704 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006705 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6706 }
6707
6708 for (const auto& [displayId, handles] : handlesPerDisplay) {
6709 setInputWindowsLocked(handles, displayId);
6710 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006711
6712 if (update.vsyncId < mWindowInfosVsyncId) {
6713 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6714 ", current update vsync id: %" PRId64,
6715 mWindowInfosVsyncId, update.vsyncId);
6716 }
6717 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006718 }
6719 // Wake up poll loop since it may need to make new input dispatching choices.
6720 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006721}
6722
Vishnu Nair062a8672021-09-03 16:07:44 -07006723bool InputDispatcher::shouldDropInput(
6724 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006725 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6726 (windowHandle->getInfo()->inputConfig.test(
6727 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006728 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006729 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6730 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006731 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006732 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006733 windowHandle->getInfo()->displayId);
6734 return true;
6735 }
6736 return false;
6737}
6738
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006739void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006740 const gui::WindowInfosUpdate& update) {
6741 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006742}
6743
Arthur Hungdfd528e2021-12-08 13:23:04 +00006744void InputDispatcher::cancelCurrentTouch() {
6745 {
6746 std::scoped_lock _l(mLock);
6747 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006748 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006749 "cancel current touch");
6750 synthesizeCancelationEventsForAllConnectionsLocked(options);
6751
6752 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006753 }
6754 // Wake up poll loop since there might be work to do.
6755 mLooper->wake();
6756}
6757
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006758void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6759 std::scoped_lock _l(mLock);
6760 mMonitorDispatchingTimeout = timeout;
6761}
6762
Arthur Hungc539dbb2022-12-08 07:45:36 +00006763void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6764 const sp<WindowInfoHandle>& oldWindowHandle,
6765 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006766 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006767 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006768 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6769 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006770 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6771 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6772 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6773 newWindowHandle->getInfo()->inputConfig.test(
6774 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6775 const sp<WindowInfoHandle> oldWallpaper =
6776 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6777 const sp<WindowInfoHandle> newWallpaper =
6778 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6779 if (oldWallpaper == newWallpaper) {
6780 return;
6781 }
6782
6783 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006784 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6785 addWindowTargetLocked(oldWallpaper,
6786 oldTouchedWindow.targetFlags |
6787 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006788 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6789 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006790 }
6791
6792 if (newWallpaper != nullptr) {
6793 state.addOrUpdateWindow(newWallpaper,
6794 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6795 InputTarget::Flags::WINDOW_IS_OBSCURED |
6796 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006797 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006798 }
6799}
6800
6801void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6802 ftl::Flags<InputTarget::Flags> newTargetFlags,
6803 const sp<WindowInfoHandle> fromWindowHandle,
6804 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006805 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006806 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006807 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6808 fromWindowHandle->getInfo()->inputConfig.test(
6809 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6810 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6811 toWindowHandle->getInfo()->inputConfig.test(
6812 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6813
6814 const sp<WindowInfoHandle> oldWallpaper =
6815 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6816 const sp<WindowInfoHandle> newWallpaper =
6817 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6818 if (oldWallpaper == newWallpaper) {
6819 return;
6820 }
6821
6822 if (oldWallpaper != nullptr) {
6823 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6824 "transferring touch focus to another window");
6825 state.removeWindowByToken(oldWallpaper->getToken());
6826 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6827 }
6828
6829 if (newWallpaper != nullptr) {
6830 nsecs_t downTimeInTarget = now();
6831 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6832 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6833 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6834 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006835 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6836 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006837 std::shared_ptr<Connection> wallpaperConnection =
6838 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006839 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006840 std::shared_ptr<Connection> toConnection =
6841 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006842 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6843 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6844 wallpaperFlags);
6845 }
6846 }
6847}
6848
6849sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6850 const sp<WindowInfoHandle>& windowHandle) const {
6851 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6852 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6853 bool foundWindow = false;
6854 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6855 if (!foundWindow && otherHandle != windowHandle) {
6856 continue;
6857 }
6858 if (windowHandle == otherHandle) {
6859 foundWindow = true;
6860 continue;
6861 }
6862
6863 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6864 return otherHandle;
6865 }
6866 }
6867 return nullptr;
6868}
6869
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006870void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6871 std::scoped_lock _l(mLock);
6872
6873 mConfig.keyRepeatTimeout = timeout;
6874 mConfig.keyRepeatDelay = delay;
6875}
6876
Garfield Tane84e6f92019-08-29 17:28:41 -07006877} // namespace android::inputdispatcher