blob: 45649dd146a810dfeeeec834c155730e93239cfe [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>
Ameer Armalycff4fa52023-10-04 23:45:11 +000028#include <com_android_input_flags.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080029#include <ftl/enum.h>
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070030#include <log/log_event_list.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050032#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070033#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080034#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080035#include <input/PrintTools.h>
Prabir Pradhana37bad12023-08-18 15:55:32 +000036#include <input/TraceTools.h>
tyiu1573a672023-02-21 22:38:32 +000037#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070038#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010039#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070040#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
Michael Wright44753b12020-07-08 13:48:11 +010042#include <cerrno>
43#include <cinttypes>
44#include <climits>
45#include <cstddef>
46#include <ctime>
47#include <queue>
48#include <sstream>
49
Asmita Poddardd9a6cd2023-09-26 15:35:12 +000050#include "../InputDeviceMetricsSource.h"
51
Michael Wright44753b12020-07-08 13:48:11 +010052#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000053#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070054#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010055
Michael Wrightd02c5b62014-02-10 15:10:22 -080056#define INDENT " "
57#define INDENT2 " "
58#define INDENT3 " "
59#define INDENT4 " "
60
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080061using namespace android::ftl::flag_operators;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -070062using android::base::Error;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080063using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000064using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080065using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070066using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050067using android::gui::FocusRequest;
68using android::gui::TouchOcclusionMode;
69using android::gui::WindowInfo;
70using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080071using android::os::InputEventInjectionResult;
72using android::os::InputEventInjectionSync;
Ameer Armalycff4fa52023-10-04 23:45:11 +000073namespace input_flags = com::android::input::flags;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080074
Garfield Tane84e6f92019-08-29 17:28:41 -070075namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
Prabir Pradhancef936d2021-07-21 16:17:52 +000077namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000078// Temporarily releases a held mutex for the lifetime of the instance.
79// Named to match std::scoped_lock
80class scoped_unlock {
81public:
82 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
83 ~scoped_unlock() { mMutex.lock(); }
84
85private:
86 std::mutex& mMutex;
87};
88
Michael Wrightd02c5b62014-02-10 15:10:22 -080089// Default input dispatching timeout if there is no focused application or paused window
90// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080091const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
92 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
93 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
95// Amount of time to allow for all pending events to be processed when an app switch
96// key is on the way. This is used to preempt input dispatch and drop input events
97// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800100const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102// 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 +0000103constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
104
105// Log a warning when an interception call takes longer than this to process.
106constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800107
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700108// Additional key latency in case a connection is still processing some motion events.
109// This will help with the case when a user touched a button that opens a new window,
110// and gives us the chance to dispatch the key to this new window.
111constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
112
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000114constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
115
Antonio Kantekea47acb2021-12-23 12:41:25 -0800116// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000117constexpr int LOGTAG_INPUT_INTERACTION = 62000;
118constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000119constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000120
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000121const ui::Transform kIdentityTransform;
122
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000123inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800124 return systemTime(SYSTEM_TIME_MONOTONIC);
125}
126
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -0700127bool isEmpty(const std::stringstream& ss) {
128 return ss.rdbuf()->in_avail() == 0;
129}
130
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700131inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000132 if (binder == nullptr) {
133 return "<null>";
134 }
135 return StringPrintf("%p", binder.get());
136}
137
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000138static std::string uidString(const gui::Uid& uid) {
139 return uid.toString();
140}
141
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700142Result<void> checkKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700144 case AKEY_EVENT_ACTION_DOWN:
145 case AKEY_EVENT_ACTION_UP:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700146 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700147 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700148 return Error() << "Key event has invalid action code " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149 }
150}
151
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700152Result<void> validateKeyEvent(int32_t action) {
153 return checkKeyAction(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154}
155
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700156Result<void> checkMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800157 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700158 case AMOTION_EVENT_ACTION_DOWN:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700159 case AMOTION_EVENT_ACTION_UP: {
160 if (pointerCount != 1) {
161 return Error() << "invalid pointer count " << pointerCount;
162 }
163 return {};
164 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700165 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700166 case AMOTION_EVENT_ACTION_HOVER_ENTER:
167 case AMOTION_EVENT_ACTION_HOVER_MOVE:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700168 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
169 if (pointerCount < 1) {
170 return Error() << "invalid pointer count " << pointerCount;
171 }
172 return {};
173 }
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800174 case AMOTION_EVENT_ACTION_CANCEL:
175 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700176 case AMOTION_EVENT_ACTION_SCROLL:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700177 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700178 case AMOTION_EVENT_ACTION_POINTER_DOWN:
179 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800180 const int32_t index = MotionEvent::getActionIndex(action);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700181 if (index < 0) {
182 return Error() << "invalid index " << index << " for "
183 << MotionEvent::actionToString(action);
184 }
185 if (index >= pointerCount) {
186 return Error() << "invalid index " << index << " for pointerCount " << pointerCount;
187 }
188 if (pointerCount <= 1) {
189 return Error() << "invalid pointer count " << pointerCount << " for "
190 << MotionEvent::actionToString(action);
191 }
192 return {};
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 }
194 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700195 case AMOTION_EVENT_ACTION_BUTTON_RELEASE: {
196 if (actionButton == 0) {
197 return Error() << "action button should be nonzero for "
198 << MotionEvent::actionToString(action);
199 }
200 return {};
201 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700202 default:
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700203 return Error() << "invalid action " << action;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 }
205}
206
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000207int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500208 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
209}
210
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700211Result<void> validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
212 const PointerProperties* pointerProperties) {
213 Result<void> actionCheck = checkMotionAction(action, actionButton, pointerCount);
214 if (!actionCheck.ok()) {
215 return actionCheck;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 }
217 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700218 return Error() << "Motion event has invalid pointer count " << pointerCount
219 << "; value must be between 1 and " << MAX_POINTERS << ".";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800221 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 for (size_t i = 0; i < pointerCount; i++) {
223 int32_t id = pointerProperties[i].id;
224 if (id < 0 || id > MAX_POINTER_ID) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700225 return Error() << "Motion event has invalid pointer id " << id
226 << "; value must be between 0 and " << MAX_POINTER_ID;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800227 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800228 if (pointerIdBits.test(id)) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700229 return Error() << "Motion event has duplicate pointer id " << id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800231 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -0700233 return {};
234}
235
236Result<void> validateInputEvent(const InputEvent& event) {
237 switch (event.getType()) {
238 case InputEventType::KEY: {
239 const KeyEvent& key = static_cast<const KeyEvent&>(event);
240 const int32_t action = key.getAction();
241 return validateKeyEvent(action);
242 }
243 case InputEventType::MOTION: {
244 const MotionEvent& motion = static_cast<const MotionEvent&>(event);
245 const int32_t action = motion.getAction();
246 const size_t pointerCount = motion.getPointerCount();
247 const PointerProperties* pointerProperties = motion.getPointerProperties();
248 const int32_t actionButton = motion.getActionButton();
249 return validateMotionEvent(action, actionButton, pointerCount, pointerProperties);
250 }
251 default: {
252 return {};
253 }
254 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255}
256
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000257std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000259 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260 }
261
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000262 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263 bool first = true;
264 Region::const_iterator cur = region.begin();
265 Region::const_iterator const tail = region.end();
266 while (cur != tail) {
267 if (first) {
268 first = false;
269 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800270 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800271 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800272 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800273 cur++;
274 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000275 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800276}
277
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000278std::string dumpQueue(const std::deque<std::unique_ptr<DispatchEntry>>& queue,
279 nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500280 constexpr size_t maxEntries = 50; // max events to print
281 constexpr size_t skipBegin = maxEntries / 2;
282 const size_t skipEnd = queue.size() - maxEntries / 2;
283 // skip from maxEntries / 2 ... size() - maxEntries/2
284 // only print from 0 .. skipBegin and then from skipEnd .. size()
285
286 std::string dump;
287 for (size_t i = 0; i < queue.size(); i++) {
288 const DispatchEntry& entry = *queue[i];
289 if (i >= skipBegin && i < skipEnd) {
290 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
291 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
292 continue;
293 }
294 dump.append(INDENT4);
295 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800296 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
297 "ms",
298 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500299 ns2ms(currentTime - entry.eventEntry->eventTime));
300 if (entry.deliveryTime != 0) {
301 // This entry was delivered, so add information on how long we've been waiting
302 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
303 }
304 dump.append("\n");
305 }
306 return dump;
307}
308
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700309/**
310 * Find the entry in std::unordered_map by key, and return it.
311 * If the entry is not found, return a default constructed entry.
312 *
313 * Useful when the entries are vectors, since an empty vector will be returned
314 * if the entry is not found.
315 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
316 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700317template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000318V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700319 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700320 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800321}
322
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000323bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700324 if (first == second) {
325 return true;
326 }
327
328 if (first == nullptr || second == nullptr) {
329 return false;
330 }
331
332 return first->getToken() == second->getToken();
333}
334
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000335bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000336 if (first == nullptr || second == nullptr) {
337 return false;
338 }
339 return first->applicationInfo.token != nullptr &&
340 first->applicationInfo.token == second->applicationInfo.token;
341}
342
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800343template <typename T>
344size_t firstMarkedBit(T set) {
345 // TODO: replace with std::countr_zero from <bit> when that's available
346 LOG_ALWAYS_FATAL_IF(set.none());
347 size_t i = 0;
348 while (!set.test(i)) {
349 i++;
350 }
351 return i;
352}
353
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800354std::unique_ptr<DispatchEntry> createDispatchEntry(
355 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
356 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700357 if (inputTarget.useDefaultPointerTransform()) {
358 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700359 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700360 inputTarget.displayTransform,
361 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000362 }
363
364 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
365 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700367 std::vector<PointerCoords> pointerCoords;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700368 pointerCoords.resize(motionEntry.getPointerCount());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000369
370 // Use the first pointer information to normalize all other pointers. This could be any pointer
371 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700372 // uses the transform for the normalized pointer.
373 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800374 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700375 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000376
377 // Iterate through all pointers in the event to normalize against the first.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700378 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount(); pointerIndex++) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000379 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
380 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700381 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000382
383 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700384 // First, apply the current pointer's transform to update the coordinates into
385 // window space.
386 pointerCoords[pointerIndex].transform(currTransform);
387 // Next, apply the inverse transform of the normalized coordinates so the
388 // current coordinates are transformed into the normalized coordinate space.
389 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000390 }
391
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700392 std::unique_ptr<MotionEntry> combinedMotionEntry =
393 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
394 motionEntry.deviceId, motionEntry.source,
395 motionEntry.displayId, motionEntry.policyFlags,
396 motionEntry.action, motionEntry.actionButton,
397 motionEntry.flags, motionEntry.metaState,
398 motionEntry.buttonState, motionEntry.classification,
399 motionEntry.edgeFlags, motionEntry.xPrecision,
400 motionEntry.yPrecision, motionEntry.xCursorPosition,
401 motionEntry.yCursorPosition, motionEntry.downTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -0700402 motionEntry.pointerProperties, pointerCoords);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000403
404 if (motionEntry.injectionState) {
405 combinedMotionEntry->injectionState = motionEntry.injectionState;
406 combinedMotionEntry->injectionState->refCount += 1;
407 }
408
409 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700410 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700411 firstPointerTransform, inputTarget.displayTransform,
412 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000413 return dispatchEntry;
414}
415
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000416status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
417 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700418 std::unique_ptr<InputChannel> uniqueServerChannel;
419 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
420
421 serverChannel = std::move(uniqueServerChannel);
422 return result;
423}
424
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500425template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000426bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500427 if (lhs == nullptr && rhs == nullptr) {
428 return true;
429 }
430 if (lhs == nullptr || rhs == nullptr) {
431 return false;
432 }
433 return *lhs == *rhs;
434}
435
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000436KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000437 KeyEvent event;
438 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
439 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
440 entry.repeatCount, entry.downTime, entry.eventTime);
441 return event;
442}
443
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000444bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000445 // Do not keep track of gesture monitors. They receive every event and would disproportionately
446 // affect the statistics.
447 if (connection.monitor) {
448 return false;
449 }
450 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
451 if (!connection.responsive) {
452 return false;
453 }
454 return true;
455}
456
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000457bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000458 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
459 const int32_t& inputEventId = eventEntry.id;
460 if (inputEventId != dispatchEntry.resolvedEventId) {
461 // Event was transmuted
462 return false;
463 }
464 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
465 return false;
466 }
467 // Only track latency for events that originated from hardware
468 if (eventEntry.isSynthesized()) {
469 return false;
470 }
471 const EventEntry::Type& inputEventEntryType = eventEntry.type;
472 if (inputEventEntryType == EventEntry::Type::KEY) {
473 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
474 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
475 return false;
476 }
477 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
478 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
479 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
480 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
481 return false;
482 }
483 } else {
484 // Not a key or a motion
485 return false;
486 }
487 if (!shouldReportMetricsForConnection(connection)) {
488 return false;
489 }
490 return true;
491}
492
Prabir Pradhancef936d2021-07-21 16:17:52 +0000493/**
494 * Connection is responsive if it has no events in the waitQueue that are older than the
495 * current time.
496 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000497bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000498 const nsecs_t currentTime = now();
Prabir Pradhan8c90d782023-09-15 21:16:44 +0000499 for (const auto& dispatchEntry : connection.waitQueue) {
500 if (dispatchEntry->timeoutTime < currentTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000501 return false;
502 }
503 }
504 return true;
505}
506
Antonio Kantekf16f2832021-09-28 04:39:20 +0000507// Returns true if the event type passed as argument represents a user activity.
508bool isUserActivityEvent(const EventEntry& eventEntry) {
509 switch (eventEntry.type) {
Josep del Riob3981622023-04-18 15:49:45 +0000510 case EventEntry::Type::CONFIGURATION_CHANGED:
511 case EventEntry::Type::DEVICE_RESET:
512 case EventEntry::Type::DRAG:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000513 case EventEntry::Type::FOCUS:
514 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000515 case EventEntry::Type::SENSOR:
Josep del Riob3981622023-04-18 15:49:45 +0000516 case EventEntry::Type::TOUCH_MODE_CHANGED:
Antonio Kantekf16f2832021-09-28 04:39:20 +0000517 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +0000518 case EventEntry::Type::KEY:
519 case EventEntry::Type::MOTION:
520 return true;
521 }
522}
523
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800524// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000525bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000526 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800527 const auto inputConfig = windowInfo.inputConfig;
528 if (windowInfo.displayId != displayId ||
529 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800530 return false;
531 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700532 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800533 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800534 return false;
535 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000536
537 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
538 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
539 // the window. Points on the right and bottom edges should not be inside the window, so we need
540 // to be careful about performing a hit test when the display is rotated, since the "right" and
541 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
542 // logical display in which WM determined the bounds. Perform the hit test in the logical
543 // display space to ensure these edges are considered correctly in all orientations.
544 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
545 const auto p = displayTransform.transform(x, y);
546 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800547 return false;
548 }
549 return true;
550}
551
Prabir Pradhand65552b2021-10-07 11:23:50 -0700552bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
553 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000554 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700555}
556
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800557// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000558// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
559// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
560// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800561// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000562bool canReceiveForegroundTouches(const WindowInfo& info) {
563 // A non-touchable window can still receive touch events (e.g. in the case of
564 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
565 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
566}
567
Prabir Pradhanaeebeb42023-06-13 19:53:03 +0000568bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -0700569 if (windowHandle == nullptr) {
570 return false;
571 }
572 const WindowInfo* windowInfo = windowHandle->getInfo();
573 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
574 return true;
575 }
576 return false;
577}
578
Prabir Pradhan5735a322022-04-11 17:23:34 +0000579// Checks targeted injection using the window's owner's uid.
580// Returns an empty string if an entry can be sent to the given window, or an error message if the
581// entry is a targeted injection whose uid target doesn't match the window owner.
582std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
583 const EventEntry& entry) {
584 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
585 // The event was not injected, or the injected event does not target a window.
586 return {};
587 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000588 const auto uid = *entry.injectionState->targetUid;
Prabir Pradhan5735a322022-04-11 17:23:34 +0000589 if (window == nullptr) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000590 return StringPrintf("No valid window target for injection into uid %s.",
591 uid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000592 }
593 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000594 return StringPrintf("Injected event targeted at uid %s would be dispatched to window '%s' "
595 "owned by uid %s.",
596 uid.toString().c_str(), window->getName().c_str(),
597 window->getInfo()->ownerUid.toString().c_str());
Prabir Pradhan5735a322022-04-11 17:23:34 +0000598 }
599 return {};
600}
601
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000602std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700603 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
604 // Always dispatch mouse events to cursor position.
605 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000606 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700607 }
608
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -0700609 const int32_t pointerIndex = MotionEvent::getActionIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000610 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
611 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700612}
613
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700614std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
615 if (eventEntry.type == EventEntry::Type::KEY) {
616 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
617 return keyEntry.downTime;
618 } else if (eventEntry.type == EventEntry::Type::MOTION) {
619 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
620 return motionEntry.downTime;
621 }
622 return std::nullopt;
623}
624
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000625/**
626 * Compare the old touch state to the new touch state, and generate the corresponding touched
627 * windows (== input targets).
628 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
629 * If the pointer just entered the new window, produce HOVER_ENTER.
630 * For pointers remaining in the window, produce HOVER_MOVE.
631 */
632std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
633 const TouchState& newTouchState,
634 const MotionEntry& entry) {
635 std::vector<TouchedWindow> out;
636 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
637 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
638 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
639 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
640 // Not a hover event - don't need to do anything
641 return out;
642 }
643
644 // We should consider all hovering pointers here. But for now, just use the first one
645 const int32_t pointerId = entry.pointerProperties[0].id;
646
647 std::set<sp<WindowInfoHandle>> oldWindows;
648 if (oldState != nullptr) {
649 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
650 }
651
652 std::set<sp<WindowInfoHandle>> newWindows =
653 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
654
655 // If the pointer is no longer in the new window set, send HOVER_EXIT.
656 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
657 if (newWindows.find(oldWindow) == newWindows.end()) {
658 TouchedWindow touchedWindow;
659 touchedWindow.windowHandle = oldWindow;
660 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000661 out.push_back(touchedWindow);
662 }
663 }
664
665 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
666 TouchedWindow touchedWindow;
667 touchedWindow.windowHandle = newWindow;
668 if (oldWindows.find(newWindow) == oldWindows.end()) {
669 // Any windows that have this pointer now, and didn't have it before, should get
670 // HOVER_ENTER
671 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
672 } else {
673 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700674 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700675 android::base::LogSeverity severity = android::base::LogSeverity::FATAL;
Ameer Armalycff4fa52023-10-04 23:45:11 +0000676 if (!input_flags::a11y_crash_on_inconsistent_event_stream() &&
677 entry.flags & AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT) {
Daniel Norman7487dfa2023-08-02 16:39:45 -0700678 // The Accessibility injected touch exploration event stream
679 // has known inconsistencies, so log ERROR instead of
680 // crashing the device with FATAL.
Daniel Norman7487dfa2023-08-02 16:39:45 -0700681 severity = android::base::LogSeverity::ERROR;
682 }
683 LOG(severity) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700684 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000685 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
686 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -0700687 touchedWindow.addHoveringPointer(entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000688 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
689 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
690 }
691 out.push_back(touchedWindow);
692 }
693 return out;
694}
695
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800696template <typename T>
697std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
698 left.insert(left.end(), right.begin(), right.end());
699 return left;
700}
701
Harry Cuttsb166c002023-05-09 13:06:05 +0000702// Filter windows in a TouchState and targets in a vector to remove untrusted windows/targets from
703// both.
704void filterUntrustedTargets(TouchState& touchState, std::vector<InputTarget>& targets) {
705 std::erase_if(touchState.windows, [&](const TouchedWindow& window) {
706 if (!window.windowHandle->getInfo()->inputConfig.test(
707 WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
708 // In addition to TouchState, erase this window from the input targets! We don't have a
709 // good way to do this today except by adding a nested loop.
710 // TODO(b/282025641): simplify this code once InputTargets are being identified
711 // separately from TouchedWindows.
712 std::erase_if(targets, [&](const InputTarget& target) {
713 return target.inputChannel->getConnectionToken() == window.windowHandle->getToken();
714 });
715 return true;
716 }
717 return false;
718 });
719}
720
Siarhei Vishniakouce1fd472023-09-18 18:38:07 -0700721/**
722 * In general, touch should be always split between windows. Some exceptions:
723 * 1. Don't split touch if all of the below is true:
724 * (a) we have an active pointer down *and*
725 * (b) a new pointer is going down that's from the same device *and*
726 * (c) the window that's receiving the current pointer does not support split touch.
727 * 2. Don't split mouse events
728 */
729bool shouldSplitTouch(const TouchState& touchState, const MotionEntry& entry) {
730 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
731 // We should never split mouse events
732 return false;
733 }
734 for (const TouchedWindow& touchedWindow : touchState.windows) {
735 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
736 // Spy windows should not affect whether or not touch is split.
737 continue;
738 }
739 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
740 continue;
741 }
742 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
743 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
744 // Wallpaper window should not affect whether or not touch is split
745 continue;
746 }
747
748 if (touchedWindow.hasTouchingPointers(entry.deviceId)) {
749 return false;
750 }
751 }
752 return true;
753}
754
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000755} // namespace
756
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757// --- InputDispatcher ---
758
Prabir Pradhana41d2442023-04-20 21:30:40 +0000759InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800760 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
761
Prabir Pradhana41d2442023-04-20 21:30:40 +0000762InputDispatcher::InputDispatcher(InputDispatcherPolicyInterface& policy,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800763 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700764 : mPolicy(policy),
765 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700766 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800767 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700768 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700769 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700770 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800771 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700772 mDispatchEnabled(false),
773 mDispatchFrozen(false),
774 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100775 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000776 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800777 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800778 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000779 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000780 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700781 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800782 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700784 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700785#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700786 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700787#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700788 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800789}
790
791InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000792 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793
Prabir Pradhancef936d2021-07-21 16:17:52 +0000794 resetKeyRepeatLocked();
795 releasePendingEventLocked();
796 drainInboundQueueLocked();
797 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000799 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700800 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000801 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802 }
803}
804
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700805status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700806 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700807 return ALREADY_EXISTS;
808 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700809 mThread = std::make_unique<InputThread>(
810 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
811 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700812}
813
814status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700815 if (mThread && mThread->isCallingThread()) {
816 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700817 return INVALID_OPERATION;
818 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700819 mThread.reset();
820 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700821}
822
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700824 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800826 std::scoped_lock _l(mLock);
827 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800828
829 // Run a dispatch loop if there are no pending commands.
830 // The dispatch loop might enqueue commands to run afterwards.
831 if (!haveCommandsLocked()) {
832 dispatchOnceInnerLocked(&nextWakeupTime);
833 }
834
835 // Run all pending commands if there are any.
836 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000837 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700838 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800840
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700841 // If we are still waiting for ack on some events,
842 // we might have to wake up earlier to check if an app is anr'ing.
843 const nsecs_t nextAnrCheck = processAnrsLocked();
844 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
845
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800846 // We are about to enter an infinitely long sleep, because we have no commands or
847 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700848 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800849 mDispatcherEnteredIdle.notify_all();
850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 } // release lock
852
853 // Wait for callback or timeout or wake. (make sure we round up, not down)
854 nsecs_t currentTime = now();
855 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
856 mLooper->pollOnce(timeoutMillis);
857}
858
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700859/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500860 * Raise ANR if there is no focused window.
861 * Before the ANR is raised, do a final state check:
862 * 1. The currently focused application must be the same one we are waiting for.
863 * 2. Ensure we still don't have a focused window.
864 */
865void InputDispatcher::processNoFocusedWindowAnrLocked() {
866 // Check if the application that we are waiting for is still focused.
867 std::shared_ptr<InputApplicationHandle> focusedApplication =
868 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
869 if (focusedApplication == nullptr ||
870 focusedApplication->getApplicationToken() !=
871 mAwaitedFocusedApplication->getApplicationToken()) {
872 // Unexpected because we should have reset the ANR timer when focused application changed
873 ALOGE("Waited for a focused window, but focused application has already changed to %s",
874 focusedApplication->getName().c_str());
875 return; // The focused application has changed.
876 }
877
chaviw98318de2021-05-19 16:45:23 -0500878 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500879 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
880 if (focusedWindowHandle != nullptr) {
881 return; // We now have a focused window. No need for ANR.
882 }
883 onAnrLocked(mAwaitedFocusedApplication);
884}
885
886/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700887 * Check if any of the connections' wait queues have events that are too old.
888 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
889 * Return the time at which we should wake up next.
890 */
891nsecs_t InputDispatcher::processAnrsLocked() {
892 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700893 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700894 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
895 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
896 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500897 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700898 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500899 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700900 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700901 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500902 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700903 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
904 }
905 }
906
907 // Check if any connection ANRs are due
908 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
909 if (currentTime < nextAnrCheck) { // most likely scenario
910 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
911 }
912
913 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700914 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700915 if (connection == nullptr) {
916 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
917 return nextAnrCheck;
918 }
919 connection->responsive = false;
920 // Stop waking up for this unresponsive connection
921 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000922 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700923 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700924}
925
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800926std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700927 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800928 if (connection->monitor) {
929 return mMonitorDispatchingTimeout;
930 }
931 const sp<WindowInfoHandle> window =
932 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700933 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500934 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700935 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500936 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700937}
938
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
940 nsecs_t currentTime = now();
941
Jeff Browndc5992e2014-04-11 01:27:26 -0700942 // Reset the key repeat timer whenever normal dispatch is suspended while the
943 // device is in a non-interactive state. This is to ensure that we abort a key
944 // repeat if the device is just coming out of sleep.
945 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 resetKeyRepeatLocked();
947 }
948
949 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
950 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100951 if (DEBUG_FOCUS) {
952 ALOGD("Dispatch frozen. Waiting some more.");
953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 return;
955 }
956
957 // Optimize latency of app switches.
958 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
959 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
960 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
961 if (mAppSwitchDueTime < *nextWakeupTime) {
962 *nextWakeupTime = mAppSwitchDueTime;
963 }
964
965 // Ready to start a new event.
966 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700967 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700968 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 if (isAppSwitchDue) {
970 // The inbound queue is empty so the app switch key we were waiting
971 // for will never arrive. Stop waiting for it.
972 resetPendingAppSwitchLocked(false);
973 isAppSwitchDue = false;
974 }
975
976 // Synthesize a key repeat if appropriate.
977 if (mKeyRepeatState.lastKeyEntry) {
978 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
979 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
980 } else {
981 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
982 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
983 }
984 }
985 }
986
987 // Nothing to do if there is no pending event.
988 if (!mPendingEvent) {
989 return;
990 }
991 } else {
992 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700993 mPendingEvent = mInboundQueue.front();
994 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995 traceInboundQueueLengthLocked();
996 }
997
998 // Poke user activity for this event.
999 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001000 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 }
1003
1004 // Now we have an event to dispatch.
1005 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -07001006 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001008 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001010 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001011 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001012 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001013 }
1014
1015 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001016 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 }
1018
1019 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001020 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001021 const ConfigurationChangedEntry& typedEntry =
1022 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001023 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001024 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001025 break;
1026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001028 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001029 const DeviceResetEntry& typedEntry =
1030 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001032 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001033 break;
1034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001036 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001037 std::shared_ptr<FocusEntry> typedEntry =
1038 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001039 dispatchFocusLocked(currentTime, typedEntry);
1040 done = true;
1041 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
1042 break;
1043 }
1044
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001045 case EventEntry::Type::TOUCH_MODE_CHANGED: {
1046 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
1047 dispatchTouchModeChangeLocked(currentTime, typedEntry);
1048 done = true;
1049 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
1050 break;
1051 }
1052
Prabir Pradhan99987712020-11-10 18:43:05 -08001053 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
1054 const auto typedEntry =
1055 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
1056 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
1057 done = true;
1058 break;
1059 }
1060
arthurhungb89ccb02020-12-30 16:19:01 +08001061 case EventEntry::Type::DRAG: {
1062 std::shared_ptr<DragEntry> typedEntry =
1063 std::static_pointer_cast<DragEntry>(mPendingEvent);
1064 dispatchDragLocked(currentTime, typedEntry);
1065 done = true;
1066 break;
1067 }
1068
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001069 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001070 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001072 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 resetPendingAppSwitchLocked(true);
1074 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001075 } else if (dropReason == DropReason::NOT_DROPPED) {
1076 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001077 }
1078 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001079 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001080 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001081 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001082 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1083 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001084 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001085 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001086 break;
1087 }
1088
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001089 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001090 std::shared_ptr<MotionEntry> motionEntry =
1091 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001092 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1093 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001095 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001096 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001097 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001098 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
1099 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001100 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001101 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001102 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103 }
Chris Yef59a2f42020-10-16 12:55:26 -07001104
1105 case EventEntry::Type::SENSOR: {
1106 std::shared_ptr<SensorEntry> sensorEntry =
1107 std::static_pointer_cast<SensorEntry>(mPendingEvent);
1108 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1109 dropReason = DropReason::APP_SWITCH;
1110 }
1111 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1112 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1113 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1114 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1115 dropReason = DropReason::STALE;
1116 }
1117 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1118 done = true;
1119 break;
1120 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001121 }
1122
1123 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001124 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001125 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 }
Michael Wright3a981722015-06-10 15:26:13 +01001127 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001128
1129 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001130 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 }
1132}
1133
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001134bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1135 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1136}
1137
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001138/**
1139 * Return true if the events preceding this incoming motion event should be dropped
1140 * Return false otherwise (the default behaviour)
1141 */
1142bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001143 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001144 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001145
1146 // Optimize case where the current application is unresponsive and the user
1147 // decides to touch a window in a different application.
1148 // If the application takes too long to catch up then we drop all events preceding
1149 // the touch into the other window.
1150 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001151 const int32_t displayId = motionEntry.displayId;
1152 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001153 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001154
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001155 sp<WindowInfoHandle> touchedWindowHandle =
1156 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001157 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001158 touchedWindowHandle->getApplicationToken() !=
1159 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001160 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001161 ALOGI("Pruning input queue because user touched a different application while waiting "
1162 "for %s",
1163 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001164 return true;
1165 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001166
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001167 // Alternatively, maybe there's a spy window that could handle this event.
1168 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1169 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1170 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001171 const std::shared_ptr<Connection> connection =
1172 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001173 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001174 // This spy window could take more input. Drop all events preceding this
1175 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001176 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001177 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001178 mAwaitedFocusedApplication->getName().c_str());
1179 return true;
1180 }
1181 }
1182 }
1183
1184 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1185 // yet been processed by some connections, the dispatcher will wait for these motion
1186 // events to be processed before dispatching the key event. This is because these motion events
1187 // may cause a new window to be launched, which the user might expect to receive focus.
1188 // To prevent waiting forever for such events, just send the key to the currently focused window
1189 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1190 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1191 "just send the pending key event to the focused window.");
1192 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001193 }
1194 return false;
1195}
1196
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001197bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001198 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001199 mInboundQueue.push_back(std::move(newEntry));
1200 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 traceInboundQueueLengthLocked();
1202
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001203 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001204 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001205 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1206 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001207 // Optimize app switch latency.
1208 // If the application takes too long to catch up then we drop all events preceding
1209 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001210 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001211 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001212 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001213 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001214 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001215 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001216 if (DEBUG_APP_SWITCH) {
1217 ALOGD("App switch is pending!");
1218 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001219 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001220 mAppSwitchSawKeyDown = false;
1221 needWake = true;
1222 }
1223 }
1224 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001225
1226 // If a new up event comes in, and the pending event with same key code has been asked
1227 // to try again later because of the policy. We have to reset the intercept key wake up
1228 // time for it may have been handled in the policy and could be dropped.
1229 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1230 mPendingEvent->type == EventEntry::Type::KEY) {
1231 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1232 if (pendingKey.keyCode == keyEntry.keyCode &&
1233 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001234 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1235 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001236 pendingKey.interceptKeyWakeupTime = 0;
1237 needWake = true;
1238 }
1239 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001240 break;
1241 }
1242
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001243 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001244 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1245 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001246 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1247 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001248 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001250 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001252 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001253 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1254 break;
1255 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001256 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001257 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001258 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001259 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001260 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1261 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001262 // nothing to do
1263 break;
1264 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 }
1266
1267 return needWake;
1268}
1269
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001270void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001271 // Do not store sensor event in recent queue to avoid flooding the queue.
1272 if (entry->type != EventEntry::Type::SENSOR) {
1273 mRecentQueue.push_back(entry);
1274 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001275 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001276 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 }
1278}
1279
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001280sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1281 bool isStylus,
1282 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001284 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001285 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001286 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001287 continue;
1288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001290 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001291 if (!info.isSpy() &&
1292 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001293 return windowHandle;
1294 }
1295 }
1296 return nullptr;
1297}
1298
1299std::vector<InputTarget> InputDispatcher::findOutsideTargetsLocked(
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001300 int32_t displayId, const sp<WindowInfoHandle>& touchedWindow, int32_t pointerId) const {
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001301 if (touchedWindow == nullptr) {
1302 return {};
1303 }
1304 // Traverse windows from front to back until we encounter the touched window.
1305 std::vector<InputTarget> outsideTargets;
1306 const auto& windowHandles = getWindowHandlesLocked(displayId);
1307 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1308 if (windowHandle == touchedWindow) {
1309 // Stop iterating once we found a touched window. Any WATCH_OUTSIDE_TOUCH window
1310 // below the touched window will not get ACTION_OUTSIDE event.
1311 return outsideTargets;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001312 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001313
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001314 const WindowInfo& info = *windowHandle->getInfo();
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001315 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07001316 std::bitset<MAX_POINTER_ID + 1> pointerIds;
1317 pointerIds.set(pointerId);
1318 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE, pointerIds,
1319 /*firstDownTimeInTarget=*/std::nullopt, outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 }
1321 }
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07001322 return outsideTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323}
1324
Prabir Pradhand65552b2021-10-07 11:23:50 -07001325std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001326 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001327 // Traverse windows from front to back and gather the touched spy windows.
1328 std::vector<sp<WindowInfoHandle>> spyWindows;
1329 const auto& windowHandles = getWindowHandlesLocked(displayId);
1330 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1331 const WindowInfo& info = *windowHandle->getInfo();
1332
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001333 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001334 continue;
1335 }
1336 if (!info.isSpy()) {
1337 // The first touched non-spy window was found, so return the spy windows touched so far.
1338 return spyWindows;
1339 }
1340 spyWindows.push_back(windowHandle);
1341 }
1342 return spyWindows;
1343}
1344
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001345void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 const char* reason;
1347 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001348 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001349 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001350 ALOGD("Dropped event because policy consumed it.");
1351 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001352 reason = "inbound event was dropped because the policy consumed it";
1353 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001354 case DropReason::DISABLED:
1355 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001356 ALOGI("Dropped event because input dispatch is disabled.");
1357 }
1358 reason = "inbound event was dropped because input dispatch is disabled";
1359 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001360 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001361 ALOGI("Dropped event because of pending overdue app switch.");
1362 reason = "inbound event was dropped because of pending overdue app switch";
1363 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001364 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001365 ALOGI("Dropped event because the current application is not responding and the user "
1366 "has started interacting with a different application.");
1367 reason = "inbound event was dropped because the current application is not responding "
1368 "and the user has started interacting with a different application";
1369 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001370 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001371 ALOGI("Dropped event because it is stale.");
1372 reason = "inbound event was dropped because it is stale";
1373 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001374 case DropReason::NO_POINTER_CAPTURE:
1375 ALOGI("Dropped event because there is no window with Pointer Capture.");
1376 reason = "inbound event was dropped because there is no window with Pointer Capture";
1377 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001378 case DropReason::NOT_DROPPED: {
1379 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001380 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382 }
1383
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001384 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001385 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001386 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001388 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001390 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001391 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1392 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001393 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001394 synthesizeCancelationEventsForAllConnectionsLocked(options);
1395 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001396 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1397 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001398 synthesizeCancelationEventsForAllConnectionsLocked(options);
1399 }
1400 break;
1401 }
Chris Yef59a2f42020-10-16 12:55:26 -07001402 case EventEntry::Type::SENSOR: {
1403 break;
1404 }
arthurhungb89ccb02020-12-30 16:19:01 +08001405 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1406 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001407 break;
1408 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001409 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001410 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001411 case EventEntry::Type::CONFIGURATION_CHANGED:
1412 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001413 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001414 break;
1415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 }
1417}
1418
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001419static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001420 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1421 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422}
1423
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001424bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1425 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1426 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1427 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428}
1429
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001430bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001431 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432}
1433
1434void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001435 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001437 if (DEBUG_APP_SWITCH) {
1438 if (handled) {
1439 ALOGD("App switch has arrived.");
1440 } else {
1441 ALOGD("App switch was abandoned.");
1442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444}
1445
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001447 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448}
1449
Prabir Pradhancef936d2021-07-21 16:17:52 +00001450bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001451 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001452 return false;
1453 }
1454
1455 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001456 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001457 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001458 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1459 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001460 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461 return true;
1462}
1463
Prabir Pradhancef936d2021-07-21 16:17:52 +00001464void InputDispatcher::postCommandLocked(Command&& command) {
1465 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466}
1467
1468void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001469 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001470 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001471 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001472 releaseInboundEventLocked(entry);
1473 }
1474 traceInboundQueueLengthLocked();
1475}
1476
1477void InputDispatcher::releasePendingEventLocked() {
1478 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001480 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481 }
1482}
1483
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001484void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001486 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001487 if (DEBUG_DISPATCH_CYCLE) {
1488 ALOGD("Injected inbound event was dropped.");
1489 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001490 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 }
1492 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001493 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 }
1495 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496}
1497
1498void InputDispatcher::resetKeyRepeatLocked() {
1499 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001500 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 }
1502}
1503
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001504std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1505 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506
Michael Wright2e732952014-09-24 13:26:59 -07001507 uint32_t policyFlags = entry->policyFlags &
1508 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001510 std::shared_ptr<KeyEntry> newEntry =
1511 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1512 entry->source, entry->displayId, policyFlags, entry->action,
1513 entry->flags, entry->keyCode, entry->scanCode,
1514 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001516 newEntry->syntheticRepeat = true;
1517 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001519 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520}
1521
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001522bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001523 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001524 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1525 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527
1528 // Reset key repeating in case a keyboard device was added or removed or something.
1529 resetKeyRepeatLocked();
1530
1531 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001532 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1533 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00001534 mPolicy.notifyConfigurationChanged(eventTime);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001535 };
1536 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 return true;
1538}
1539
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001540bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1541 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001542 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1543 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1544 entry.deviceId);
1545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546
liushenxiang42232912021-05-21 20:24:09 +08001547 // Reset key repeating in case a keyboard device was disabled or enabled.
1548 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1549 resetKeyRepeatLocked();
1550 }
1551
Michael Wrightfb04fd52022-11-24 22:31:11 +00001552 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001553 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 synthesizeCancelationEventsForAllConnectionsLocked(options);
Siarhei Vishniakou0686f0c2023-05-02 11:56:15 -07001555
1556 // Remove all active pointers from this device
1557 for (auto& [_, touchState] : mTouchStatesByDisplay) {
1558 touchState.removeAllPointersForDevice(entry.deviceId);
1559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 return true;
1561}
1562
Vishnu Nairad321cd2020-08-20 16:40:21 -07001563void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001564 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001565 if (mPendingEvent != nullptr) {
1566 // Move the pending event to the front of the queue. This will give the chance
1567 // for the pending event to get dispatched to the newly focused window
1568 mInboundQueue.push_front(mPendingEvent);
1569 mPendingEvent = nullptr;
1570 }
1571
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001572 std::unique_ptr<FocusEntry> focusEntry =
1573 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1574 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001575
1576 // This event should go to the front of the queue, but behind all other focus events
1577 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001578 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001579 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001580 [](const std::shared_ptr<EventEntry>& event) {
1581 return event->type == EventEntry::Type::FOCUS;
1582 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001583
1584 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001585 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001586}
1587
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001588void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001589 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001590 if (channel == nullptr) {
1591 return; // Window has gone away
1592 }
1593 InputTarget target;
1594 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001595 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001596 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001597 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1598 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001599 std::string reason = std::string("reason=").append(entry->reason);
1600 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001601 dispatchEventLocked(currentTime, entry, {target});
1602}
1603
Prabir Pradhan99987712020-11-10 18:43:05 -08001604void InputDispatcher::dispatchPointerCaptureChangedLocked(
1605 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1606 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001607 dropReason = DropReason::NOT_DROPPED;
1608
Prabir Pradhan99987712020-11-10 18:43:05 -08001609 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001610 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001611
1612 if (entry->pointerCaptureRequest.enable) {
1613 // Enable Pointer Capture.
1614 if (haveWindowWithPointerCapture &&
1615 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001616 // This can happen if pointer capture is disabled and re-enabled before we notify the
1617 // app of the state change, so there is no need to notify the app.
1618 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1619 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001620 }
1621 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001622 // This can happen if a window requests capture and immediately releases capture.
1623 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001624 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001625 return;
1626 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001627 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1628 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1629 return;
1630 }
1631
Vishnu Nairc519ff72021-01-21 08:23:08 -08001632 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001633 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1634 mWindowTokenWithPointerCapture = token;
1635 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001636 // Disable Pointer Capture.
1637 // We do not check if the sequence number matches for requests to disable Pointer Capture
1638 // for two reasons:
1639 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1640 // to disable capture with the same sequence number: one generated by
1641 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1642 // Capture being disabled in InputReader.
1643 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1644 // actual Pointer Capture state that affects events being generated by input devices is
1645 // in InputReader.
1646 if (!haveWindowWithPointerCapture) {
1647 // Pointer capture was already forcefully disabled because of focus change.
1648 dropReason = DropReason::NOT_DROPPED;
1649 return;
1650 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001651 token = mWindowTokenWithPointerCapture;
1652 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001653 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001654 setPointerCaptureLocked(false);
1655 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001656 }
1657
1658 auto channel = getInputChannelLocked(token);
1659 if (channel == nullptr) {
1660 // Window has gone away, clean up Pointer Capture state.
1661 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001662 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001663 setPointerCaptureLocked(false);
1664 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001665 return;
1666 }
1667 InputTarget target;
1668 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001669 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001670 entry->dispatchInProgress = true;
1671 dispatchEventLocked(currentTime, entry, {target});
1672
1673 dropReason = DropReason::NOT_DROPPED;
1674}
1675
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001676void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1677 const std::shared_ptr<TouchModeEntry>& entry) {
1678 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001679 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001680 if (windowHandles.empty()) {
1681 return;
1682 }
1683 const std::vector<InputTarget> inputTargets =
1684 getInputTargetsFromWindowHandlesLocked(windowHandles);
1685 if (inputTargets.empty()) {
1686 return;
1687 }
1688 entry->dispatchInProgress = true;
1689 dispatchEventLocked(currentTime, entry, inputTargets);
1690}
1691
1692std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1693 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1694 std::vector<InputTarget> inputTargets;
1695 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001696 const sp<IBinder>& token = handle->getToken();
1697 if (token == nullptr) {
1698 continue;
1699 }
1700 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1701 if (channel == nullptr) {
1702 continue; // Window has gone away
1703 }
1704 InputTarget target;
1705 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001706 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001707 inputTargets.push_back(target);
1708 }
1709 return inputTargets;
1710}
1711
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001712bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001713 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001715 if (!entry->dispatchInProgress) {
1716 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1717 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1718 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1719 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001720 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 // We have seen two identical key downs in a row which indicates that the device
1722 // driver is automatically generating key repeats itself. We take note of the
1723 // repeat here, but we disable our own next key repeat timer since it is clear that
1724 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001725 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1726 // Make sure we don't get key down from a different device. If a different
1727 // device Id has same key pressed down, the new device Id will replace the
1728 // current one to hold the key repeat with repeat count reset.
1729 // In the future when got a KEY_UP on the device id, drop it and do not
1730 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1732 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001733 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 } else {
1735 // Not a repeat. Save key down state in case we do see a repeat later.
1736 resetKeyRepeatLocked();
1737 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1738 }
1739 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001740 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1741 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001742 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001743 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001744 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1745 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001746 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747 resetKeyRepeatLocked();
1748 }
1749
1750 if (entry->repeatCount == 1) {
1751 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1752 } else {
1753 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1754 }
1755
1756 entry->dispatchInProgress = true;
1757
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001758 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 }
1760
1761 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001762 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763 if (currentTime < entry->interceptKeyWakeupTime) {
1764 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1765 *nextWakeupTime = entry->interceptKeyWakeupTime;
1766 }
1767 return false; // wait until next wakeup
1768 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001769 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001770 entry->interceptKeyWakeupTime = 0;
1771 }
1772
1773 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001774 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001776 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001777 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001778
1779 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1780 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1781 };
1782 postCommandLocked(std::move(command));
Josep del Riob3981622023-04-18 15:49:45 +00001783 // Poke user activity for keys not passed to user
1784 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 return false; // wait for the command to run
1786 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001787 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001789 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001790 if (*dropReason == DropReason::NOT_DROPPED) {
1791 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 }
1793 }
1794
1795 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001796 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001797 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001798 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1799 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001800 mReporter->reportDroppedKey(entry->id);
Josep del Riob3981622023-04-18 15:49:45 +00001801 // Poke user activity for undispatched keys
1802 pokeUserActivityLocked(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 return true;
1804 }
1805
1806 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001807 InputEventInjectionResult injectionResult;
1808 sp<WindowInfoHandle> focusedWindow =
1809 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1810 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001811 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 return false;
1813 }
1814
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001815 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001816 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 return true;
1818 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001819 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1820
1821 std::vector<InputTarget> inputTargets;
1822 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001823 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001824 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001826 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001827 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828
1829 // Dispatch the key.
1830 dispatchEventLocked(currentTime, entry, inputTargets);
1831 return true;
1832}
1833
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001834void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001835 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1836 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1837 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1838 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1839 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1840 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1841 entry.metaState, entry.repeatCount, entry.downTime);
1842 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843}
1844
Prabir Pradhancef936d2021-07-21 16:17:52 +00001845void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1846 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001847 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001848 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1849 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1850 "source=0x%x, sensorType=%s",
1851 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001852 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001853 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001854 auto command = [this, entry]() REQUIRES(mLock) {
1855 scoped_unlock unlock(mLock);
1856
1857 if (entry->accuracyChanged) {
Prabir Pradhana41d2442023-04-20 21:30:40 +00001858 mPolicy.notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001859 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00001860 mPolicy.notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1861 entry->hwTimestamp, entry->values);
Prabir Pradhancef936d2021-07-21 16:17:52 +00001862 };
1863 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001864}
1865
1866bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001867 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1868 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001869 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001870 }
Chris Yef59a2f42020-10-16 12:55:26 -07001871 { // acquire lock
1872 std::scoped_lock _l(mLock);
1873
1874 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1875 std::shared_ptr<EventEntry> entry = *it;
1876 if (entry->type == EventEntry::Type::SENSOR) {
1877 it = mInboundQueue.erase(it);
1878 releaseInboundEventLocked(entry);
1879 }
1880 }
1881 }
1882 return true;
1883}
1884
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001885bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001886 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001887 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001889 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 entry->dispatchInProgress = true;
1891
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001892 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 }
1894
1895 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001896 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001897 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001898 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1899 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 return true;
1901 }
1902
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001903 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904
1905 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001906 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907
1908 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001909 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 if (isPointerEvent) {
1911 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001912
1913 if (mDragState &&
1914 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1915 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1916 pilferPointersLocked(mDragState->dragWindow->getToken());
1917 }
1918
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001919 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001920 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001921 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001922 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1923 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924 } else {
1925 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001926 sp<WindowInfoHandle> focusedWindow =
1927 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1928 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1929 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1930 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001931 InputTarget::Flags::FOREGROUND |
1932 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001933 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001936 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 return false;
1938 }
1939
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001940 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001941 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001942 return true;
1943 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001944 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001945 CancelationOptions::Mode mode(
1946 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1947 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001948 CancelationOptions options(mode, "input event injection failed");
1949 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 return true;
1951 }
1952
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001953 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001954 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955
1956 // Dispatch the motion.
1957 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001958 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001959 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 synthesizeCancelationEventsForAllConnectionsLocked(options);
1961 }
1962 dispatchEventLocked(currentTime, entry, inputTargets);
1963 return true;
1964}
1965
chaviw98318de2021-05-19 16:45:23 -05001966void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001967 bool isExiting, const int32_t rawX,
1968 const int32_t rawY) {
1969 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001970 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001971 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1972 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001973
1974 enqueueInboundEventLocked(std::move(dragEntry));
1975}
1976
1977void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1978 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1979 if (channel == nullptr) {
1980 return; // Window has gone away
1981 }
1982 InputTarget target;
1983 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001984 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001985 entry->dispatchInProgress = true;
1986 dispatchEventLocked(currentTime, entry, {target});
1987}
1988
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001989void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001990 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001991 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001992 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001993 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001994 "metaState=0x%x, buttonState=0x%x,"
1995 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001996 prefix, entry.eventTime, entry.deviceId,
1997 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1998 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1999 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
2000 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002002 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002003 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002004 "x=%f, y=%f, pressure=%f, size=%f, "
2005 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2006 "orientation=%f",
Siarhei Vishniakou09a8fe42022-07-21 17:27:03 -07002007 i, entry.pointerProperties[i].id,
2008 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002009 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2010 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2011 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2012 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2013 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2014 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2015 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2016 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2017 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020}
2021
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002022void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
2023 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002024 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002025 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002026 if (DEBUG_DISPATCH_CYCLE) {
2027 ALOGD("dispatchEventToCurrentInputTargets");
2028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002030 processInteractionsLocked(*eventEntry, inputTargets);
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002031
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
2033
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002034 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002036 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002037 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002038 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002039 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002040 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002041 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002042 if (DEBUG_FOCUS) {
2043 ALOGD("Dropping event delivery to target with channel '%s' because it "
2044 "is no longer registered with the input dispatcher.",
2045 inputTarget.inputChannel->getName().c_str());
2046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 }
2048 }
2049}
2050
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002051void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002052 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
2053 // If the policy decides to close the app, we will get a channel removal event via
2054 // unregisterInputChannel, and will clean up the connection that way. We are already not
2055 // sending new pointers to the connection when it blocked, but focused events will continue to
2056 // pile up.
2057 ALOGW("Canceling events for %s because it is unresponsive",
2058 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002059 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00002060 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002061 "application not responding");
2062 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 }
2064}
2065
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002066void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002067 if (DEBUG_FOCUS) {
2068 ALOGD("Resetting ANR timeouts.");
2069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070
2071 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002072 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07002073 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074}
2075
Tiger Huang721e26f2018-07-24 22:26:19 +08002076/**
2077 * Get the display id that the given event should go to. If this event specifies a valid display id,
2078 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
2079 * Focused display is the display that the user most recently interacted with.
2080 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002081int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002082 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002083 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002084 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002085 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2086 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002087 break;
2088 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002089 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002090 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2091 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002092 break;
2093 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002094 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08002095 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002096 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002097 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07002098 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08002099 case EventEntry::Type::SENSOR:
2100 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08002101 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002102 return ADISPLAY_ID_NONE;
2103 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002104 }
2105 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
2106}
2107
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002108bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
2109 const char* focusedWindowName) {
2110 if (mAnrTracker.empty()) {
2111 // already processed all events that we waited for
2112 mKeyIsWaitingForEventsTimeout = std::nullopt;
2113 return false;
2114 }
2115
2116 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
2117 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00002118 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002119 mKeyIsWaitingForEventsTimeout = currentTime +
2120 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
2121 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002122 return true;
2123 }
2124
2125 // We still have pending events, and already started the timer
2126 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
2127 return true; // Still waiting
2128 }
2129
2130 // Waited too long, and some connection still hasn't processed all motions
2131 // Just send the key to the focused window
2132 ALOGW("Dispatching key to %s even though there are other unprocessed events",
2133 focusedWindowName);
2134 mKeyIsWaitingForEventsTimeout = std::nullopt;
2135 return false;
2136}
2137
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002138sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2139 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2140 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002141 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002142 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143
Tiger Huang721e26f2018-07-24 22:26:19 +08002144 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002145 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002146 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002147 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2148
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 // If there is no currently focused window and no focused application
2150 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002151 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2152 ALOGI("Dropping %s event because there is no focused window or focused application in "
2153 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002154 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002155 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 }
2157
Vishnu Nair062a8672021-09-03 16:07:44 -07002158 // Drop key events if requested by input feature
2159 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002160 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002161 }
2162
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002163 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2164 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2165 // start interacting with another application via touch (app switch). This code can be removed
2166 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2167 // an app is expected to have a focused window.
2168 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2169 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2170 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002171 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2172 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2173 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002174 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002175 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002176 ALOGW("Waiting because no window has focus but %s may eventually add a "
2177 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002178 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002179 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002180 outInjectionResult = InputEventInjectionResult::PENDING;
2181 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002182 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2183 // Already raised ANR. Drop the event
2184 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002185 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002186 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002187 } else {
2188 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002189 outInjectionResult = InputEventInjectionResult::PENDING;
2190 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002191 }
2192 }
2193
2194 // we have a valid, non-null focused window
2195 resetNoFocusedWindowTimeoutLocked();
2196
Prabir Pradhan5735a322022-04-11 17:23:34 +00002197 // Verify targeted injection.
2198 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2199 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002200 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2201 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 }
2203
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002204 if (focusedWindowHandle->getInfo()->inputConfig.test(
2205 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002206 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002207 outInjectionResult = InputEventInjectionResult::PENDING;
2208 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002209 }
2210
2211 // If the event is a key event, then we must wait for all previous events to
2212 // complete before delivering it because previous events may have the
2213 // side-effect of transferring focus to a different window and we want to
2214 // ensure that the following keys are sent to the new window.
2215 //
2216 // Suppose the user touches a button in a window then immediately presses "A".
2217 // If the button causes a pop-up window to appear then we want to ensure that
2218 // the "A" key is delivered to the new pop-up window. This is because users
2219 // often anticipate pending UI changes when typing on a keyboard.
2220 // To obtain this behavior, we must serialize key events with respect to all
2221 // prior input events.
2222 if (entry.type == EventEntry::Type::KEY) {
2223 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2224 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002225 outInjectionResult = InputEventInjectionResult::PENDING;
2226 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228 }
2229
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002230 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2231 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232}
2233
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002234/**
2235 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2236 * that are currently unresponsive.
2237 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002238std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2239 const std::vector<Monitor>& monitors) const {
2240 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002241 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002242 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002243 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002244 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002245 if (connection == nullptr) {
2246 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002247 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002248 return false;
2249 }
2250 if (!connection->responsive) {
2251 ALOGW("Unresponsive monitor %s will not get the new gesture",
2252 connection->inputChannel->getName().c_str());
2253 return false;
2254 }
2255 return true;
2256 });
2257 return responsiveMonitors;
2258}
2259
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002260std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002261 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2262 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002263 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002265 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 // For security reasons, we defer updating the touch state until we are sure that
2267 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002268 const int32_t displayId = entry.displayId;
2269 const int32_t action = entry.action;
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07002270 const int32_t maskedAction = MotionEvent::getActionMasked(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271
2272 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002273 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002275 // Copy current touch state into tempTouchState.
2276 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2277 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002278 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002279 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002280 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2281 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002282 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002283 }
2284
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002285 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002286 bool switchedDevice = false;
2287 if (oldState != nullptr) {
2288 std::set<int32_t> oldActiveDevices = oldState->getActiveDeviceIds();
2289 const bool anotherDeviceIsActive =
2290 oldActiveDevices.count(entry.deviceId) == 0 && !oldActiveDevices.empty();
2291 switchedDevice |= anotherDeviceIsActive;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002292 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002293
2294 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2295 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2296 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002297 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2298 // touchable windows.
2299 const bool wasDown = oldState != nullptr && oldState->isDown();
2300 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2301 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002302 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL ||
2303 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2304 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002305 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002306
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002307 // If pointers are already down, let's finish the current gesture and ignore the new events
2308 // from another device. However, if the new event is a down event, let's cancel the current
2309 // touch and let the new one take over.
2310 if (switchedDevice && wasDown && !isDown) {
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07002311 LOG(INFO) << "Dropping event because a pointer for another device "
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002312 << " is already down in display " << displayId << ": " << entry.getDescription();
2313 // TODO(b/211379801): test multiple simultaneous input streams.
2314 outInjectionResult = InputEventInjectionResult::FAILED;
2315 return {}; // wrong device
2316 }
2317
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002319 // If a new gesture is starting, clear the touch state completely.
2320 tempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002322 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002323 ALOGI("Dropping move event because a pointer for a different device is already active "
2324 "in display %" PRId32,
2325 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002326 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002327 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002328 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 }
2330
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002331 if (isHoverAction) {
2332 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2333 // all of the existing hovering pointers and recompute.
2334 tempTouchState.clearHoveringPointers();
2335 }
2336
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2338 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002339 const auto [x, y] = resolveTouchedPosition(entry);
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002340 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002341 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002342 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2343 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002344 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002345 sp<WindowInfoHandle> newTouchedWindowHandle =
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002346 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002347
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002348 if (isDown) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002349 targets += findOutsideTargetsLocked(displayId, newTouchedWindowHandle, pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002352 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002353 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002355 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002356 }
2357
Prabir Pradhan5735a322022-04-11 17:23:34 +00002358 // Verify targeted injection.
2359 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2360 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002361 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002362 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002363 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002364 }
2365
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002366 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002367 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002368 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2369 // New window supports splitting, but we should never split mouse events.
2370 isSplit = !isFromMouse;
2371 } else if (isSplit) {
2372 // New window does not support splitting but we have already split events.
2373 // Ignore the new window.
Siarhei Vishniakou25537f82023-07-18 14:35:47 -07002374 LOG(INFO) << "Skipping " << newTouchedWindowHandle->getName()
2375 << " because it doesn't support split touch";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002376 newTouchedWindowHandle = nullptr;
2377 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002378 } else {
2379 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002380 // be delivered to a new window which supports split touch. Pointers from a mouse device
2381 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002382 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002383 }
2384
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002385 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002386 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002387 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002388 // Process the foreground window first so that it is the first to receive the event.
2389 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002390 }
2391
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002392 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002393 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2394 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002395 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002396 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002397 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002398 }
2399
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002400 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002401 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002402 continue;
2403 }
2404
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002405 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2406 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoub681c202023-05-01 11:22:33 -07002407 // The "windowHandle" is the target of this hovering pointer.
2408 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId, pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002409 }
2410
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002411 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002412 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002413
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002414 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2415 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002416 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002417 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002418
2419 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002420 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002421 }
2422 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002423 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002424 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002425 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002426 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002427
2428 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002429 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002430 if (!isHoverAction) {
Siarhei Vishniakou70f3d8c2023-09-19 15:36:52 -07002431 pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002432 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002433
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002434 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2435 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2436
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002437 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2438 // still add a window to the touch state. We should avoid doing that, but some of the
2439 // later checks ("at least one foreground window") rely on this in order to dispatch
2440 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002441 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, entry.deviceId, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002442 isDownOrPointerDown
2443 ? std::make_optional(entry.eventTime)
2444 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002445
2446 // If this is the pointer going down and the touched window has a wallpaper
2447 // then also add the touched wallpaper windows so they are locked in for the duration
2448 // of the touch gesture.
2449 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2450 // engine only supports touch events. We would need to add a mechanism similar
2451 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002452 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002453 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2454 windowHandle->getInfo()->inputConfig.test(
2455 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2456 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2457 if (wallpaper != nullptr) {
2458 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2459 InputTarget::Flags::WINDOW_IS_OBSCURED |
2460 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2461 InputTarget::Flags::DISPATCH_AS_IS;
2462 if (isSplit) {
2463 wallpaperFlags |= InputTarget::Flags::SPLIT;
2464 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002465 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, entry.deviceId,
2466 pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002467 }
2468 }
2469 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002471
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002472 // If a window is already pilfering some pointers, give it this new pointer as well and
2473 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2474 // which is a specific behaviour that we want.
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002475 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002476 if (touchedWindow.hasTouchingPointer(entry.deviceId, pointerId) &&
2477 touchedWindow.hasPilferingPointers(entry.deviceId)) {
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002478 // This window is already pilfering some pointers, and this new pointer is also
2479 // going to it. Therefore, take over this pointer and don't give it to anyone
2480 // else.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002481 touchedWindow.addPilferingPointer(entry.deviceId, pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002482 }
2483 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002484
2485 // Restrict all pilfered pointers to the pilfering windows.
2486 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 } else {
2488 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2489
2490 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002491 if (!tempTouchState.isDown() && maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002492 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2493 "dropped the pointer down event in display "
2494 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002495 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002496 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497 }
2498
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002499 // If the pointer is not currently hovering, then ignore the event.
2500 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2501 const int32_t pointerId = entry.pointerProperties[0].id;
2502 if (oldState == nullptr ||
2503 oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId).empty()) {
2504 LOG(INFO) << "Dropping event because the hovering pointer is not in any windows in "
2505 "display "
2506 << displayId << ": " << entry.getDescription();
2507 outInjectionResult = InputEventInjectionResult::FAILED;
2508 return {};
2509 }
2510 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2511 }
2512
arthurhung6d4bed92021-03-17 11:59:33 +08002513 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002514
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002516 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.getPointerCount() == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002517 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002518 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002519 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002520 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002521 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002522 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002523 sp<WindowInfoHandle> newTouchedWindowHandle =
2524 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002525
Prabir Pradhan5735a322022-04-11 17:23:34 +00002526 // Verify targeted injection.
2527 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2528 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002529 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002530 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002531 }
2532
Vishnu Nair062a8672021-09-03 16:07:44 -07002533 // Drop touch events if requested by input feature
2534 if (newTouchedWindowHandle != nullptr &&
2535 shouldDropInput(entry, newTouchedWindowHandle)) {
2536 newTouchedWindowHandle = nullptr;
2537 }
2538
Siarhei Vishniakouafa08cc2023-05-08 22:35:50 -07002539 if (newTouchedWindowHandle != nullptr &&
2540 !haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002541 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2542 oldTouchedWindowHandle->getName().c_str(),
2543 newTouchedWindowHandle->getName().c_str(), displayId);
2544
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002546 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002547 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002548 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002549
2550 const TouchedWindow& touchedWindow =
2551 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2552 addWindowTargetLocked(oldTouchedWindowHandle,
2553 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002554 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555
2556 // Make a slippery entrance into the new window.
2557 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002558 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 }
2560
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002561 ftl::Flags<InputTarget::Flags> targetFlags =
2562 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002563 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002564 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002566 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002567 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 }
2569 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002570 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002571 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002572 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 }
2574
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002575 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags,
2576 entry.deviceId, pointerIds, entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002577
2578 // Check if the wallpaper window should deliver the corresponding event.
2579 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002580 tempTouchState, entry.deviceId, pointerId, targets);
2581 tempTouchState.removeTouchingPointerFromWindow(entry.deviceId, pointerId,
2582 oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 }
2584 }
Arthur Hung96483742022-11-15 03:30:48 +00002585
2586 // Update the pointerIds for non-splittable when it received pointer down.
2587 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2588 // If no split, we suppose all touched windows should receive pointer down.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002589 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
Arthur Hung96483742022-11-15 03:30:48 +00002590 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2591 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2592 // Ignore drag window for it should just track one pointer.
2593 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2594 continue;
2595 }
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002596 std::bitset<MAX_POINTER_ID + 1> touchingPointers;
2597 touchingPointers.set(entry.pointerProperties[pointerIndex].id);
2598 touchedWindow.addTouchingPointers(entry.deviceId, touchingPointers);
Arthur Hung96483742022-11-15 03:30:48 +00002599 }
2600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 }
2602
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002603 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002604 {
2605 std::vector<TouchedWindow> hoveringWindows =
2606 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2607 for (const TouchedWindow& touchedWindow : hoveringWindows) {
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002608 std::optional<InputTarget> target =
2609 createInputTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002610 touchedWindow.getDownTimeInTarget(entry.deviceId));
Siarhei Vishniakoud5876ba2023-05-15 17:58:34 -07002611 if (!target) {
2612 continue;
2613 }
2614 // Hardcode to single hovering pointer for now.
2615 std::bitset<MAX_POINTER_ID + 1> pointerIds;
2616 pointerIds.set(entry.pointerProperties[0].id);
2617 target->addPointers(pointerIds, touchedWindow.windowHandle->getInfo()->transform);
2618 targets.push_back(*target);
Sam Dubeyf886dec2023-01-27 13:28:19 +00002619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621
Prabir Pradhan5735a322022-04-11 17:23:34 +00002622 // Ensure that all touched windows are valid for injection.
2623 if (entry.injectionState != nullptr) {
2624 std::string errs;
2625 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002626 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2627 if (err) errs += "\n - " + *err;
2628 }
2629 if (!errs.empty()) {
2630 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002631 "%s:%s",
2632 entry.injectionState->targetUid->toString().c_str(), errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002633 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002634 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002635 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002636 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002637
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002638 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2639 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002640 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002641 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002642 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002643 if (foregroundWindowHandle) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002644 const auto foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002645 for (InputTarget& target : targets) {
2646 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2647 sp<WindowInfoHandle> targetWindow =
2648 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2649 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2650 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652 }
2653 }
2654 }
2655 }
2656
Harry Cuttsb166c002023-05-09 13:06:05 +00002657 // If this is a touchpad navigation gesture, it needs to only be sent to trusted targets, as we
2658 // only want the system UI to handle these gestures.
2659 const bool isTouchpadNavGesture = isFromSource(entry.source, AINPUT_SOURCE_MOUSE) &&
2660 entry.classification == MotionClassification::MULTI_FINGER_SWIPE;
2661 if (isTouchpadNavGesture) {
2662 filterUntrustedTargets(/* byref */ tempTouchState, /* byref */ targets);
2663 }
2664
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002665 // Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002666 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002667 if (!touchedWindow.hasTouchingPointers(entry.deviceId) &&
2668 !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002669 // Windows with hovering pointers are getting persisted inside TouchState.
2670 // Do not send this event to those windows.
2671 continue;
2672 }
Harry Cuttsb166c002023-05-09 13:06:05 +00002673
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002674 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002675 touchedWindow.getTouchingPointers(entry.deviceId),
2676 touchedWindow.getDownTimeInTarget(entry.deviceId), targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002677 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002678
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002679 // During targeted injection, only allow owned targets to receive events
2680 std::erase_if(targets, [&](const InputTarget& target) {
2681 LOG_ALWAYS_FATAL_IF(target.windowHandle == nullptr);
2682 const auto err = verifyTargetedInjection(target.windowHandle, entry);
2683 if (err) {
2684 LOG(WARNING) << "Dropping injected event from " << target.windowHandle->getName()
2685 << ": " << (*err);
2686 return true;
2687 }
2688 return false;
2689 });
2690
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07002691 if (targets.empty()) {
2692 LOG(INFO) << "Dropping event because no targets were found: " << entry.getDescription();
2693 outInjectionResult = InputEventInjectionResult::FAILED;
2694 return {};
2695 }
2696
2697 // If we only have windows getting ACTION_OUTSIDE, then drop the event, because there is no
2698 // window that is actually receiving the entire gesture.
2699 if (std::all_of(targets.begin(), targets.end(), [](const InputTarget& target) {
2700 return target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE);
2701 })) {
2702 LOG(INFO) << "Dropping event because all windows would just receive ACTION_OUTSIDE: "
2703 << entry.getDescription();
2704 outInjectionResult = InputEventInjectionResult::FAILED;
2705 return {};
2706 }
2707
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002708 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002709 // Drop the outside or hover touch windows since we will not care about them
2710 // in the next iteration.
2711 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002714 if (switchedDevice) {
2715 if (DEBUG_FOCUS) {
2716 ALOGD("Conflicting pointer actions: Switched to a different device.");
2717 }
2718 *outConflictingPointerActions = true;
2719 }
2720
2721 if (isHoverAction) {
2722 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002723 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002724 ALOGD_IF(DEBUG_FOCUS,
2725 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002726 *outConflictingPointerActions = true;
2727 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002728 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2729 // Pointer went up.
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07002730 tempTouchState.removeTouchingPointer(entry.deviceId, entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002731 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002732 // All pointers up or canceled.
2733 tempTouchState.reset();
2734 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2735 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002736 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2737 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002738 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002739 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002740 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2741 // One pointer went up.
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002742 const int32_t pointerIndex = MotionEvent::getActionIndex(action);
2743 const uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
2744 tempTouchState.removeTouchingPointer(entry.deviceId, pointerId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 }
2746
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002747 // Save changes unless the action was scroll in which case the temporary touch
2748 // state was only valid for this one action.
2749 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002750 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002751 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002752 mTouchStatesByDisplay[displayId] = tempTouchState;
2753 } else {
2754 mTouchStatesByDisplay.erase(displayId);
2755 }
2756 }
2757
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002758 if (tempTouchState.windows.empty()) {
2759 mTouchStatesByDisplay.erase(displayId);
2760 }
2761
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002762 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763}
2764
arthurhung6d4bed92021-03-17 11:59:33 +08002765void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002766 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2767 // have an explicit reason to support it.
2768 constexpr bool isStylus = false;
2769
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002770 sp<WindowInfoHandle> dropWindow =
Harry Cutts33476232023-01-30 19:57:29 +00002771 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002772 if (dropWindow) {
2773 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002774 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002775 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002776 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002777 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002778 }
2779 mDragState.reset();
2780}
2781
2782void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002783 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002784 return;
2785 }
2786
arthurhung6d4bed92021-03-17 11:59:33 +08002787 if (!mDragState->isStartDrag) {
2788 mDragState->isStartDrag = true;
2789 mDragState->isStylusButtonDownAtStart =
2790 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2791 }
2792
Arthur Hung54745652022-04-20 07:17:41 +00002793 // Find the pointer index by id.
2794 int32_t pointerIndex = 0;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002795 for (; static_cast<uint32_t>(pointerIndex) < entry.getPointerCount(); pointerIndex++) {
Arthur Hung54745652022-04-20 07:17:41 +00002796 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2797 if (pointerProperties.id == mDragState->pointerId) {
2798 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002799 }
Arthur Hung54745652022-04-20 07:17:41 +00002800 }
arthurhung6d4bed92021-03-17 11:59:33 +08002801
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07002802 if (uint32_t(pointerIndex) == entry.getPointerCount()) {
Arthur Hung54745652022-04-20 07:17:41 +00002803 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Arthur Hung54745652022-04-20 07:17:41 +00002804 }
2805
2806 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2807 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2808 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2809
2810 switch (maskedAction) {
2811 case AMOTION_EVENT_ACTION_MOVE: {
2812 // Handle the special case : stylus button no longer pressed.
2813 bool isStylusButtonDown =
2814 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2815 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2816 finishDragAndDrop(entry.displayId, x, y);
2817 return;
2818 }
2819
2820 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2821 // until we have an explicit reason to support it.
2822 constexpr bool isStylus = false;
2823
Siarhei Vishniakoue1ada272022-11-03 10:47:08 -07002824 sp<WindowInfoHandle> hoverWindowHandle =
2825 findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
2826 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002827 // enqueue drag exit if needed.
2828 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2829 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2830 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002831 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002832 y);
2833 }
2834 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2835 }
2836 // enqueue drag location if needed.
2837 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002838 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002839 }
2840 break;
2841 }
2842
2843 case AMOTION_EVENT_ACTION_POINTER_UP:
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07002844 if (MotionEvent::getActionIndex(entry.action) != pointerIndex) {
Arthur Hung54745652022-04-20 07:17:41 +00002845 break;
2846 }
2847 // The drag pointer is up.
2848 [[fallthrough]];
2849 case AMOTION_EVENT_ACTION_UP:
2850 finishDragAndDrop(entry.displayId, x, y);
2851 break;
2852 case AMOTION_EVENT_ACTION_CANCEL: {
2853 ALOGD("Receiving cancel when drag and drop.");
2854 sendDropWindowCommandLocked(nullptr, 0, 0);
2855 mDragState.reset();
2856 break;
2857 }
arthurhungb89ccb02020-12-30 16:19:01 +08002858 }
2859}
2860
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002861std::optional<InputTarget> InputDispatcher::createInputTargetLocked(
2862 const sp<android::gui::WindowInfoHandle>& windowHandle,
2863 ftl::Flags<InputTarget::Flags> targetFlags,
2864 std::optional<nsecs_t> firstDownTimeInTarget) const {
2865 std::shared_ptr<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
2866 if (inputChannel == nullptr) {
2867 ALOGW("Not creating InputTarget for %s, no input channel", windowHandle->getName().c_str());
2868 return {};
2869 }
2870 InputTarget inputTarget;
2871 inputTarget.inputChannel = inputChannel;
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00002872 inputTarget.windowHandle = windowHandle;
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002873 inputTarget.flags = targetFlags;
2874 inputTarget.globalScaleFactor = windowHandle->getInfo()->globalScaleFactor;
2875 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
2876 const auto& displayInfoIt = mDisplayInfos.find(windowHandle->getInfo()->displayId);
2877 if (displayInfoIt != mDisplayInfos.end()) {
2878 inputTarget.displayTransform = displayInfoIt->second.transform;
2879 } else {
Siarhei Vishniakou580fb3a2023-05-05 15:02:20 -07002880 // DisplayInfo not found for this window on display windowHandle->getInfo()->displayId.
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002881 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
2882 }
2883 return inputTarget;
2884}
2885
chaviw98318de2021-05-19 16:45:23 -05002886void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002887 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002888 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002889 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002890 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002891 std::vector<InputTarget>::iterator it =
2892 std::find_if(inputTargets.begin(), inputTargets.end(),
2893 [&windowHandle](const InputTarget& inputTarget) {
2894 return inputTarget.inputChannel->getConnectionToken() ==
2895 windowHandle->getToken();
2896 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002897
chaviw98318de2021-05-19 16:45:23 -05002898 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002899
2900 if (it == inputTargets.end()) {
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002901 std::optional<InputTarget> target =
2902 createInputTargetLocked(windowHandle, targetFlags, firstDownTimeInTarget);
2903 if (!target) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002904 return;
2905 }
Siarhei Vishniakou6c377b32023-05-15 17:03:39 -07002906 inputTargets.push_back(*target);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002907 it = inputTargets.end() - 1;
2908 }
2909
2910 ALOG_ASSERT(it->flags == targetFlags);
2911 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2912
chaviw1ff3d1e2020-07-01 15:53:47 -07002913 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914}
2915
Michael Wright3dd60e22019-03-27 22:06:44 +00002916void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002917 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002918 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2919 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002920
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002921 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2922 InputTarget target;
2923 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002924 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002925 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2926 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002927 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2928 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002929 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002930 target.setDefaultPointerTransform(target.displayTransform);
2931 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932 }
2933}
2934
Robert Carrc9bf1d32020-04-13 17:21:08 -07002935/**
2936 * Indicate whether one window handle should be considered as obscuring
2937 * another window handle. We only check a few preconditions. Actually
2938 * checking the bounds is left to the caller.
2939 */
chaviw98318de2021-05-19 16:45:23 -05002940static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2941 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002942 // Compare by token so cloned layers aren't counted
2943 if (haveSameToken(windowHandle, otherHandle)) {
2944 return false;
2945 }
2946 auto info = windowHandle->getInfo();
2947 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002948 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002949 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002950 } else if (otherInfo->alpha == 0 &&
2951 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002952 // Those act as if they were invisible, so we don't need to flag them.
2953 // We do want to potentially flag touchable windows even if they have 0
2954 // opacity, since they can consume touches and alter the effects of the
2955 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002956 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002957 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2958 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002959 } else if (info->ownerUid == otherInfo->ownerUid) {
2960 // If ownerUid is the same we don't generate occlusion events as there
2961 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002962 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002963 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002964 return false;
2965 } else if (otherInfo->displayId != info->displayId) {
2966 return false;
2967 }
2968 return true;
2969}
2970
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002971/**
2972 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2973 * untrusted, one should check:
2974 *
2975 * 1. If result.hasBlockingOcclusion is true.
2976 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2977 * BLOCK_UNTRUSTED.
2978 *
2979 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2980 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2981 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2982 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2983 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2984 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2985 *
2986 * If neither of those is true, then it means the touch can be allowed.
2987 */
2988InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002989 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2990 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002991 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002992 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002993 TouchOcclusionInfo info;
2994 info.hasBlockingOcclusion = false;
2995 info.obscuringOpacity = 0;
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00002996 info.obscuringUid = gui::Uid::INVALID;
2997 std::map<gui::Uid, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002998 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002999 if (windowHandle == otherHandle) {
3000 break; // All future windows are below us. Exit early.
3001 }
chaviw98318de2021-05-19 16:45:23 -05003002 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00003003 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
3004 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003005 if (DEBUG_TOUCH_OCCLUSION) {
3006 info.debugInfo.push_back(
Harry Cutts101ee9b2023-07-06 18:04:14 +00003007 dumpWindowForTouchOcclusion(otherInfo, /*isTouchedWindow=*/false));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003008 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003009 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
3010 // we perform the checks below to see if the touch can be propagated or not based on the
3011 // window's touch occlusion mode
3012 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
3013 info.hasBlockingOcclusion = true;
3014 info.obscuringUid = otherInfo->ownerUid;
3015 info.obscuringPackage = otherInfo->packageName;
3016 break;
3017 }
3018 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003019 const auto uid = otherInfo->ownerUid;
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003020 float opacity =
3021 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
3022 // Given windows A and B:
3023 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
3024 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
3025 opacityByUid[uid] = opacity;
3026 if (opacity > info.obscuringOpacity) {
3027 info.obscuringOpacity = opacity;
3028 info.obscuringUid = uid;
3029 info.obscuringPackage = otherInfo->packageName;
3030 }
3031 }
3032 }
3033 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003034 if (DEBUG_TOUCH_OCCLUSION) {
Harry Cutts101ee9b2023-07-06 18:04:14 +00003035 info.debugInfo.push_back(dumpWindowForTouchOcclusion(windowInfo, /*isTouchedWindow=*/true));
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003036 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003037 return info;
3038}
3039
chaviw98318de2021-05-19 16:45:23 -05003040std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003041 bool isTouchedWindow) const {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003042 return StringPrintf(INDENT2 "* %spackage=%s/%s, id=%" PRId32 ", mode=%s, alpha=%.2f, "
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003043 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
3044 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
3045 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003046 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003047 info->ownerUid.toString().c_str(), info->id,
Chavi Weingarten7f019192023-08-08 20:39:01 +00003048 toString(info->touchOcclusionMode).c_str(), info->alpha, info->frame.left,
3049 info->frame.top, info->frame.right, info->frame.bottom,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003050 dumpRegion(info->touchableRegion).c_str(), info->name.c_str(),
3051 info->inputConfig.string().c_str(), toString(info->token != nullptr),
3052 info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003053 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00003054}
3055
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003056bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
3057 if (occlusionInfo.hasBlockingOcclusion) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003058 ALOGW("Untrusted touch due to occlusion by %s/%s", occlusionInfo.obscuringPackage.c_str(),
3059 occlusionInfo.obscuringUid.toString().c_str());
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003060 return false;
3061 }
3062 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003063 ALOGW("Untrusted touch due to occlusion by %s/%s (obscuring opacity = "
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003064 "%.2f, maximum allowed = %.2f)",
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003065 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid.toString().c_str(),
Bernardo Rufinoea97d182020-08-19 14:43:14 +01003066 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
3067 return false;
3068 }
3069 return true;
3070}
3071
chaviw98318de2021-05-19 16:45:23 -05003072bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003073 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003075 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3076 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003077 if (windowHandle == otherHandle) {
3078 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079 }
chaviw98318de2021-05-19 16:45:23 -05003080 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003081 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003082 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083 return true;
3084 }
3085 }
3086 return false;
3087}
3088
chaviw98318de2021-05-19 16:45:23 -05003089bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003090 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05003091 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
3092 const WindowInfo* windowInfo = windowHandle->getInfo();
3093 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07003094 if (windowHandle == otherHandle) {
3095 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003096 }
chaviw98318de2021-05-19 16:45:23 -05003097 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07003098 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08003099 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07003100 return true;
3101 }
3102 }
3103 return false;
3104}
3105
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003106std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05003107 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003108 if (applicationHandle != nullptr) {
3109 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003110 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111 } else {
3112 return applicationHandle->getName();
3113 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003114 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07003115 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003117 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118 }
3119}
3120
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003121void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00003122 if (!isUserActivityEvent(eventEntry)) {
3123 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003124 return;
3125 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003126 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05003127 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Josep del Riob3981622023-04-18 15:49:45 +00003128 const WindowInfo* windowDisablingUserActivityInfo = nullptr;
Tiger Huang721e26f2018-07-24 22:26:19 +08003129 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003130 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08003131 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Josep del Riob3981622023-04-18 15:49:45 +00003132 windowDisablingUserActivityInfo = info;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003133 }
3134 }
3135
3136 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003137 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003138 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003139 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3140 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003141 return;
3142 }
Josep del Riob3981622023-04-18 15:49:45 +00003143 if (windowDisablingUserActivityInfo != nullptr) {
3144 if (DEBUG_DISPATCH_CYCLE) {
3145 ALOGD("Not poking user activity: disabled by window '%s'.",
3146 windowDisablingUserActivityInfo->name.c_str());
3147 }
3148 return;
3149 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003150 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003151 eventType = USER_ACTIVITY_EVENT_TOUCH;
3152 }
3153 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003155 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003156 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3157 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003158 return;
3159 }
Josep del Riob3981622023-04-18 15:49:45 +00003160 // If the key code is unknown, we don't consider it user activity
3161 if (keyEntry.keyCode == AKEYCODE_UNKNOWN) {
3162 return;
3163 }
3164 // Don't inhibit events that were intercepted or are not passed to
3165 // the apps, like system shortcuts
3166 if (windowDisablingUserActivityInfo != nullptr &&
3167 keyEntry.interceptKeyResult != KeyEntry::InterceptKeyResult::SKIP &&
3168 keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER) {
3169 if (DEBUG_DISPATCH_CYCLE) {
3170 ALOGD("Not poking user activity: disabled by window '%s'.",
3171 windowDisablingUserActivityInfo->name.c_str());
3172 }
3173 return;
3174 }
3175
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003176 eventType = USER_ACTIVITY_EVENT_BUTTON;
3177 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003179 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003180 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003181 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003182 break;
3183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 }
3185
Prabir Pradhancef936d2021-07-21 16:17:52 +00003186 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3187 REQUIRES(mLock) {
3188 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003189 mPolicy.pokeUserActivity(eventTime, eventType, displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003190 };
3191 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192}
3193
3194void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003195 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003196 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003197 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003198 ATRACE_NAME_IF(ATRACE_ENABLED(),
3199 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3200 connection->getInputChannelName().c_str(), eventEntry->id));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003201 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003202 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003203 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003204 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003205 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003206 inputTarget.getPointerInfoString().c_str());
3207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003208
3209 // Skip this event if the connection status is not normal.
3210 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003211 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003212 if (DEBUG_DISPATCH_CYCLE) {
3213 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003214 connection->getInputChannelName().c_str(),
3215 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003216 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 return;
3218 }
3219
3220 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003221 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003222 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003223 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003224 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003226 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003227 if (inputTarget.pointerIds.count() != originalMotionEntry.getPointerCount()) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003228 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3229 logDispatchStateLocked();
3230 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3231 "target on connection "
3232 << connection->getInputChannelName() << " for "
3233 << originalMotionEntry.getDescription();
3234 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003235 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003236 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3237 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238 if (!splitMotionEntry) {
3239 return; // split event was dropped
3240 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003241 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3242 std::string reason = std::string("reason=pointer cancel on split window");
3243 android_log_event_list(LOGTAG_INPUT_CANCEL)
3244 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3245 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003246 if (DEBUG_FOCUS) {
3247 ALOGD("channel '%s' ~ Split motion event.",
3248 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003249 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003250 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003251 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3252 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 return;
3254 }
3255 }
3256
3257 // Not splitting. Enqueue dispatch entries for the event as is.
3258 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3259}
3260
3261void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003262 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003263 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003264 const InputTarget& inputTarget) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003265 ATRACE_NAME_IF(ATRACE_ENABLED(),
3266 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
3267 connection->getInputChannelName().c_str(), eventEntry->id));
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003268 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3269 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003270
hongzuo liu95785e22022-09-06 02:51:35 +00003271 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272
3273 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003274 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003275 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003276 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003277 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003278 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003279 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003280 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003281 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003282 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003283 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003284 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003285 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286
3287 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003288 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289 startDispatchCycleLocked(currentTime, connection);
3290 }
3291}
3292
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003293void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003294 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003295 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003296 ftl::Flags<InputTarget::Flags> dispatchMode) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003297 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3298 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299 return;
3300 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003301
3302 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3303 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304
3305 // This is a new event.
3306 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003307 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003308 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003310 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3311 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003312 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003314 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003315 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003316 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003317 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3318 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003319 LOG(WARNING) << "channel " << connection->getInputChannelName()
3320 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003321 return; // skip the inconsistent event
3322 }
3323 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003326 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003327 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003328 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3329 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3330 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3331 static_cast<int32_t>(IdGenerator::Source::OTHER);
3332 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003333 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003334 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003335 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003336 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003337 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003338 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003339 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003340 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003341 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003342 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3343 } else {
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003344 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003345 }
3346 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003347 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3348 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003349 if (DEBUG_DISPATCH_CYCLE) {
3350 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3351 "enter event",
3352 connection->getInputChannelName().c_str());
3353 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003354 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3355 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003356 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003359 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3360 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3361 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003362 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003363 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3364 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003365 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003366 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3367 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003369 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3370 dispatchEntry->resolvedFlags)) {
Siarhei Vishniakouc94dafe2023-05-26 10:24:19 -07003371 LOG(WARNING) << "channel " << connection->getInputChannelName()
3372 << "~ dropping inconsistent event: " << *dispatchEntry;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003373 return; // skip the inconsistent event
3374 }
3375
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003376 dispatchEntry->resolvedEventId =
3377 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3378 ? mIdGenerator.nextId()
3379 : motionEntry.id;
3380 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3381 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3382 ") to MotionEvent(id=0x%" PRIx32 ").",
3383 motionEntry.id, dispatchEntry->resolvedEventId);
3384 ATRACE_NAME(message.c_str());
3385 }
3386
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003387 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3388 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3389 // Skip reporting pointer down outside focus to the policy.
3390 break;
3391 }
3392
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003393 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003394 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003395
3396 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003398 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003399 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003400 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3401 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003402 break;
3403 }
Chris Yef59a2f42020-10-16 12:55:26 -07003404 case EventEntry::Type::SENSOR: {
3405 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3406 break;
3407 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003408 case EventEntry::Type::CONFIGURATION_CHANGED:
3409 case EventEntry::Type::DEVICE_RESET: {
3410 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003411 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003412 break;
3413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414 }
3415
3416 // Remember that we are waiting for this dispatch to complete.
3417 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003418 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 }
3420
3421 // Enqueue the dispatch entry.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003422 connection->outboundQueue.emplace_back(std::move(dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003423 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003424}
3425
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003426/**
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003427 * This function is for debugging and metrics collection. It has two roles.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003428 *
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003429 * The first role is to log input interaction with windows, which helps determine what the user was
3430 * interacting with. For example, if user is touching launcher, we will see an input_interaction log
3431 * that user started interacting with launcher window, as well as any other window that received
3432 * that gesture, such as the wallpaper or other spy windows. A new input_interaction is only logged
3433 * when the set of tokens that received the event changes. It is not logged again as long as the
3434 * user is interacting with the same windows.
3435 *
3436 * The second role is to track input device activity for metrics collection. For each input event,
3437 * we report the set of UIDs that the input device interacted with to the policy. Unlike for the
3438 * input_interaction logs, the device interaction is reported even when the set of interaction
3439 * tokens do not change.
3440 *
3441 * For these purposes, we do not count ACTION_OUTSIDE, ACTION_UP and ACTION_CANCEL actions as
3442 * interaction. This includes up and cancel events for both keys and motions.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003443 */
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003444void InputDispatcher::processInteractionsLocked(const EventEntry& entry,
3445 const std::vector<InputTarget>& targets) {
3446 int32_t deviceId;
3447 nsecs_t eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003448 // Skip ACTION_UP events, and all events other than keys and motions
3449 if (entry.type == EventEntry::Type::KEY) {
3450 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3451 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3452 return;
3453 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003454 deviceId = keyEntry.deviceId;
3455 eventTime = keyEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003456 } else if (entry.type == EventEntry::Type::MOTION) {
3457 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3458 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003459 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
3460 MotionEvent::getActionMasked(motionEntry.action) == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003461 return;
3462 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003463 deviceId = motionEntry.deviceId;
3464 eventTime = motionEntry.eventTime;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003465 } else {
3466 return; // Not a key or a motion
3467 }
3468
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00003469 std::set<gui::Uid> interactionUids;
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003470 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003471 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003472 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003473 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003474 continue; // Skip windows that receive ACTION_OUTSIDE
3475 }
3476
3477 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003478 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003479 if (connection == nullptr) {
3480 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003481 }
3482 newConnectionTokens.insert(std::move(token));
3483 newConnections.emplace_back(connection);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003484 if (target.windowHandle) {
3485 interactionUids.emplace(target.windowHandle->getInfo()->ownerUid);
3486 }
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003487 }
Prabir Pradhan8ede1d12023-05-08 19:37:44 +00003488
3489 auto command = [this, deviceId, eventTime, uids = std::move(interactionUids)]()
3490 REQUIRES(mLock) {
3491 scoped_unlock unlock(mLock);
3492 mPolicy.notifyDeviceInteraction(deviceId, eventTime, uids);
3493 };
3494 postCommandLocked(std::move(command));
3495
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003496 if (newConnectionTokens == mInteractionConnectionTokens) {
3497 return; // no change
3498 }
3499 mInteractionConnectionTokens = newConnectionTokens;
3500
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003501 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003502 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003503 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003504 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003505 std::string message = "Interaction with: " + targetList;
3506 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003507 message += "<none>";
3508 }
3509 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3510}
3511
chaviwfd6d3512019-03-25 13:23:49 -07003512void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003513 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003514 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003515 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3516 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003517 return;
3518 }
3519
Vishnu Nairc519ff72021-01-21 08:23:08 -08003520 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003521 if (focusedToken == token) {
3522 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003523 return;
3524 }
3525
Prabir Pradhancef936d2021-07-21 16:17:52 +00003526 auto command = [this, token]() REQUIRES(mLock) {
3527 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003528 mPolicy.onPointerDownOutsideFocus(token);
Prabir Pradhancef936d2021-07-21 16:17:52 +00003529 };
3530 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531}
3532
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003533status_t InputDispatcher::publishMotionEvent(Connection& connection,
3534 DispatchEntry& dispatchEntry) const {
3535 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3536 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3537
3538 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003539 const PointerCoords* usingCoords = motionEntry.pointerCoords.data();
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003540
3541 // Set the X and Y offset and X and Y scale depending on the input source.
3542 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003543 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003544 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3545 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003546 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003547 scaledCoords[i] = motionEntry.pointerCoords[i];
3548 // Don't apply window scale here since we don't want scale to affect raw
3549 // coordinates. The scale will be sent back to the client and applied
3550 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003551 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003552 }
3553 usingCoords = scaledCoords;
3554 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003555 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003556 // We don't want the dispatch target to know the coordinates
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003557 for (uint32_t i = 0; i < motionEntry.getPointerCount(); i++) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003558 scaledCoords[i].clear();
3559 }
3560 usingCoords = scaledCoords;
3561 }
3562
3563 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3564
3565 // Publish the motion event.
3566 return connection.inputPublisher
3567 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3568 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3569 std::move(hmac), dispatchEntry.resolvedAction,
3570 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3571 motionEntry.edgeFlags, motionEntry.metaState,
3572 motionEntry.buttonState, motionEntry.classification,
3573 dispatchEntry.transform, motionEntry.xPrecision,
3574 motionEntry.yPrecision, motionEntry.xCursorPosition,
3575 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3576 motionEntry.downTime, motionEntry.eventTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003577 motionEntry.getPointerCount(), motionEntry.pointerProperties.data(),
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003578 usingCoords);
3579}
3580
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003582 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00003583 ATRACE_NAME_IF(ATRACE_ENABLED(),
3584 StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
3585 connection->getInputChannelName().c_str()));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003586 if (DEBUG_DISPATCH_CYCLE) {
3587 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003590 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003591 std::unique_ptr<DispatchEntry>& dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003593 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003594 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595
3596 // Publish the event.
3597 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003598 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3599 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003600 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003601 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3602 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003603 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003604 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3605 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003606 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003608 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003609 status = connection->inputPublisher
3610 .publishKeyEvent(dispatchEntry->seq,
3611 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3612 keyEntry.source, keyEntry.displayId,
3613 std::move(hmac), dispatchEntry->resolvedAction,
3614 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3615 keyEntry.scanCode, keyEntry.metaState,
3616 keyEntry.repeatCount, keyEntry.downTime,
3617 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003618 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 }
3620
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003621 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003622 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003623 LOG(INFO) << "Publishing " << *dispatchEntry << " to "
3624 << connection->getInputChannelName();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003625 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003626 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003627 break;
3628 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003629
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003630 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003631 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003632 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003633 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003634 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003635 break;
3636 }
3637
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003638 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3639 const TouchModeEntry& touchModeEntry =
3640 static_cast<const TouchModeEntry&>(eventEntry);
3641 status = connection->inputPublisher
3642 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3643 touchModeEntry.inTouchMode);
3644
3645 break;
3646 }
3647
Prabir Pradhan99987712020-11-10 18:43:05 -08003648 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3649 const auto& captureEntry =
3650 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3651 status = connection->inputPublisher
3652 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003653 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003654 break;
3655 }
3656
arthurhungb89ccb02020-12-30 16:19:01 +08003657 case EventEntry::Type::DRAG: {
3658 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3659 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3660 dragEntry.id, dragEntry.x,
3661 dragEntry.y,
3662 dragEntry.isExiting);
3663 break;
3664 }
3665
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003666 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003667 case EventEntry::Type::DEVICE_RESET:
3668 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003669 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003670 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003671 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003672 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673 }
3674
3675 // Check the result.
3676 if (status) {
3677 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003678 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003680 "This is unexpected because the wait queue is empty, so the pipe "
3681 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003682 "event to it, status=%s(%d)",
3683 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3684 status);
Harry Cutts33476232023-01-30 19:57:29 +00003685 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686 } else {
3687 // Pipe is full and we are waiting for the app to finish process some events
3688 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003689 if (DEBUG_DISPATCH_CYCLE) {
3690 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3691 "waiting for the application to catch up",
3692 connection->getInputChannelName().c_str());
3693 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 }
3695 } else {
3696 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003697 "status=%s(%d)",
3698 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3699 status);
Harry Cutts33476232023-01-30 19:57:29 +00003700 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 }
3702 return;
3703 }
3704
3705 // Re-enqueue the event on the wait queue.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003706 const nsecs_t timeoutTime = dispatchEntry->timeoutTime;
3707 connection->waitQueue.emplace_back(std::move(dispatchEntry));
3708 connection->outboundQueue.erase(connection->outboundQueue.begin());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003709 traceOutboundQueueLength(*connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003710 if (connection->responsive) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003711 mAnrTracker.insert(timeoutTime, connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003712 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003713 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 }
3715}
3716
chaviw09c8d2d2020-08-24 15:48:26 -07003717std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3718 size_t size;
3719 switch (event.type) {
3720 case VerifiedInputEvent::Type::KEY: {
3721 size = sizeof(VerifiedKeyEvent);
3722 break;
3723 }
3724 case VerifiedInputEvent::Type::MOTION: {
3725 size = sizeof(VerifiedMotionEvent);
3726 break;
3727 }
3728 }
3729 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3730 return mHmacKeyManager.sign(start, size);
3731}
3732
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003733const std::array<uint8_t, 32> InputDispatcher::getSignature(
3734 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07003735 const int32_t actionMasked = MotionEvent::getActionMasked(dispatchEntry.resolvedAction);
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003736 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003737 // Only sign events up and down events as the purely move events
3738 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003739 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003740 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003741
3742 VerifiedMotionEvent verifiedEvent =
3743 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3744 verifiedEvent.actionMasked = actionMasked;
3745 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3746 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003747}
3748
3749const std::array<uint8_t, 32> InputDispatcher::getSignature(
3750 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3751 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3752 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3753 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003754 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003755}
3756
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003758 const std::shared_ptr<Connection>& connection,
3759 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003760 if (DEBUG_DISPATCH_CYCLE) {
3761 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3762 connection->getInputChannelName().c_str(), seq, toString(handled));
3763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003765 if (connection->status == Connection::Status::BROKEN ||
3766 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 return;
3768 }
3769
3770 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003771 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3772 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3773 };
3774 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775}
3776
3777void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003778 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003779 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003780 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07003781 LOG(INFO) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3782 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784
3785 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003786 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003787 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003788 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003789 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790
3791 // The connection appears to be unrecoverably broken.
3792 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003793 if (connection->status == Connection::Status::NORMAL) {
3794 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795
3796 if (notify) {
3797 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003798 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3799 connection->getInputChannelName().c_str());
3800
3801 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003802 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00003803 mPolicy.notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Prabir Pradhancef936d2021-07-21 16:17:52 +00003804 };
3805 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 }
3807 }
3808}
3809
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003810void InputDispatcher::drainDispatchQueue(std::deque<std::unique_ptr<DispatchEntry>>& queue) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003811 while (!queue.empty()) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003812 releaseDispatchEntry(std::move(queue.front()));
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003813 queue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 }
3815}
3816
Prabir Pradhan8c90d782023-09-15 21:16:44 +00003817void InputDispatcher::releaseDispatchEntry(std::unique_ptr<DispatchEntry> dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003819 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821}
3822
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003823int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3824 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003825 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003826 if (connection == nullptr) {
3827 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3828 connectionToken.get(), events);
3829 return 0; // remove the callback
3830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003832 bool notify;
3833 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3834 if (!(events & ALOOPER_EVENT_INPUT)) {
3835 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3836 "events=0x%x",
3837 connection->getInputChannelName().c_str(), events);
3838 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003839 }
3840
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003841 nsecs_t currentTime = now();
3842 bool gotOne = false;
3843 status_t status = OK;
3844 for (;;) {
3845 Result<InputPublisher::ConsumerResponse> result =
3846 connection->inputPublisher.receiveConsumerResponse();
3847 if (!result.ok()) {
3848 status = result.error().code();
3849 break;
3850 }
3851
3852 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3853 const InputPublisher::Finished& finish =
3854 std::get<InputPublisher::Finished>(*result);
3855 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3856 finish.consumeTime);
3857 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003858 if (shouldReportMetricsForConnection(*connection)) {
3859 const InputPublisher::Timeline& timeline =
3860 std::get<InputPublisher::Timeline>(*result);
3861 mLatencyTracker
3862 .trackGraphicsLatency(timeline.inputEventId,
3863 connection->inputChannel->getConnectionToken(),
3864 std::move(timeline.graphicsTimeline));
3865 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003866 }
3867 gotOne = true;
3868 }
3869 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003870 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003871 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 return 1;
3873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 }
3875
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003876 notify = status != DEAD_OBJECT || !connection->monitor;
3877 if (notify) {
3878 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3879 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3880 status);
3881 }
3882 } else {
3883 // Monitor channels are never explicitly unregistered.
3884 // We do it automatically when the remote endpoint is closed so don't warn about them.
3885 const bool stillHaveWindowHandle =
3886 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3887 notify = !connection->monitor && stillHaveWindowHandle;
3888 if (notify) {
3889 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3890 connection->getInputChannelName().c_str(), events);
3891 }
3892 }
3893
3894 // Remove the channel.
3895 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3896 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897}
3898
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003899void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003901 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003902 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 }
3904}
3905
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003906void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003907 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003908 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003909 for (const Monitor& monitor : monitors) {
3910 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003911 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003912 }
3913}
3914
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003916 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003917 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003918 if (connection == nullptr) {
3919 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003921
3922 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923}
3924
3925void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003926 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Linnan Li5af92f92023-07-14 14:36:22 +08003927 if ((options.mode == CancelationOptions::Mode::CANCEL_POINTER_EVENTS ||
3928 options.mode == CancelationOptions::Mode::CANCEL_ALL_EVENTS) &&
3929 mDragState && mDragState->dragWindow->getToken() == connection->inputChannel->getToken()) {
3930 LOG(INFO) << __func__
3931 << ": Canceling drag and drop because the pointers for the drag window are being "
3932 "canceled.";
3933 sendDropWindowCommandLocked(nullptr, /*x=*/0, /*y=*/0);
3934 mDragState.reset();
3935 }
3936
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003937 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938 return;
3939 }
3940
3941 nsecs_t currentTime = now();
3942
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003943 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003944 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003946 if (cancelationEvents.empty()) {
3947 return;
3948 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003949 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3950 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003951 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003952 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003953 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003954 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003955
Arthur Hungb3307ee2021-10-14 10:57:37 +00003956 std::string reason = std::string("reason=").append(options.reason);
3957 android_log_event_list(LOGTAG_INPUT_CANCEL)
3958 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3959
hongzuo liu95785e22022-09-06 02:51:35 +00003960 const bool wasEmpty = connection->outboundQueue.empty();
Prabir Pradhan16463382023-10-12 23:03:19 +00003961 // The target to use if we don't find a window associated with the channel.
3962 const InputTarget fallbackTarget{.inputChannel = connection->inputChannel,
3963 .flags = InputTarget::Flags::DISPATCH_AS_IS};
3964 const auto& token = connection->inputChannel->getConnectionToken();
hongzuo liu95785e22022-09-06 02:51:35 +00003965
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003966 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003967 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003968 std::vector<InputTarget> targets{};
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003969
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003970 switch (cancelationEventEntry->type) {
3971 case EventEntry::Type::KEY: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003972 const auto& keyEntry = static_cast<const KeyEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00003973 const std::optional<int32_t> targetDisplay = keyEntry.displayId != ADISPLAY_ID_NONE
3974 ? std::make_optional(keyEntry.displayId)
3975 : std::nullopt;
3976 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
3977 addWindowTargetLocked(window, InputTarget::Flags::DISPATCH_AS_IS,
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003978 /*pointerIds=*/{}, keyEntry.downTime, targets);
3979 } else {
3980 targets.emplace_back(fallbackTarget);
3981 }
3982 logOutboundKeyDetails("cancel - ", keyEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003983 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003985 case EventEntry::Type::MOTION: {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003986 const auto& motionEntry = static_cast<const MotionEntry&>(*cancelationEventEntry);
Prabir Pradhan16463382023-10-12 23:03:19 +00003987 const std::optional<int32_t> targetDisplay =
3988 motionEntry.displayId != ADISPLAY_ID_NONE
3989 ? std::make_optional(motionEntry.displayId)
3990 : std::nullopt;
3991 if (const auto& window = getWindowHandleLocked(token, targetDisplay); window) {
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003992 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07003993 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003994 pointerIndex++) {
3995 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
3996 }
Prabir Pradhan16463382023-10-12 23:03:19 +00003997 addWindowTargetLocked(window, InputTarget::Flags::DISPATCH_AS_IS, pointerIds,
3998 motionEntry.downTime, targets);
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00003999 } else {
4000 targets.emplace_back(fallbackTarget);
4001 const auto it = mDisplayInfos.find(motionEntry.displayId);
4002 if (it != mDisplayInfos.end()) {
4003 targets.back().displayTransform = it->second.transform;
4004 targets.back().setDefaultPointerTransform(it->second.transform);
4005 }
4006 }
4007 logOutboundMotionDetails("cancel - ", motionEntry);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004008 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 }
Prabir Pradhan99987712020-11-10 18:43:05 -08004010 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004011 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004012 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
4013 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08004014 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08004015 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004016 break;
4017 }
4018 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07004019 case EventEntry::Type::DEVICE_RESET:
4020 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004021 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004022 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004023 break;
4024 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 }
4026
Prabir Pradhan112b1ad2023-09-21 09:53:53 +00004027 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4028 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004029 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08004031
hongzuo liu95785e22022-09-06 02:51:35 +00004032 // If the outbound queue was previously empty, start the dispatch cycle going.
4033 if (wasEmpty && !connection->outboundQueue.empty()) {
4034 startDispatchCycleLocked(currentTime, connection);
4035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036}
4037
Svet Ganov5d3bc372020-01-26 23:11:07 -08004038void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004039 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00004040 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08004041 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004042 return;
4043 }
4044
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004045 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004046 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004047
4048 if (downEvents.empty()) {
4049 return;
4050 }
4051
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004052 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004053 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
4054 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004055 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004056
chaviw98318de2021-05-19 16:45:23 -05004057 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08004058 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004059
hongzuo liu95785e22022-09-06 02:51:35 +00004060 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004061 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004062 std::vector<InputTarget> targets{};
Svet Ganov5d3bc372020-01-26 23:11:07 -08004063 switch (downEventEntry->type) {
4064 case EventEntry::Type::MOTION: {
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004065 const auto& motionEntry = static_cast<const MotionEntry&>(*downEventEntry);
4066 if (windowHandle != nullptr) {
4067 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004068 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.getPointerCount();
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004069 pointerIndex++) {
4070 pointerIds.set(motionEntry.pointerProperties[pointerIndex].id);
4071 }
4072 addWindowTargetLocked(windowHandle, targetFlags, pointerIds,
4073 motionEntry.downTime, targets);
4074 } else {
4075 targets.emplace_back(InputTarget{.inputChannel = connection->inputChannel,
4076 .flags = targetFlags});
4077 const auto it = mDisplayInfos.find(motionEntry.displayId);
4078 if (it != mDisplayInfos.end()) {
4079 targets.back().displayTransform = it->second.transform;
4080 targets.back().setDefaultPointerTransform(it->second.transform);
4081 }
4082 }
4083 logOutboundMotionDetails("down - ", motionEntry);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004084 break;
4085 }
4086
4087 case EventEntry::Type::KEY:
4088 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07004089 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08004090 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08004091 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07004092 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08004093 case EventEntry::Type::SENSOR:
4094 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004095 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08004096 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08004097 break;
4098 }
4099 }
4100
Prabir Pradhan1c29a092023-09-21 10:29:29 +00004101 if (targets.size() != 1) LOG(FATAL) << __func__ << ": InputTarget not created";
4102 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), targets[0],
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004103 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004104 }
4105
hongzuo liu95785e22022-09-06 02:51:35 +00004106 // If the outbound queue was previously empty, start the dispatch cycle going.
4107 if (wasEmpty && !connection->outboundQueue.empty()) {
4108 startDispatchCycleLocked(downTime, connection);
4109 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08004110}
4111
Arthur Hungc539dbb2022-12-08 07:45:36 +00004112void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
4113 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
4114 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004115 std::shared_ptr<Connection> wallpaperConnection =
4116 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00004117 if (wallpaperConnection != nullptr) {
4118 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
4119 }
4120 }
4121}
4122
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004123std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004124 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
4125 nsecs_t splitDownTime) {
4126 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127
4128 uint32_t splitPointerIndexMap[MAX_POINTERS];
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004129 std::vector<PointerProperties> splitPointerProperties;
4130 std::vector<PointerCoords> splitPointerCoords;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004132 uint32_t originalPointerCount = originalMotionEntry.getPointerCount();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 uint32_t splitPointerCount = 0;
4134
4135 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004136 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004138 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004140 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004142 splitPointerProperties.push_back(pointerProperties);
4143 splitPointerCoords.push_back(originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 splitPointerCount += 1;
4145 }
4146 }
4147
4148 if (splitPointerCount != pointerIds.count()) {
4149 // This is bad. We are missing some of the pointers that we expected to deliver.
4150 // Most likely this indicates that we received an ACTION_MOVE events that has
4151 // different pointer ids than we expected based on the previous ACTION_DOWN
4152 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
4153 // in this way.
4154 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004155 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08004156 "a broken sequence of pointer ids from the input device: %s",
4157 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07004158 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 }
4160
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004161 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004163 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
4164 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Siarhei Vishniakou5b9766d2023-07-18 14:06:29 -07004165 int32_t originalPointerIndex = MotionEvent::getActionIndex(action);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004167 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08004169 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 if (pointerIds.count() == 1) {
4171 // The first/last pointer went down/up.
4172 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004173 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08004174 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
4175 ? AMOTION_EVENT_ACTION_CANCEL
4176 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 } else {
4178 // A secondary pointer went down/up.
4179 uint32_t splitPointerIndex = 0;
4180 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
4181 splitPointerIndex += 1;
4182 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004183 action = maskedAction |
4184 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 }
4186 } else {
4187 // An unrelated pointer changed.
4188 action = AMOTION_EVENT_ACTION_MOVE;
4189 }
4190 }
4191
Siarhei Vishniakou59e302b2023-06-05 08:04:53 -07004192 if (action == AMOTION_EVENT_ACTION_DOWN && splitDownTime != originalMotionEntry.eventTime) {
4193 logDispatchStateLocked();
4194 LOG_ALWAYS_FATAL("Split motion event has mismatching downTime and eventTime for "
4195 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
4196 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004197 }
4198
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004199 int32_t newId = mIdGenerator.nextId();
Prabir Pradhan2dac8b82023-09-06 01:11:51 +00004200 ATRACE_NAME_IF(ATRACE_ENABLED(),
4201 StringPrintf("Split MotionEvent(id=0x%" PRIx32 ") to MotionEvent(id=0x%" PRIx32
4202 ").",
4203 originalMotionEntry.id, newId));
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004204 std::unique_ptr<MotionEntry> splitMotionEntry =
4205 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4206 originalMotionEntry.deviceId, originalMotionEntry.source,
4207 originalMotionEntry.displayId,
4208 originalMotionEntry.policyFlags, action,
4209 originalMotionEntry.actionButton,
4210 originalMotionEntry.flags, originalMotionEntry.metaState,
4211 originalMotionEntry.buttonState,
4212 originalMotionEntry.classification,
4213 originalMotionEntry.edgeFlags,
4214 originalMotionEntry.xPrecision,
4215 originalMotionEntry.yPrecision,
4216 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004217 originalMotionEntry.yCursorPosition, splitDownTime,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004218 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004220 if (originalMotionEntry.injectionState) {
4221 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 splitMotionEntry->injectionState->refCount += 1;
4223 }
4224
4225 return splitMotionEntry;
4226}
4227
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004228void InputDispatcher::notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs& args) {
4229 std::scoped_lock _l(mLock);
4230 mLatencyTracker.setInputDevices(args.inputDeviceInfos);
4231}
4232
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004233void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004234 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004235 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004236 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237
Antonio Kantekf16f2832021-09-28 04:39:20 +00004238 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004240 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004242 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004243 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004244 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 } // release lock
4246
4247 if (needWake) {
4248 mLooper->wake();
4249 }
4250}
4251
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004252void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004253 ALOGD_IF(debugInboundEventDetails(),
4254 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4255 ", deviceId=%d, source=%s, displayId=%" PRId32
4256 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4257 "downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004258 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4259 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4260 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004261 Result<void> keyCheck = validateKeyEvent(args.action);
4262 if (!keyCheck.ok()) {
4263 LOG(ERROR) << "invalid key event: " << keyCheck.error();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 return;
4265 }
4266
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004267 uint32_t policyFlags = args.policyFlags;
4268 int32_t flags = args.flags;
4269 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004270 // InputDispatcher tracks and generates key repeats on behalf of
4271 // whatever notifies it, so repeatCount should always be set to 0
4272 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4274 policyFlags |= POLICY_FLAG_VIRTUAL;
4275 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 if (policyFlags & POLICY_FLAG_FUNCTION) {
4278 metaState |= AMETA_FUNCTION_ON;
4279 }
4280
4281 policyFlags |= POLICY_FLAG_TRUSTED;
4282
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004283 int32_t keyCode = args.keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 KeyEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004285 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4286 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4287 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288
Michael Wright2b3c3302018-03-02 17:19:13 +00004289 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004290 mPolicy.interceptKeyBeforeQueueing(event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004291 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4292 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004293 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295
Antonio Kantekf16f2832021-09-28 04:39:20 +00004296 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 { // acquire lock
4298 mLock.lock();
4299
4300 if (shouldSendKeyToInputFilterLocked(args)) {
4301 mLock.unlock();
4302
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004303 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004304 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 return; // event was consumed by the filter
4306 }
4307
4308 mLock.lock();
4309 }
4310
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004311 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004312 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4313 args.displayId, policyFlags, args.action, flags, keyCode,
4314 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004316 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 mLock.unlock();
4318 } // release lock
4319
4320 if (needWake) {
4321 mLooper->wake();
4322 }
4323}
4324
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004325bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 return mInputFilterEnabled;
4327}
4328
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004329void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004330 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004331 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004332 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004333 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004334 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4335 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004336 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4337 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4338 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4339 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4340 args.downTime);
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004341 for (uint32_t i = 0; i < args.getPointerCount(); i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004342 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4343 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004344 i, args.pointerProperties[i].id,
4345 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4346 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4347 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4348 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4349 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4350 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4351 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4352 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4353 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4354 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356 }
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004357
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004358 Result<void> motionCheck =
4359 validateMotionEvent(args.action, args.actionButton, args.getPointerCount(),
4360 args.pointerProperties.data());
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004361 if (!motionCheck.ok()) {
4362 LOG(FATAL) << "Invalid event: " << args.dump() << "; reason: " << motionCheck.error();
4363 return;
4364 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004366 if (DEBUG_VERIFY_EVENTS) {
4367 auto [it, _] =
4368 mVerifiersByDisplay.try_emplace(args.displayId,
4369 StringPrintf("display %" PRId32, args.displayId));
4370 Result<void> result =
Siarhei Vishniakou2d151ac2023-09-19 13:30:24 -07004371 it->second.processMovement(args.deviceId, args.source, args.action,
4372 args.getPointerCount(), args.pointerProperties.data(),
4373 args.pointerCoords.data(), args.flags);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07004374 if (!result.ok()) {
4375 LOG(FATAL) << "Bad stream: " << result.error() << " caused by " << args.dump();
4376 }
4377 }
4378
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004379 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004381
4382 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004383 mPolicy.interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004384 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4385 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004386 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388
Antonio Kantekf16f2832021-09-28 04:39:20 +00004389 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390 { // acquire lock
4391 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004392 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4393 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4394 // complete the processing of the current stroke.
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004395 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004396 if (touchStateIt != mTouchStatesByDisplay.end()) {
4397 const TouchState& touchState = touchStateIt->second;
Siarhei Vishniakou45504fe2023-05-05 16:05:10 -07004398 if (touchState.hasTouchingPointers(args.deviceId)) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004399 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4400 }
4401 }
4402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403
4404 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004405 ui::Transform displayTransform;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004406 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004407 displayTransform = it->second.transform;
4408 }
4409
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 mLock.unlock();
4411
4412 MotionEvent event;
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004413 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4414 args.action, args.actionButton, args.flags, args.edgeFlags,
4415 args.metaState, args.buttonState, args.classification,
4416 displayTransform, args.xPrecision, args.yPrecision,
4417 args.xCursorPosition, args.yCursorPosition, displayTransform,
Siarhei Vishniakou3218fc02023-06-15 20:41:02 -07004418 args.downTime, args.eventTime, args.getPointerCount(),
4419 args.pointerProperties.data(), args.pointerCoords.data());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420
4421 policyFlags |= POLICY_FLAG_FILTERED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004422 if (!mPolicy.filterInputEvent(event, policyFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 return; // event was consumed by the filter
4424 }
4425
4426 mLock.lock();
4427 }
4428
4429 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004430 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004431 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4432 args.displayId, policyFlags, args.action,
4433 args.actionButton, args.flags, args.metaState,
4434 args.buttonState, args.classification, args.edgeFlags,
4435 args.xPrecision, args.yPrecision,
4436 args.xCursorPosition, args.yCursorPosition,
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004437 args.downTime, args.pointerProperties,
4438 args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004440 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4441 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004442 !mInputFilterEnabled) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004443 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
Asmita Poddardd9a6cd2023-09-26 15:35:12 +00004444 std::set<InputDeviceUsageSource> sources = getUsageSourcesForMotionArgs(args);
4445 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime,
4446 args.deviceId, sources);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004447 }
4448
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004449 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 mLock.unlock();
4451 } // release lock
4452
4453 if (needWake) {
4454 mLooper->wake();
4455 }
4456}
4457
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004458void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004459 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004460 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4461 " sensorType=%s",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004462 args.id, args.eventTime, args.deviceId, args.source,
4463 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004464 }
Chris Yef59a2f42020-10-16 12:55:26 -07004465
Antonio Kantekf16f2832021-09-28 04:39:20 +00004466 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004467 { // acquire lock
4468 mLock.lock();
4469
4470 // Just enqueue a new sensor event.
4471 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004472 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4473 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4474 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004475
4476 needWake = enqueueInboundEventLocked(std::move(newEntry));
4477 mLock.unlock();
4478 } // release lock
4479
4480 if (needWake) {
4481 mLooper->wake();
4482 }
4483}
4484
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004485void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004486 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004487 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4488 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004489 }
Prabir Pradhana41d2442023-04-20 21:30:40 +00004490 mPolicy.notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004491}
4492
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004493bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004494 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495}
4496
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004497void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004498 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004499 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4500 "switchMask=0x%08x",
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004501 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004504 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004506 mPolicy.notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507}
4508
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004509void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004510 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004511 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4512 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514
Antonio Kantekf16f2832021-09-28 04:39:20 +00004515 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004517 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004519 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004520 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004521 needWake = enqueueInboundEventLocked(std::move(newEntry));
Siarhei Vishniakou1160ecd2023-06-28 15:57:47 -07004522
4523 for (auto& [_, verifier] : mVerifiersByDisplay) {
4524 verifier.resetDevice(args.deviceId);
4525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526 } // release lock
4527
4528 if (needWake) {
4529 mLooper->wake();
4530 }
4531}
4532
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004533void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004534 if (debugInboundEventDetails()) {
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004535 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4536 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004537 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004538
Antonio Kantekf16f2832021-09-28 04:39:20 +00004539 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004540 { // acquire lock
4541 std::scoped_lock _l(mLock);
Prabir Pradhanc392d8f2023-04-13 19:32:51 +00004542 auto entry =
4543 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004544 needWake = enqueueInboundEventLocked(std::move(entry));
4545 } // release lock
4546
4547 if (needWake) {
4548 mLooper->wake();
4549 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004550}
4551
Prabir Pradhan5735a322022-04-11 17:23:34 +00004552InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00004553 std::optional<gui::Uid> targetUid,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004554 InputEventInjectionSync syncMode,
4555 std::chrono::milliseconds timeout,
4556 uint32_t policyFlags) {
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004557 Result<void> eventValidation = validateInputEvent(*event);
4558 if (!eventValidation.ok()) {
4559 LOG(INFO) << "Injection failed: invalid event: " << eventValidation.error();
4560 return InputEventInjectionResult::FAILED;
4561 }
4562
Prabir Pradhan65613802023-02-22 23:36:58 +00004563 if (debugInboundEventDetails()) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004564 LOG(INFO) << __func__ << ": targetUid=" << toString(targetUid, &uidString)
4565 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4566 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4567 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004568 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004569 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570
Prabir Pradhan5735a322022-04-11 17:23:34 +00004571 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004573 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004574 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4575 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4576 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4577 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4578 // from events that originate from actual hardware.
Siarhei Vishniakouf4043212023-09-18 19:33:03 -07004579 DeviceId resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004580 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004581 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004582 }
4583
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004584 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004586 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004587 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004588 const int32_t action = incomingKey.getAction();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004589 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004590 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4591 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4592 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004593 int32_t keyCode = incomingKey.getKeyCode();
4594 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004595 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004596 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004597 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4598 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4599 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004601 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4602 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004603 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004604
4605 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4606 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004607 mPolicy.interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004608 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4609 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4610 std::to_string(t.duration().count()).c_str());
4611 }
4612 }
4613
4614 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004615 std::unique_ptr<KeyEntry> injectedEntry =
4616 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004617 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004618 incomingKey.getDisplayId(), policyFlags, action,
4619 flags, keyCode, incomingKey.getScanCode(), metaState,
4620 incomingKey.getRepeatCount(),
4621 incomingKey.getDownTime());
4622 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004623 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 }
4625
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004626 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004627 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004628 const bool isPointerEvent =
4629 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4630 // If a pointer event has no displayId specified, inject it to the default display.
4631 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4632 ? ADISPLAY_ID_DEFAULT
4633 : event->getDisplayId();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004634 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004635
4636 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004637 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004638 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00004639 mPolicy.interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004640 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4641 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4642 std::to_string(t.duration().count()).c_str());
4643 }
4644 }
4645
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004646 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4647 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4648 }
4649
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004650 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004651 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004652 const size_t pointerCount = motionEvent.getPointerCount();
4653 const std::vector<PointerProperties>
4654 pointerProperties(motionEvent.getPointerProperties(),
4655 motionEvent.getPointerProperties() + pointerCount);
4656
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004657 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004658 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004659 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4660 resolvedDeviceId, motionEvent.getSource(),
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004661 displayId, policyFlags, motionEvent.getAction(),
4662 motionEvent.getActionButton(), flags,
4663 motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004664 motionEvent.getButtonState(),
4665 motionEvent.getClassification(),
4666 motionEvent.getEdgeFlags(),
4667 motionEvent.getXPrecision(),
4668 motionEvent.getYPrecision(),
4669 motionEvent.getRawXCursorPosition(),
4670 motionEvent.getRawYCursorPosition(),
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004671 motionEvent.getDownTime(), pointerProperties,
4672 std::vector<PointerCoords>(samplePointerCoords,
4673 samplePointerCoords +
4674 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004675 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004676 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004677 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004678 sampleEventTimes += 1;
Siarhei Vishniakou23740b92023-04-21 11:30:20 -07004679 samplePointerCoords += motionEvent.getPointerCount();
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004680 std::unique_ptr<MotionEntry> nextInjectedEntry = std::make_unique<
4681 MotionEntry>(motionEvent.getId(), *sampleEventTimes, resolvedDeviceId,
4682 motionEvent.getSource(), displayId, policyFlags,
4683 motionEvent.getAction(), motionEvent.getActionButton(), flags,
4684 motionEvent.getMetaState(), motionEvent.getButtonState(),
4685 motionEvent.getClassification(), motionEvent.getEdgeFlags(),
4686 motionEvent.getXPrecision(), motionEvent.getYPrecision(),
4687 motionEvent.getRawXCursorPosition(),
4688 motionEvent.getRawYCursorPosition(), motionEvent.getDownTime(),
4689 pointerProperties,
4690 std::vector<PointerCoords>(samplePointerCoords,
4691 samplePointerCoords +
4692 pointerCount));
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004693 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4694 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004695 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004696 }
4697 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004700 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004701 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004702 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 }
4704
Prabir Pradhan5735a322022-04-11 17:23:34 +00004705 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004706 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 injectionState->injectionIsAsync = true;
4708 }
4709
4710 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004711 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712
4713 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004714 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004715 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004716 LOG(INFO) << "Injecting " << injectedEntries.front()->getDescription();
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004717 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004718 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004719 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 }
4721
4722 mLock.unlock();
4723
4724 if (needWake) {
4725 mLooper->wake();
4726 }
4727
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004728 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004730 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004732 if (syncMode == InputEventInjectionSync::NONE) {
4733 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734 } else {
4735 for (;;) {
4736 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004737 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738 break;
4739 }
4740
4741 nsecs_t remainingTimeout = endTime - now();
4742 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004743 if (DEBUG_INJECTION) {
4744 ALOGD("injectInputEvent - Timed out waiting for injection result "
4745 "to become available.");
4746 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004747 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 break;
4749 }
4750
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004751 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 }
4753
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004754 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4755 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004757 if (DEBUG_INJECTION) {
4758 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4759 injectionState->pendingForegroundDispatches);
4760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761 nsecs_t remainingTimeout = endTime - now();
4762 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004763 if (DEBUG_INJECTION) {
4764 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4765 "dispatches to finish.");
4766 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004767 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 break;
4769 }
4770
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004771 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 }
4773 }
4774 }
4775
4776 injectionState->release();
4777 } // release lock
4778
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004779 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004780 LOG(INFO) << "injectInputEvent - Finished with result "
4781 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783
4784 return injectionResult;
4785}
4786
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004787std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004788 std::array<uint8_t, 32> calculatedHmac;
4789 std::unique_ptr<VerifiedInputEvent> result;
4790 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004791 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004792 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4793 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4794 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004795 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004796 break;
4797 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004798 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004799 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4800 VerifiedMotionEvent verifiedMotionEvent =
4801 verifiedMotionEventFromMotionEvent(motionEvent);
4802 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004803 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004804 break;
4805 }
4806 default: {
4807 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4808 return nullptr;
4809 }
4810 }
4811 if (calculatedHmac == INVALID_HMAC) {
4812 return nullptr;
4813 }
tyiu1573a672023-02-21 22:38:32 +00004814 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004815 return nullptr;
4816 }
4817 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004818}
4819
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004820void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004821 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004822 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004824 if (DEBUG_INJECTION) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07004825 LOG(INFO) << "Setting input event injection result to "
4826 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004829 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 // Log the outcome since the injector did not wait for the injection result.
4831 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004832 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004833 ALOGV("Asynchronous input event injection succeeded.");
4834 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004835 case InputEventInjectionResult::TARGET_MISMATCH:
4836 ALOGV("Asynchronous input event injection target mismatch.");
4837 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004838 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004839 ALOGW("Asynchronous input event injection failed.");
4840 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004841 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004842 ALOGW("Asynchronous input event injection timed out.");
4843 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004844 case InputEventInjectionResult::PENDING:
4845 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4846 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 }
4848 }
4849
4850 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004851 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852 }
4853}
4854
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004855void InputDispatcher::transformMotionEntryForInjectionLocked(
4856 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004857 // Input injection works in the logical display coordinate space, but the input pipeline works
4858 // display space, so we need to transform the injected events accordingly.
4859 const auto it = mDisplayInfos.find(entry.displayId);
4860 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004861 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004862
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004863 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4864 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4865 const vec2 cursor =
4866 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4867 {entry.xCursorPosition, entry.yCursorPosition});
4868 entry.xCursorPosition = cursor.x;
4869 entry.yCursorPosition = cursor.y;
4870 }
Siarhei Vishniakouedd61202023-10-18 11:22:40 -07004871 for (uint32_t i = 0; i < entry.getPointerCount(); i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004872 entry.pointerCoords[i] =
4873 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4874 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004875 }
4876}
4877
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004878void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4879 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 if (injectionState) {
4881 injectionState->pendingForegroundDispatches += 1;
4882 }
4883}
4884
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004885void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4886 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887 if (injectionState) {
4888 injectionState->pendingForegroundDispatches -= 1;
4889
4890 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004891 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892 }
4893 }
4894}
4895
chaviw98318de2021-05-19 16:45:23 -05004896const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004897 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004898 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004899 auto it = mWindowHandlesByDisplay.find(displayId);
4900 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004901}
4902
chaviw98318de2021-05-19 16:45:23 -05004903sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
Prabir Pradhan16463382023-10-12 23:03:19 +00004904 const sp<IBinder>& windowHandleToken, std::optional<int32_t> displayId) const {
arthurhungbe737672020-06-24 12:29:21 +08004905 if (windowHandleToken == nullptr) {
4906 return nullptr;
4907 }
4908
Prabir Pradhan16463382023-10-12 23:03:19 +00004909 if (!displayId) {
4910 // Look through all displays.
4911 for (auto& it : mWindowHandlesByDisplay) {
4912 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4913 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
4914 if (windowHandle->getToken() == windowHandleToken) {
4915 return windowHandle;
4916 }
Arthur Hungb92218b2018-08-14 12:00:21 +08004917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07004919 return nullptr;
4920 }
4921
Prabir Pradhan16463382023-10-12 23:03:19 +00004922 // Only look through the requested display.
4923 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(*displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004924 if (windowHandle->getToken() == windowHandleToken) {
4925 return windowHandle;
4926 }
4927 }
4928 return nullptr;
4929}
4930
chaviw98318de2021-05-19 16:45:23 -05004931sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4932 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004933 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004934 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4935 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004936 if (handle->getId() == windowHandle->getId() &&
4937 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004938 if (windowHandle->getInfo()->displayId != it.first) {
4939 ALOGE("Found window %s in display %" PRId32
4940 ", but it should belong to display %" PRId32,
4941 windowHandle->getName().c_str(), it.first,
4942 windowHandle->getInfo()->displayId);
4943 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004944 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946 }
4947 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004948 return nullptr;
4949}
4950
chaviw98318de2021-05-19 16:45:23 -05004951sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004952 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4953 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004954}
4955
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004956ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4957 auto displayInfoIt = mDisplayInfos.find(displayId);
4958 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4959 : kIdentityTransform;
4960}
4961
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004962bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4963 const MotionEntry& motionEntry) const {
4964 const WindowInfo& info = *window->getInfo();
4965
4966 // Skip spy window targets that are not valid for targeted injection.
4967 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004968 return false;
4969 }
4970
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004971 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4972 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4973 return false;
4974 }
4975
4976 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4977 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4978 window->getName().c_str());
4979 return false;
4980 }
4981
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004982 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004983 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004984 ALOGW("Not sending touch to %s because there's no corresponding connection",
4985 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004986 return false;
4987 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004988
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004989 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004990 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004991 return false;
4992 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004993
4994 // Drop events that can't be trusted due to occlusion
4995 const auto [x, y] = resolveTouchedPosition(motionEntry);
4996 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4997 if (!isTouchTrustedLocked(occlusionInfo)) {
4998 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004999 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005000 for (const auto& log : occlusionInfo.debugInfo) {
5001 ALOGD("%s", log.c_str());
5002 }
5003 }
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005004 ALOGW("Dropping untrusted touch event due to %s/%s", occlusionInfo.obscuringPackage.c_str(),
5005 occlusionInfo.obscuringUid.toString().c_str());
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07005006 return false;
5007 }
5008
5009 // Drop touch events if requested by input feature
5010 if (shouldDropInput(motionEntry, window)) {
5011 return false;
5012 }
5013
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005014 return true;
5015}
5016
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005017std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
5018 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005019 auto connectionIt = mConnectionsByToken.find(token);
5020 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07005021 return nullptr;
5022 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005023 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07005024}
5025
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005026void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05005027 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
5028 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005029 // Remove all handles on a display if there are no windows left.
5030 mWindowHandlesByDisplay.erase(displayId);
5031 return;
5032 }
5033
5034 // Since we compare the pointer of input window handles across window updates, we need
5035 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05005036 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
5037 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
5038 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07005039 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005040 }
5041
chaviw98318de2021-05-19 16:45:23 -05005042 std::vector<sp<WindowInfoHandle>> newHandles;
5043 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05005044 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06005045 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005046 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005047 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005048 const bool canReceiveInput =
5049 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
5050 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005051 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07005052 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005053 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07005054 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005055 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005056 }
5057
5058 if (info->displayId != displayId) {
5059 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
5060 handle->getName().c_str(), displayId, info->displayId);
5061 continue;
5062 }
5063
Robert Carredd13602020-04-13 17:24:34 -07005064 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
5065 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05005066 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005067 oldHandle->updateFrom(handle);
5068 newHandles.push_back(oldHandle);
5069 } else {
5070 newHandles.push_back(handle);
5071 }
5072 }
5073
5074 // Insert or replace
5075 mWindowHandlesByDisplay[displayId] = newHandles;
5076}
5077
Arthur Hungb92218b2018-08-14 12:00:21 +08005078/**
5079 * Called from InputManagerService, update window handle list by displayId that can receive input.
5080 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
5081 * If set an empty list, remove all handles from the specific display.
5082 * For focused handle, check if need to change and send a cancel event to previous one.
5083 * For removed handle, check if need to send a cancel event if already in touch.
5084 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00005085void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05005086 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005087 if (DEBUG_FOCUS) {
5088 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05005089 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005090 windowList += iwh->getName() + " ";
5091 }
5092 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
5093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005094
Prabir Pradhand65552b2021-10-07 11:23:50 -07005095 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05005096 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07005097 const WindowInfo& info = *window->getInfo();
5098
5099 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005100 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005101 if (noInputWindow && window->getToken() != nullptr) {
5102 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
5103 window->getName().c_str());
5104 window->releaseChannel();
5105 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07005106
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005107 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005108 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
5109 !info.inputConfig.test(
5110 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08005111 "%s has feature SPY, but is not a trusted overlay.",
5112 window->getName().c_str());
5113
Prabir Pradhand65552b2021-10-07 11:23:50 -07005114 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005115 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
5116 !info.inputConfig.test(
5117 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07005118 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
5119 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005120 }
5121
Arthur Hung72d8dc32020-03-28 00:48:39 +00005122 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05005123 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124
chaviw98318de2021-05-19 16:45:23 -05005125 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07005126
chaviw98318de2021-05-19 16:45:23 -05005127 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005128
Vishnu Nairc519ff72021-01-21 08:23:08 -08005129 std::optional<FocusResolver::FocusChanges> changes =
5130 mFocusResolver.setInputWindows(displayId, windowHandles);
5131 if (changes) {
5132 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00005133 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005135 std::unordered_map<int32_t, TouchState>::iterator stateIt =
5136 mTouchStatesByDisplay.find(displayId);
5137 if (stateIt != mTouchStatesByDisplay.end()) {
5138 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00005139 for (size_t i = 0; i < state.windows.size();) {
5140 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005141 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005142 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005143 ALOGD("Touched window was removed: %s in display %" PRId32,
5144 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005145 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005146 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00005147 getInputChannelLocked(touchedWindow.windowHandle->getToken());
5148 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005149 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00005150 "touched window was removed");
5151 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005152 // Since we are about to drop the touch, cancel the events for the wallpaper as
5153 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005154 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005155 touchedWindow.windowHandle->getInfo()->inputConfig.test(
5156 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005157 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00005158 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00005159 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005161 state.windows.erase(state.windows.begin() + i);
5162 } else {
5163 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 }
5165 }
arthurhungb89ccb02020-12-30 16:19:01 +08005166
arthurhung6d4bed92021-03-17 11:59:33 +08005167 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005168 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005169 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005170 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005171 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005172 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5173 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005174 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005175 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005176 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005177
Arthur Hung72d8dc32020-03-28 00:48:39 +00005178 // Release information for windows that are no longer present.
5179 // This ensures that unused input channels are released promptly.
5180 // Otherwise, they might stick around until the window handle is destroyed
5181 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005182 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005183 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005184 if (DEBUG_FOCUS) {
5185 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005186 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005187 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005188 }
chaviw291d88a2019-02-14 10:33:58 -08005189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005190}
5191
5192void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005193 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005194 if (DEBUG_FOCUS) {
5195 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5196 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5197 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005198 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005199 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005200 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005201 } // release lock
5202
5203 // Wake up poll loop since it may need to make new input dispatching choices.
5204 mLooper->wake();
5205}
5206
Vishnu Nair599f1412021-06-21 10:39:58 -07005207void InputDispatcher::setFocusedApplicationLocked(
5208 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5209 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5210 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5211
5212 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5213 return; // This application is already focused. No need to wake up or change anything.
5214 }
5215
5216 // Set the new application handle.
5217 if (inputApplicationHandle != nullptr) {
5218 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5219 } else {
5220 mFocusedApplicationHandlesByDisplay.erase(displayId);
5221 }
5222
5223 // No matter what the old focused application was, stop waiting on it because it is
5224 // no longer focused.
5225 resetNoFocusedWindowTimeoutLocked();
5226}
5227
Tiger Huang721e26f2018-07-24 22:26:19 +08005228/**
5229 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5230 * the display not specified.
5231 *
5232 * We track any unreleased events for each window. If a window loses the ability to receive the
5233 * released event, we will send a cancel event to it. So when the focused display is changed, we
5234 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5235 * display. The display-specified events won't be affected.
5236 */
5237void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005238 if (DEBUG_FOCUS) {
5239 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5240 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005241 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005242 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005243
5244 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005245 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005246 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005247 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005248 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005249 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005250 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005251 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005252 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005253 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005254 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005255 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5256 }
5257 }
5258 mFocusedDisplayId = displayId;
5259
Chris Ye3c2d6f52020-08-09 10:39:48 -07005260 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005261 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005262 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005263
Vishnu Nairad321cd2020-08-20 16:40:21 -07005264 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005265 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005266 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005267 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005268 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005269 }
5270 }
5271 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005272 } // release lock
5273
5274 // Wake up poll loop since it may need to make new input dispatching choices.
5275 mLooper->wake();
5276}
5277
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005279 if (DEBUG_FOCUS) {
5280 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5281 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282
5283 bool changed;
5284 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005285 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286
5287 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5288 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005289 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290 }
5291
5292 if (mDispatchEnabled && !enabled) {
5293 resetAndDropEverythingLocked("dispatcher is being disabled");
5294 }
5295
5296 mDispatchEnabled = enabled;
5297 mDispatchFrozen = frozen;
5298 changed = true;
5299 } else {
5300 changed = false;
5301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302 } // release lock
5303
5304 if (changed) {
5305 // Wake up poll loop since it may need to make new input dispatching choices.
5306 mLooper->wake();
5307 }
5308}
5309
5310void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005311 if (DEBUG_FOCUS) {
5312 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314
5315 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005316 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317
5318 if (mInputFilterEnabled == enabled) {
5319 return;
5320 }
5321
5322 mInputFilterEnabled = enabled;
5323 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5324 } // release lock
5325
5326 // Wake up poll loop since there might be work to do to drop everything.
5327 mLooper->wake();
5328}
5329
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005330bool InputDispatcher::setInTouchMode(bool inTouchMode, gui::Pid pid, gui::Uid uid,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005331 bool hasPermission, int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005332 bool needWake = false;
5333 {
5334 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005335 ALOGD_IF(DEBUG_TOUCH_MODE,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005336 "Request to change touch mode to %s (calling pid=%s, uid=%s, "
Antonio Kantek15beb512022-06-13 22:35:41 +00005337 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005338 toString(inTouchMode), pid.toString().c_str(), uid.toString().c_str(),
5339 toString(hasPermission), displayId,
Antonio Kantek15beb512022-06-13 22:35:41 +00005340 mTouchModePerDisplay.count(displayId) == 0
5341 ? "not set"
5342 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5343
Antonio Kantek15beb512022-06-13 22:35:41 +00005344 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5345 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005346 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005347 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005348 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005349 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5350 !recentWindowsAreOwnedByLocked(pid, uid)) {
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005351 ALOGD("Touch mode switch rejected, caller (pid=%s, uid=%s) doesn't own the focused "
Antonio Kantek48710e42022-03-24 14:19:30 -07005352 "window nor none of the previously interacted window",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005353 pid.toString().c_str(), uid.toString().c_str());
Antonio Kantekea47acb2021-12-23 12:41:25 -08005354 return false;
5355 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005356 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005357 mTouchModePerDisplay[displayId] = inTouchMode;
5358 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5359 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005360 needWake = enqueueInboundEventLocked(std::move(entry));
5361 } // release lock
5362
5363 if (needWake) {
5364 mLooper->wake();
5365 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005366 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005367}
5368
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005369bool InputDispatcher::focusedWindowIsOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005370 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5371 if (focusedToken == nullptr) {
5372 return false;
5373 }
5374 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5375 return isWindowOwnedBy(windowHandle, pid, uid);
5376}
5377
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005378bool InputDispatcher::recentWindowsAreOwnedByLocked(gui::Pid pid, gui::Uid uid) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005379 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5380 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5381 const sp<WindowInfoHandle> windowHandle =
5382 getWindowHandleLocked(connectionToken);
5383 return isWindowOwnedBy(windowHandle, pid, uid);
5384 }) != mInteractionConnectionTokens.end();
5385}
5386
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005387void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5388 if (opacity < 0 || opacity > 1) {
5389 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5390 return;
5391 }
5392
5393 std::scoped_lock lock(mLock);
5394 mMaximumObscuringOpacityForTouch = opacity;
5395}
5396
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005397std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5398InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005399 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5400 for (TouchedWindow& w : state.windows) {
5401 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005402 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005403 }
5404 }
5405 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005406 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005407}
5408
arthurhungb89ccb02020-12-30 16:19:01 +08005409bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5410 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005411 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005412 if (DEBUG_FOCUS) {
5413 ALOGD("Trivial transfer to same window.");
5414 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005415 return true;
5416 }
5417
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005419 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420
Arthur Hungabbb9d82021-09-01 14:52:30 +00005421 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005422 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005423
Arthur Hungabbb9d82021-09-01 14:52:30 +00005424 if (state == nullptr || touchedWindow == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005425 ALOGD("Touch transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426 return false;
5427 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005428 std::set<int32_t> deviceIds = touchedWindow->getTouchingDeviceIds();
5429 if (deviceIds.size() != 1) {
Siarhei Vishniakou827d1ac2023-07-21 16:37:51 -07005430 LOG(INFO) << "Can't transfer touch. Currently touching devices: " << dumpSet(deviceIds)
5431 << " for window: " << touchedWindow->dump();
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005432 return false;
5433 }
5434 const int32_t deviceId = *deviceIds.begin();
Arthur Hungabbb9d82021-09-01 14:52:30 +00005435
Arthur Hungabbb9d82021-09-01 14:52:30 +00005436 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5437 if (toWindowHandle == nullptr) {
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005438 ALOGW("Cannot transfer touch because to window not found.");
Arthur Hungabbb9d82021-09-01 14:52:30 +00005439 return false;
5440 }
5441
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005442 if (DEBUG_FOCUS) {
5443 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005444 touchedWindow->windowHandle->getName().c_str(),
5445 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 }
5447
Arthur Hungabbb9d82021-09-01 14:52:30 +00005448 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005449 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005450 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->getTouchingPointers(deviceId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005451 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005452 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005453
Arthur Hungabbb9d82021-09-01 14:52:30 +00005454 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005455 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005456 ftl::Flags<InputTarget::Flags> newTargetFlags =
5457 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005458 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005459 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005460 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005461 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, deviceId, pointerIds,
5462 downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463
Arthur Hungabbb9d82021-09-01 14:52:30 +00005464 // Store the dragging window.
5465 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005466 if (pointerIds.count() != 1) {
5467 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5468 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005469 return false;
5470 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005471 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005472 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005473 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474 }
5475
Arthur Hungabbb9d82021-09-01 14:52:30 +00005476 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005477 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5478 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005479 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005480 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005481 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5482 "transferring touch from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005484 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5485 newTargetFlags);
5486
5487 // Check if the wallpaper window should deliver the corresponding event.
5488 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005489 *state, deviceId, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 } // release lock
5492
5493 // Wake up poll loop since it may need to make new input dispatching choices.
5494 mLooper->wake();
5495 return true;
5496}
5497
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005498/**
5499 * Get the touched foreground window on the given display.
5500 * Return null if there are no windows touched on that display, or if more than one foreground
5501 * window is being touched.
5502 */
5503sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5504 auto stateIt = mTouchStatesByDisplay.find(displayId);
5505 if (stateIt == mTouchStatesByDisplay.end()) {
5506 ALOGI("No touch state on display %" PRId32, displayId);
5507 return nullptr;
5508 }
5509
5510 const TouchState& state = stateIt->second;
5511 sp<WindowInfoHandle> touchedForegroundWindow;
5512 // If multiple foreground windows are touched, return nullptr
5513 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005514 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005515 if (touchedForegroundWindow != nullptr) {
5516 ALOGI("Two or more foreground windows: %s and %s",
5517 touchedForegroundWindow->getName().c_str(),
5518 window.windowHandle->getName().c_str());
5519 return nullptr;
5520 }
5521 touchedForegroundWindow = window.windowHandle;
5522 }
5523 }
5524 return touchedForegroundWindow;
5525}
5526
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005527// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005528bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005529 sp<IBinder> fromToken;
5530 { // acquire lock
5531 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005532 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005533 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005534 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5535 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005536 return false;
5537 }
5538
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005539 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5540 if (from == nullptr) {
5541 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5542 return false;
5543 }
5544
5545 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005546 } // release lock
5547
5548 return transferTouchFocus(fromToken, destChannelToken);
5549}
5550
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005552 if (DEBUG_FOCUS) {
5553 ALOGD("Resetting and dropping all events (%s).", reason);
5554 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555
Michael Wrightfb04fd52022-11-24 22:31:11 +00005556 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557 synthesizeCancelationEventsForAllConnectionsLocked(options);
5558
5559 resetKeyRepeatLocked();
5560 releasePendingEventLocked();
5561 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005562 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005564 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005565 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566}
5567
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005568void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005569 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570 dumpDispatchStateLocked(dump);
5571
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005572 std::istringstream stream(dump);
5573 std::string line;
5574
5575 while (std::getline(stream, line, '\n')) {
Siarhei Vishniakoua235c042023-05-02 09:59:09 -07005576 ALOGI("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005577 }
5578}
5579
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005580std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005581 std::string dump;
5582
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005583 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5584 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005585
5586 std::string windowName = "None";
5587 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005588 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005589 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5590 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5591 : "token has capture without window";
5592 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005593 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005594
5595 return dump;
5596}
5597
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005598void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005599 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5600 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5601 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005602 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005603
Tiger Huang721e26f2018-07-24 22:26:19 +08005604 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5605 dump += StringPrintf(INDENT "FocusedApplications:\n");
5606 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5607 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005608 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005609 const std::chrono::duration timeout =
5610 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005611 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005612 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005613 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005616 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005618
Vishnu Nairc519ff72021-01-21 08:23:08 -08005619 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005620 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005622 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005623 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005624 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005625 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5626 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627 }
5628 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005629 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630 }
5631
arthurhung6d4bed92021-03-17 11:59:33 +08005632 if (mDragState) {
5633 dump += StringPrintf(INDENT "DragState:\n");
5634 mDragState->dump(dump, INDENT2);
5635 }
5636
Arthur Hungb92218b2018-08-14 12:00:21 +08005637 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005638 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5639 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5640 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5641 const auto& displayInfo = it->second;
5642 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5643 displayInfo.logicalHeight);
5644 displayInfo.transform.dump(dump, "transform", INDENT4);
5645 } else {
5646 dump += INDENT2 "No DisplayInfo found!\n";
5647 }
5648
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005649 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005650 dump += INDENT2 "Windows:\n";
5651 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005652 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5653 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005655 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005656 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005657 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005658 "applicationInfo.name=%s, "
5659 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005660 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005661 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005662 windowInfo->displayId,
5663 windowInfo->inputConfig.string().c_str(),
Chavi Weingarten7f019192023-08-08 20:39:01 +00005664 windowInfo->alpha, windowInfo->frame.left,
5665 windowInfo->frame.top, windowInfo->frame.right,
5666 windowInfo->frame.bottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005667 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005668 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005669 dump += dumpRegion(windowInfo->touchableRegion);
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005670 dump += StringPrintf(", ownerPid=%s, ownerUid=%s, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005671 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005672 "touchOcclusionMode=%s\n",
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005673 windowInfo->ownerPid.toString().c_str(),
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +00005674 windowInfo->ownerUid.toString().c_str(),
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005675 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005676 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005677 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005678 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005679 }
5680 } else {
5681 dump += INDENT2 "Windows: <none>\n";
5682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005683 }
5684 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005685 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005686 }
5687
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005688 if (!mGlobalMonitorsByDisplay.empty()) {
5689 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5690 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005691 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005694 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695 }
5696
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005697 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005698
5699 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005700 if (!mRecentQueue.empty()) {
5701 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005702 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005703 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005704 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005705 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005706 }
5707 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005708 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709 }
5710
5711 // Dump event currently being dispatched.
5712 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005713 dump += INDENT "PendingEvent:\n";
5714 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005715 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005716 dump += StringPrintf(", age=%" PRId64 "ms\n",
5717 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005719 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005720 }
5721
5722 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005723 if (!mInboundQueue.empty()) {
5724 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005725 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005726 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005727 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005728 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729 }
5730 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005731 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005732 }
5733
Prabir Pradhancef936d2021-07-21 16:17:52 +00005734 if (!mCommandQueue.empty()) {
5735 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5736 } else {
5737 dump += INDENT "CommandQueue: <empty>\n";
5738 }
5739
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005740 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005741 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005742 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005743 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005744 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005745 connection->inputChannel->getFd().get(),
5746 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005747 connection->getWindowName().c_str(),
5748 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005749 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005750
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005751 if (!connection->outboundQueue.empty()) {
5752 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5753 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005754 dump += dumpQueue(connection->outboundQueue, currentTime);
5755
Michael Wrightd02c5b62014-02-10 15:10:22 -08005756 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005757 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005758 }
5759
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005760 if (!connection->waitQueue.empty()) {
5761 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5762 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005763 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005765 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005766 }
Siarhei Vishniakoud38a1e02023-07-18 11:55:17 -07005767 std::stringstream inputStateDump;
5768 inputStateDump << connection->inputState;
5769 if (!isEmpty(inputStateDump)) {
5770 dump += INDENT3 "InputState: ";
5771 dump += inputStateDump.str() + "\n";
5772 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773 }
5774 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005775 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005776 }
5777
5778 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005779 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5780 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005782 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005783 }
5784
Antonio Kantek15beb512022-06-13 22:35:41 +00005785 if (!mTouchModePerDisplay.empty()) {
5786 dump += INDENT "TouchModePerDisplay:\n";
5787 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5788 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5789 std::to_string(touchMode).c_str());
5790 }
5791 } else {
5792 dump += INDENT "TouchModePerDisplay: <none>\n";
5793 }
5794
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005795 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005796 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5797 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5798 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005799 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005800 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005801}
5802
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005803void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005804 const size_t numMonitors = monitors.size();
5805 for (size_t i = 0; i < numMonitors; i++) {
5806 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005807 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005808 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5809 dump += "\n";
5810 }
5811}
5812
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005813class LooperEventCallback : public LooperCallback {
5814public:
5815 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5816 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5817
5818private:
5819 std::function<int(int events)> mCallback;
5820};
5821
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005822Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005823 if (DEBUG_CHANNEL_CREATION) {
5824 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005826
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005827 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005828 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005829 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005830
5831 if (result) {
5832 return base::Error(result) << "Failed to open input channel pair with name " << name;
5833 }
5834
Michael Wrightd02c5b62014-02-10 15:10:22 -08005835 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005836 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005837 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005838 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005839 std::shared_ptr<Connection> connection =
5840 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5841 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005842
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005843 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5844 ALOGE("Created a new connection, but the token %p is already known", token.get());
5845 }
5846 mConnectionsByToken.emplace(token, connection);
5847
5848 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5849 this, std::placeholders::_1, token);
5850
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005851 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5852 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005853 } // release lock
5854
5855 // Wake the looper because some connections have changed.
5856 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005857 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005858}
5859
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005860Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005861 const std::string& name,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00005862 gui::Pid pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005863 std::shared_ptr<InputChannel> serverChannel;
5864 std::unique_ptr<InputChannel> clientChannel;
5865 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5866 if (result) {
5867 return base::Error(result) << "Failed to open input channel pair with name " << name;
5868 }
5869
Michael Wright3dd60e22019-03-27 22:06:44 +00005870 { // acquire lock
5871 std::scoped_lock _l(mLock);
5872
5873 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005874 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5875 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005876 }
5877
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005878 std::shared_ptr<Connection> connection =
5879 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005880 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005881 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005882
5883 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5884 ALOGE("Created a new connection, but the token %p is already known", token.get());
5885 }
5886 mConnectionsByToken.emplace(token, connection);
5887 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5888 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005889
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005890 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005891
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005892 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5893 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005894 }
Garfield Tan15601662020-09-22 15:32:38 -07005895
Michael Wright3dd60e22019-03-27 22:06:44 +00005896 // Wake the looper because some connections have changed.
5897 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005898 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005899}
5900
Garfield Tan15601662020-09-22 15:32:38 -07005901status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005903 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005904
Harry Cutts33476232023-01-30 19:57:29 +00005905 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906 if (status) {
5907 return status;
5908 }
5909 } // release lock
5910
5911 // Wake the poll loop because removing the connection may have changed the current
5912 // synchronization state.
5913 mLooper->wake();
5914 return OK;
5915}
5916
Garfield Tan15601662020-09-22 15:32:38 -07005917status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5918 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005919 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005920 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005921 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005922 return BAD_VALUE;
5923 }
5924
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005925 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005926
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005928 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929 }
5930
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005931 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005932
5933 nsecs_t currentTime = now();
5934 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5935
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005936 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937 return OK;
5938}
5939
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005940void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005941 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5942 auto& [displayId, monitors] = *it;
5943 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5944 return monitor.inputChannel->getConnectionToken() == connectionToken;
5945 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005946
Michael Wright3dd60e22019-03-27 22:06:44 +00005947 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005948 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005949 } else {
5950 ++it;
5951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005952 }
5953}
5954
Michael Wright3dd60e22019-03-27 22:06:44 +00005955status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005956 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005957 return pilferPointersLocked(token);
5958}
Michael Wright3dd60e22019-03-27 22:06:44 +00005959
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005960status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005961 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5962 if (!requestingChannel) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005963 LOG(WARNING)
5964 << "Attempted to pilfer pointers from an un-registered channel or invalid token";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005965 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005966 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005967
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005968 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005969 if (statePtr == nullptr || windowPtr == nullptr) {
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005970 LOG(WARNING)
5971 << "Attempted to pilfer points from a channel without any on-going pointer streams."
5972 " Ignoring.";
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005973 return BAD_VALUE;
5974 }
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07005975 std::set<int32_t> deviceIds = windowPtr->getTouchingDeviceIds();
5976 if (deviceIds.size() != 1) {
5977 LOG(WARNING) << "Can't pilfer. Currently touching devices: " << dumpSet(deviceIds)
5978 << " in window: " << windowPtr->dump();
5979 return BAD_VALUE;
5980 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005981
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07005982 for (const DeviceId deviceId : deviceIds) {
5983 TouchState& state = *statePtr;
5984 TouchedWindow& window = *windowPtr;
5985 // Send cancel events to all the input channels we're stealing from.
5986 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
5987 "input channel stole pointer stream");
5988 options.deviceId = deviceId;
5989 options.displayId = displayId;
5990 std::bitset<MAX_POINTER_ID + 1> pointerIds = window.getTouchingPointers(deviceId);
5991 options.pointerIds = pointerIds;
5992 std::string canceledWindows;
5993 for (const TouchedWindow& w : state.windows) {
5994 const std::shared_ptr<InputChannel> channel =
5995 getInputChannelLocked(w.windowHandle->getToken());
5996 if (channel != nullptr && channel->getConnectionToken() != token) {
5997 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5998 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5999 canceledWindows += channel->getName();
6000 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006001 }
Siarhei Vishniakou8384e0d2023-09-18 18:48:27 -07006002 canceledWindows += canceledWindows.empty() ? "[]" : "]";
6003 LOG(INFO) << "Channel " << requestingChannel->getName()
6004 << " is stealing input gesture for device " << deviceId << " from "
6005 << canceledWindows;
6006
6007 // Prevent the gesture from being sent to any other windows.
6008 // This only blocks relevant pointers to be sent to other windows
6009 window.addPilferingPointers(deviceId, pointerIds);
6010
6011 state.cancelPointersForWindowsExcept(deviceId, pointerIds, token);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006012 }
Michael Wright3dd60e22019-03-27 22:06:44 +00006013 return OK;
6014}
6015
Prabir Pradhan99987712020-11-10 18:43:05 -08006016void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
6017 { // acquire lock
6018 std::scoped_lock _l(mLock);
6019 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05006020 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08006021 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
6022 windowHandle != nullptr ? windowHandle->getName().c_str()
6023 : "token without window");
6024 }
6025
Vishnu Nairc519ff72021-01-21 08:23:08 -08006026 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08006027 if (focusedToken != windowToken) {
6028 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
6029 enabled ? "enable" : "disable");
6030 return;
6031 }
6032
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006033 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006034 ALOGW("Ignoring request to %s Pointer Capture: "
6035 "window has %s requested pointer capture.",
6036 enabled ? "enable" : "disable", enabled ? "already" : "not");
6037 return;
6038 }
6039
Christine Franksb768bb42021-11-29 12:11:31 -08006040 if (enabled) {
6041 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
6042 mIneligibleDisplaysForPointerCapture.end(),
6043 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
6044 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
6045 return;
6046 }
6047 }
6048
Prabir Pradhan99987712020-11-10 18:43:05 -08006049 setPointerCaptureLocked(enabled);
6050 } // release lock
6051
6052 // Wake the thread to process command entries.
6053 mLooper->wake();
6054}
6055
Christine Franksb768bb42021-11-29 12:11:31 -08006056void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
6057 { // acquire lock
6058 std::scoped_lock _l(mLock);
6059 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
6060 if (!isEligible) {
6061 mIneligibleDisplaysForPointerCapture.push_back(displayId);
6062 }
6063 } // release lock
6064}
6065
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006066std::optional<gui::Pid> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006067 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00006068 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006069 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006070 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00006071 }
6072 }
6073 }
6074 return std::nullopt;
6075}
6076
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006077std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
6078 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07006079 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006080 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08006081 }
6082
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006083 for (const auto& [token, connection] : mConnectionsByToken) {
6084 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006085 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006086 }
6087 }
Robert Carr4e670e52018-08-15 13:26:12 -07006088
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07006089 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006090}
6091
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006092std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006093 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05006094 if (connection == nullptr) {
6095 return "<nullptr>";
6096 }
6097 return connection->getInputChannelName();
6098}
6099
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006100void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006101 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00006102 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07006103}
6104
Prabir Pradhancef936d2021-07-21 16:17:52 +00006105void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006106 const std::shared_ptr<Connection>& connection,
6107 uint32_t seq, bool handled,
6108 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006109 // Handle post-event policy actions.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006110 bool restartEvent;
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006111
6112 { // Start critical section
6113 auto dispatchEntryIt =
6114 std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6115 [seq](auto& e) { return e->seq == seq; });
6116 if (dispatchEntryIt == connection->waitQueue.end()) {
6117 return;
6118 }
6119
6120 DispatchEntry& dispatchEntry = **dispatchEntryIt;
6121
6122 const nsecs_t eventDuration = finishTime - dispatchEntry.deliveryTime;
6123 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
6124 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
6125 ns2ms(eventDuration), dispatchEntry.eventEntry->getDescription().c_str());
6126 }
6127 if (shouldReportFinishedEvent(dispatchEntry, *connection)) {
6128 mLatencyTracker.trackFinishedEvent(dispatchEntry.eventEntry->id,
6129 connection->inputChannel->getConnectionToken(),
6130 dispatchEntry.deliveryTime, consumeTime, finishTime);
6131 }
6132
6133 if (dispatchEntry.eventEntry->type == EventEntry::Type::KEY) {
6134 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry.eventEntry));
6135 restartEvent =
6136 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
6137 } else if (dispatchEntry.eventEntry->type == EventEntry::Type::MOTION) {
6138 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry.eventEntry));
6139 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry,
6140 motionEntry, handled);
6141 } else {
6142 restartEvent = false;
6143 }
6144 } // End critical section: The -LockedInterruptable methods may have released the lock.
Prabir Pradhancef936d2021-07-21 16:17:52 +00006145
6146 // Dequeue the event and start the next cycle.
6147 // Because the lock might have been released, it is possible that the
6148 // contents of the wait queue to have been drained, so we need to double-check
6149 // a few things.
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006150 auto entryIt = std::find_if(connection->waitQueue.begin(), connection->waitQueue.end(),
6151 [seq](auto& e) { return e->seq == seq; });
6152 if (entryIt != connection->waitQueue.end()) {
6153 std::unique_ptr<DispatchEntry> dispatchEntry = std::move(*entryIt);
6154 connection->waitQueue.erase(entryIt);
6155
Prabir Pradhancef936d2021-07-21 16:17:52 +00006156 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
6157 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
6158 if (!connection->responsive) {
6159 connection->responsive = isConnectionResponsive(*connection);
6160 if (connection->responsive) {
6161 // The connection was unresponsive, and now it's responsive.
6162 processConnectionResponsiveLocked(*connection);
6163 }
6164 }
6165 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006166 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006167 connection->outboundQueue.emplace_front(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006168 traceOutboundQueueLength(*connection);
6169 } else {
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006170 releaseDispatchEntry(std::move(dispatchEntry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00006171 }
6172 }
6173
6174 // Start the next dispatch cycle for this connection.
6175 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006176}
6177
Prabir Pradhancef936d2021-07-21 16:17:52 +00006178void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6179 const sp<IBinder>& newToken) {
6180 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6181 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006182 mPolicy.notifyFocusChanged(oldToken, newToken);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006183 };
6184 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006185}
6186
Prabir Pradhancef936d2021-07-21 16:17:52 +00006187void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6188 auto command = [this, token, x, y]() REQUIRES(mLock) {
6189 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006190 mPolicy.notifyDropWindow(token, x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006191 };
6192 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006193}
6194
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006195void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006196 if (connection == nullptr) {
6197 LOG_ALWAYS_FATAL("Caller must check for nullness");
6198 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006199 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6200 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006201 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006202 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006203 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006204 return;
6205 }
6206 /**
6207 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6208 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6209 * has changed. This could cause newer entries to time out before the already dispatched
6210 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6211 * processes the events linearly. So providing information about the oldest entry seems to be
6212 * most useful.
6213 */
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006214 DispatchEntry& oldestEntry = *connection->waitQueue.front();
6215 const nsecs_t currentWait = now() - oldestEntry.deliveryTime;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006216 std::string reason =
6217 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006218 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006219 ns2ms(currentWait),
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006220 oldestEntry.eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006221 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006222 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006223
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006224 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6225
6226 // Stop waking up for events on this connection, it is already unresponsive
6227 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006228}
6229
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006230void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6231 std::string reason =
6232 StringPrintf("%s does not have a focused window", application->getName().c_str());
6233 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006234
Yabin Cui8eb9c552023-06-08 18:05:07 +00006235 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006236 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006237 mPolicy.notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006238 };
6239 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006240}
6241
chaviw98318de2021-05-19 16:45:23 -05006242void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006243 const std::string& reason) {
6244 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6245 updateLastAnrStateLocked(windowLabel, reason);
6246}
6247
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006248void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6249 const std::string& reason) {
6250 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006251 updateLastAnrStateLocked(windowLabel, reason);
6252}
6253
6254void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6255 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006257 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006258 struct tm tm;
6259 localtime_r(&t, &tm);
6260 char timestr[64];
6261 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006262 mLastAnrState.clear();
6263 mLastAnrState += INDENT "ANR:\n";
6264 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006265 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6266 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006267 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006268}
6269
Prabir Pradhancef936d2021-07-21 16:17:52 +00006270void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6271 KeyEntry& entry) {
6272 const KeyEvent event = createKeyEvent(entry);
6273 nsecs_t delay = 0;
6274 { // release lock
6275 scoped_unlock unlock(mLock);
6276 android::base::Timer t;
Prabir Pradhana41d2442023-04-20 21:30:40 +00006277 delay = mPolicy.interceptKeyBeforeDispatching(focusedWindowToken, event, entry.policyFlags);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006278 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6279 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6280 std::to_string(t.duration().count()).c_str());
6281 }
6282 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006283
6284 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006285 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006286 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006287 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006288 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006289 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006290 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006291 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006292}
6293
Prabir Pradhancef936d2021-07-21 16:17:52 +00006294void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006295 std::optional<gui::Pid> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006296 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00006297 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006298 scoped_unlock unlock(mLock);
Yabin Cuiced952f2023-06-09 21:12:51 +00006299 mPolicy.notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006300 };
6301 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006302}
6303
Prabir Pradhanedd96402022-02-15 01:46:16 -08006304void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006305 std::optional<gui::Pid> pid) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006306 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006307 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006308 mPolicy.notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006309 };
6310 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006311}
6312
6313/**
6314 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6315 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6316 * command entry to the command queue.
6317 */
6318void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6319 std::string reason) {
6320 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006321 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006322 if (connection.monitor) {
6323 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6324 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006325 pid = findMonitorPidByTokenLocked(connectionToken);
6326 } else {
6327 // The connection is a window
6328 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6329 reason.c_str());
6330 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6331 if (handle != nullptr) {
6332 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006333 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006334 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006335 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006336}
6337
6338/**
6339 * Tell the policy that a connection has become responsive so that it can stop ANR.
6340 */
6341void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6342 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanaeebeb42023-06-13 19:53:03 +00006343 std::optional<gui::Pid> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006344 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006345 pid = findMonitorPidByTokenLocked(connectionToken);
6346 } else {
6347 // The connection is a window
6348 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6349 if (handle != nullptr) {
6350 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006351 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006352 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006353 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006354}
6355
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006356bool InputDispatcher::afterKeyEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006357 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006358 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006359 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006360 if (!handled) {
6361 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006362 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006363 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006364 return false;
6365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006366
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006367 // Get the fallback key state.
6368 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006369 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006370 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006371 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006372 connection->inputState.removeFallbackKey(originalKeyCode);
6373 }
6374
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006375 if (handled || !dispatchEntry.hasForegroundTarget()) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006376 // If the application handles the original key for which we previously
6377 // generated a fallback or if the window is not a foreground window,
6378 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006379 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006380 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006381 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6382 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6383 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6384 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6385 keyEntry.policyFlags);
6386 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006387 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006388 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006389
6390 mLock.unlock();
6391
Prabir Pradhana41d2442023-04-20 21:30:40 +00006392 if (const auto unhandledKeyFallback =
6393 mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6394 event, keyEntry.policyFlags);
6395 unhandledKeyFallback) {
6396 event = *unhandledKeyFallback;
6397 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006398
6399 mLock.lock();
6400
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006401 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006402 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006403 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006404 "application handled the original non-fallback key "
6405 "or is no longer a foreground target, "
6406 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006407 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006408 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006409 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006410 connection->inputState.removeFallbackKey(originalKeyCode);
6411 }
6412 } else {
6413 // If the application did not handle a non-fallback key, first check
6414 // that we are in a good state to perform unhandled key event processing
6415 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006416 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006417 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006418 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6419 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6420 "since this is not an initial down. "
6421 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6422 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6423 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006424 return false;
6425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006426
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006427 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006428 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6429 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6430 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6431 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6432 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006433 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006434
6435 mLock.unlock();
6436
Prabir Pradhana41d2442023-04-20 21:30:40 +00006437 bool fallback = false;
6438 if (auto fb = mPolicy.dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
6439 event, keyEntry.policyFlags);
6440 fb) {
6441 fallback = true;
6442 event = *fb;
6443 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006444
6445 mLock.lock();
6446
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006447 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006448 connection->inputState.removeFallbackKey(originalKeyCode);
6449 return false;
6450 }
6451
6452 // Latch the fallback keycode for this key on an initial down.
6453 // The fallback keycode cannot change at any other point in the lifecycle.
6454 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006455 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006456 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006457 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006458 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006459 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006460 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006461 }
6462
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006463 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006464
6465 // Cancel the fallback key if the policy decides not to send it anymore.
6466 // We will continue to dispatch the key to the policy but we will no
6467 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006468 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6469 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006470 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6471 if (fallback) {
6472 ALOGD("Unhandled key event: Policy requested to send key %d"
6473 "as a fallback for %d, but on the DOWN it had requested "
6474 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006475 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006476 } else {
6477 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6478 "but on the DOWN it had requested to send %d. "
6479 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006480 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006481 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006482 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006483
Michael Wrightfb04fd52022-11-24 22:31:11 +00006484 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006485 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006486 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006487 synthesizeCancelationEventsForConnectionLocked(connection, options);
6488
6489 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006490 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006491 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006492 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006493 }
6494 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006495
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006496 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6497 {
6498 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006499 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006500 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006501 for (const auto& [key, value] : fallbackKeys) {
6502 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006503 }
6504 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6505 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006506 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006507 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006508
6509 if (fallback) {
6510 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006511 keyEntry.eventTime = event.getEventTime();
6512 keyEntry.deviceId = event.getDeviceId();
6513 keyEntry.source = event.getSource();
6514 keyEntry.displayId = event.getDisplayId();
6515 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006516 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006517 keyEntry.scanCode = event.getScanCode();
6518 keyEntry.metaState = event.getMetaState();
6519 keyEntry.repeatCount = event.getRepeatCount();
6520 keyEntry.downTime = event.getDownTime();
6521 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006522
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006523 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6524 ALOGD("Unhandled key event: Dispatching fallback key. "
6525 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006526 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006527 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006528 return true; // restart the event
6529 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006530 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6531 ALOGD("Unhandled key event: No fallback key.");
6532 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006533
6534 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006535 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006536 }
6537 }
6538 return false;
6539}
6540
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006541bool InputDispatcher::afterMotionEventLockedInterruptable(
Prabir Pradhan8c90d782023-09-15 21:16:44 +00006542 const std::shared_ptr<Connection>& connection, DispatchEntry& dispatchEntry,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006543 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006544 return false;
6545}
6546
Michael Wrightd02c5b62014-02-10 15:10:22 -08006547void InputDispatcher::traceInboundQueueLengthLocked() {
6548 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006549 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006550 }
6551}
6552
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006553void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006554 if (ATRACE_ENABLED()) {
6555 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006556 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6557 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006558 }
6559}
6560
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006561void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006562 if (ATRACE_ENABLED()) {
6563 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006564 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6565 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006566 }
6567}
6568
Siarhei Vishniakou5e20f272023-06-08 17:24:44 -07006569void InputDispatcher::dump(std::string& dump) const {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006570 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006571
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006572 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006573 dumpDispatchStateLocked(dump);
6574
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006575 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006576 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006577 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006578 }
6579}
6580
6581void InputDispatcher::monitor() {
6582 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006583 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006584 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006585 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006586}
6587
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006588/**
6589 * Wake up the dispatcher and wait until it processes all events and commands.
6590 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6591 * this method can be safely called from any thread, as long as you've ensured that
6592 * the work you are interested in completing has already been queued.
6593 */
Siarhei Vishniakoua66d65e2023-06-16 10:32:51 -07006594bool InputDispatcher::waitForIdle() const {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006595 /**
6596 * Timeout should represent the longest possible time that a device might spend processing
6597 * events and commands.
6598 */
6599 constexpr std::chrono::duration TIMEOUT = 100ms;
6600 std::unique_lock lock(mLock);
6601 mLooper->wake();
6602 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6603 return result == std::cv_status::no_timeout;
6604}
6605
Vishnu Naire798b472020-07-23 13:52:21 -07006606/**
6607 * Sets focus to the window identified by the token. This must be called
6608 * after updating any input window handles.
6609 *
6610 * Params:
6611 * request.token - input channel token used to identify the window that should gain focus.
6612 * request.focusedToken - the token that the caller expects currently to be focused. If the
6613 * specified token does not match the currently focused window, this request will be dropped.
6614 * If the specified focused token matches the currently focused window, the call will succeed.
6615 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6616 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6617 * when requesting the focus change. This determines which request gets
6618 * precedence if there is a focus change request from another source such as pointer down.
6619 */
Vishnu Nair958da932020-08-21 17:12:37 -07006620void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6621 { // acquire lock
6622 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006623 std::optional<FocusResolver::FocusChanges> changes =
6624 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6625 if (changes) {
6626 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006627 }
6628 } // release lock
6629 // Wake up poll loop since it may need to make new input dispatching choices.
6630 mLooper->wake();
6631}
6632
Vishnu Nairc519ff72021-01-21 08:23:08 -08006633void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6634 if (changes.oldFocus) {
6635 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006636 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006637 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006638 "focus left window");
6639 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006640 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006641 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006642 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006643 if (changes.newFocus) {
Siarhei Vishniakouc033dfb2023-10-03 10:45:16 -07006644 resetNoFocusedWindowTimeoutLocked();
Harry Cutts33476232023-01-30 19:57:29 +00006645 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006646 }
6647
Prabir Pradhan99987712020-11-10 18:43:05 -08006648 // If a window has pointer capture, then it must have focus. We need to ensure that this
6649 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6650 // If the window loses focus before it loses pointer capture, then the window can be in a state
6651 // where it has pointer capture but not focus, violating the contract. Therefore we must
6652 // dispatch the pointer capture event before the focus event. Since focus events are added to
6653 // the front of the queue (above), we add the pointer capture event to the front of the queue
6654 // after the focus events are added. This ensures the pointer capture event ends up at the
6655 // front.
6656 disablePointerCaptureForcedLocked();
6657
Vishnu Nairc519ff72021-01-21 08:23:08 -08006658 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006659 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006660 }
6661}
Vishnu Nair958da932020-08-21 17:12:37 -07006662
Prabir Pradhan99987712020-11-10 18:43:05 -08006663void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006664 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006665 return;
6666 }
6667
6668 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6669
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006670 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006671 setPointerCaptureLocked(false);
6672 }
6673
6674 if (!mWindowTokenWithPointerCapture) {
6675 // No need to send capture changes because no window has capture.
6676 return;
6677 }
6678
6679 if (mPendingEvent != nullptr) {
6680 // Move the pending event to the front of the queue. This will give the chance
6681 // for the pending event to be dropped if it is a captured event.
6682 mInboundQueue.push_front(mPendingEvent);
6683 mPendingEvent = nullptr;
6684 }
6685
6686 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006687 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006688 mInboundQueue.push_front(std::move(entry));
6689}
6690
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006691void InputDispatcher::setPointerCaptureLocked(bool enable) {
6692 mCurrentPointerCaptureRequest.enable = enable;
6693 mCurrentPointerCaptureRequest.seq++;
6694 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006695 scoped_unlock unlock(mLock);
Prabir Pradhana41d2442023-04-20 21:30:40 +00006696 mPolicy.setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006697 };
6698 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006699}
6700
Vishnu Nair599f1412021-06-21 10:39:58 -07006701void InputDispatcher::displayRemoved(int32_t displayId) {
6702 { // acquire lock
6703 std::scoped_lock _l(mLock);
6704 // Set an empty list to remove all handles from the specific display.
Harry Cutts101ee9b2023-07-06 18:04:14 +00006705 setInputWindowsLocked(/*windowInfoHandles=*/{}, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006706 setFocusedApplicationLocked(displayId, nullptr);
6707 // Call focus resolver to clean up stale requests. This must be called after input windows
6708 // have been removed for the removed display.
6709 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006710 // Reset pointer capture eligibility, regardless of previous state.
6711 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006712 // Remove the associated touch mode state.
6713 mTouchModePerDisplay.erase(displayId);
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -07006714 mVerifiersByDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006715 } // release lock
6716
6717 // Wake up poll loop since it may need to make new input dispatching choices.
6718 mLooper->wake();
6719}
6720
Patrick Williamsd828f302023-04-28 17:52:08 -05006721void InputDispatcher::onWindowInfosChanged(const gui::WindowInfosUpdate& update) {
chaviw15fab6f2021-06-07 14:15:52 -05006722 // The listener sends the windows as a flattened array. Separate the windows by display for
6723 // more convenient parsing.
6724 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
Patrick Williamsd828f302023-04-28 17:52:08 -05006725 for (const auto& info : update.windowInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006726 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006727 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006728 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006729
6730 { // acquire lock
6731 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006732
6733 // Ensure that we have an entry created for all existing displays so that if a displayId has
6734 // no windows, we can tell that the windows were removed from the display.
6735 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6736 handlesPerDisplay[displayId];
6737 }
6738
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006739 mDisplayInfos.clear();
Patrick Williamsd828f302023-04-28 17:52:08 -05006740 for (const auto& displayInfo : update.displayInfos) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006741 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6742 }
6743
6744 for (const auto& [displayId, handles] : handlesPerDisplay) {
6745 setInputWindowsLocked(handles, displayId);
6746 }
Patrick Williams9464b2c2023-05-23 11:22:04 -05006747
6748 if (update.vsyncId < mWindowInfosVsyncId) {
6749 ALOGE("Received out of order window infos update. Last update vsync id: %" PRId64
6750 ", current update vsync id: %" PRId64,
6751 mWindowInfosVsyncId, update.vsyncId);
6752 }
6753 mWindowInfosVsyncId = update.vsyncId;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006754 }
6755 // Wake up poll loop since it may need to make new input dispatching choices.
6756 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006757}
6758
Vishnu Nair062a8672021-09-03 16:07:44 -07006759bool InputDispatcher::shouldDropInput(
6760 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006761 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6762 (windowHandle->getInfo()->inputConfig.test(
6763 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006764 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006765 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6766 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006767 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006768 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006769 windowHandle->getInfo()->displayId);
6770 return true;
6771 }
6772 return false;
6773}
6774
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006775void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
Patrick Williamsd828f302023-04-28 17:52:08 -05006776 const gui::WindowInfosUpdate& update) {
6777 mDispatcher.onWindowInfosChanged(update);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006778}
6779
Arthur Hungdfd528e2021-12-08 13:23:04 +00006780void InputDispatcher::cancelCurrentTouch() {
6781 {
6782 std::scoped_lock _l(mLock);
6783 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006784 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006785 "cancel current touch");
6786 synthesizeCancelationEventsForAllConnectionsLocked(options);
6787
6788 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006789 }
6790 // Wake up poll loop since there might be work to do.
6791 mLooper->wake();
6792}
6793
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006794void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6795 std::scoped_lock _l(mLock);
6796 mMonitorDispatchingTimeout = timeout;
6797}
6798
Arthur Hungc539dbb2022-12-08 07:45:36 +00006799void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6800 const sp<WindowInfoHandle>& oldWindowHandle,
6801 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006802 TouchState& state, int32_t deviceId, int32_t pointerId,
Siarhei Vishniakoubf880522023-05-01 11:03:22 -07006803 std::vector<InputTarget>& targets) const {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006804 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6805 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006806 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6807 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6808 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6809 newWindowHandle->getInfo()->inputConfig.test(
6810 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6811 const sp<WindowInfoHandle> oldWallpaper =
6812 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6813 const sp<WindowInfoHandle> newWallpaper =
6814 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6815 if (oldWallpaper == newWallpaper) {
6816 return;
6817 }
6818
6819 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006820 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6821 addWindowTargetLocked(oldWallpaper,
6822 oldTouchedWindow.targetFlags |
6823 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006824 pointerIds, oldTouchedWindow.getDownTimeInTarget(deviceId), targets);
6825 state.removeTouchingPointerFromWindow(deviceId, pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006826 }
6827
6828 if (newWallpaper != nullptr) {
6829 state.addOrUpdateWindow(newWallpaper,
6830 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6831 InputTarget::Flags::WINDOW_IS_OBSCURED |
6832 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006833 deviceId, pointerIds);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006834 }
6835}
6836
6837void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6838 ftl::Flags<InputTarget::Flags> newTargetFlags,
6839 const sp<WindowInfoHandle> fromWindowHandle,
6840 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006841 TouchState& state, int32_t deviceId,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006842 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006843 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6844 fromWindowHandle->getInfo()->inputConfig.test(
6845 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6846 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6847 toWindowHandle->getInfo()->inputConfig.test(
6848 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6849
6850 const sp<WindowInfoHandle> oldWallpaper =
6851 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6852 const sp<WindowInfoHandle> newWallpaper =
6853 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6854 if (oldWallpaper == newWallpaper) {
6855 return;
6856 }
6857
6858 if (oldWallpaper != nullptr) {
6859 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6860 "transferring touch focus to another window");
6861 state.removeWindowByToken(oldWallpaper->getToken());
6862 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6863 }
6864
6865 if (newWallpaper != nullptr) {
6866 nsecs_t downTimeInTarget = now();
6867 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6868 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6869 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6870 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Siarhei Vishniakou0836a302023-05-03 13:54:30 -07006871 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, deviceId, pointerIds,
6872 downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006873 std::shared_ptr<Connection> wallpaperConnection =
6874 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006875 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006876 std::shared_ptr<Connection> toConnection =
6877 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006878 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6879 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6880 wallpaperFlags);
6881 }
6882 }
6883}
6884
6885sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6886 const sp<WindowInfoHandle>& windowHandle) const {
6887 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6888 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6889 bool foundWindow = false;
6890 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6891 if (!foundWindow && otherHandle != windowHandle) {
6892 continue;
6893 }
6894 if (windowHandle == otherHandle) {
6895 foundWindow = true;
6896 continue;
6897 }
6898
6899 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6900 return otherHandle;
6901 }
6902 }
6903 return nullptr;
6904}
6905
Nergi Rahardi730cf3c2023-04-13 12:41:17 +09006906void InputDispatcher::setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
6907 std::scoped_lock _l(mLock);
6908
6909 mConfig.keyRepeatTimeout = timeout;
6910 mConfig.keyRepeatDelay = delay;
6911}
6912
Garfield Tane84e6f92019-08-29 17:28:41 -07006913} // namespace android::inputdispatcher