blob: 97b57b4dd9471e513fab5b48df55af72912bd785 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
Michael Wright2b3c3302018-03-02 17:19:13 +000022#include <android-base/chrono_utils.h>
Siarhei Vishniakoud010b012023-01-18 15:00:53 -080023#include <android-base/logging.h>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080024#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080025#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050026#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070027#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080028#include <ftl/enum.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070029#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050030#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070031#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080032#include <input/InputDevice.h>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080033#include <input/PrintTools.h>
tyiu1573a672023-02-21 22:38:32 +000034#include <openssl/mem.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070035#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010036#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070037#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080038
Michael Wright44753b12020-07-08 13:48:11 +010039#include <cerrno>
40#include <cinttypes>
41#include <climits>
42#include <cstddef>
43#include <ctime>
44#include <queue>
45#include <sstream>
46
47#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000048#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070049#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010050
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#define INDENT " "
52#define INDENT2 " "
53#define INDENT3 " "
54#define INDENT4 " "
55
Siarhei Vishniakou253f4642022-11-09 13:42:06 -080056using namespace android::ftl::flag_operators;
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080057using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000058using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080059using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070060using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050061using android::gui::FocusRequest;
62using android::gui::TouchOcclusionMode;
63using android::gui::WindowInfo;
64using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080065using android::os::InputEventInjectionResult;
66using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067
Garfield Tane84e6f92019-08-29 17:28:41 -070068namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
Prabir Pradhancef936d2021-07-21 16:17:52 +000070namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000071// Temporarily releases a held mutex for the lifetime of the instance.
72// Named to match std::scoped_lock
73class scoped_unlock {
74public:
75 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
76 ~scoped_unlock() { mMutex.lock(); }
77
78private:
79 std::mutex& mMutex;
80};
81
Michael Wrightd02c5b62014-02-10 15:10:22 -080082// Default input dispatching timeout if there is no focused application or paused window
83// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080084const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
85 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
86 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow for all pending events to be processed when an app switch
89// key is on the way. This is used to preempt input dispatch and drop input events
90// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000091constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080093const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080094
Michael Wrightd02c5b62014-02-10 15:10:22 -080095// 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 +000096constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
97
98// Log a warning when an interception call takes longer than this to process.
99constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700101// Additional key latency in case a connection is still processing some motion events.
102// This will help with the case when a user touched a button that opens a new window,
103// and gives us the chance to dispatch the key to this new window.
104constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
105
Michael Wrightd02c5b62014-02-10 15:10:22 -0800106// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000107constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
108
Antonio Kantekea47acb2021-12-23 12:41:25 -0800109// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000110constexpr int LOGTAG_INPUT_INTERACTION = 62000;
111constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000112constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000113
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000114const ui::Transform kIdentityTransform;
115
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000116inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117 return systemTime(SYSTEM_TIME_MONOTONIC);
118}
119
Siarhei Vishniakou63b63612023-04-12 11:00:23 -0700120inline const std::string binderToString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000121 if (binder == nullptr) {
122 return "<null>";
123 }
124 return StringPrintf("%p", binder.get());
125}
126
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000127inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700128 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
129 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130}
131
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000132bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700134 case AKEY_EVENT_ACTION_DOWN:
135 case AKEY_EVENT_ACTION_UP:
136 return true;
137 default:
138 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 }
140}
141
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000142bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 ALOGE("Key event has invalid action code 0x%x", action);
145 return false;
146 }
147 return true;
148}
149
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000150bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800151 switch (MotionEvent::getActionMasked(action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700152 case AMOTION_EVENT_ACTION_DOWN:
153 case AMOTION_EVENT_ACTION_UP:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800154 return pointerCount == 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700155 case AMOTION_EVENT_ACTION_MOVE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700156 case AMOTION_EVENT_ACTION_HOVER_ENTER:
157 case AMOTION_EVENT_ACTION_HOVER_MOVE:
158 case AMOTION_EVENT_ACTION_HOVER_EXIT:
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800159 return pointerCount >= 1;
160 case AMOTION_EVENT_ACTION_CANCEL:
161 case AMOTION_EVENT_ACTION_OUTSIDE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700162 case AMOTION_EVENT_ACTION_SCROLL:
163 return true;
164 case AMOTION_EVENT_ACTION_POINTER_DOWN:
165 case AMOTION_EVENT_ACTION_POINTER_UP: {
Siarhei Vishniakou2f61bdc2022-12-02 08:55:51 -0800166 const int32_t index = MotionEvent::getActionIndex(action);
167 return index >= 0 && index < pointerCount && pointerCount > 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700168 }
169 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
170 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
171 return actionButton != 0;
172 default:
173 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800174 }
175}
176
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000177int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500178 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
179}
180
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000181bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
182 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700183 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 ALOGE("Motion event has invalid action code 0x%x", action);
185 return false;
186 }
187 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800188 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700189 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190 return false;
191 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800192 std::bitset<MAX_POINTER_ID + 1> pointerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 for (size_t i = 0; i < pointerCount; i++) {
194 int32_t id = pointerProperties[i].id;
195 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700196 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
197 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800198 return false;
199 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800200 if (pointerIdBits.test(id)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 ALOGE("Motion event has duplicate pointer id %d", id);
202 return false;
203 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800204 pointerIdBits.set(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800205 }
206 return true;
207}
208
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000209std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000211 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 }
213
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000214 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 bool first = true;
216 Region::const_iterator cur = region.begin();
217 Region::const_iterator const tail = region.end();
218 while (cur != tail) {
219 if (first) {
220 first = false;
221 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800222 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800224 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800225 cur++;
226 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000227 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228}
229
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000230std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500231 constexpr size_t maxEntries = 50; // max events to print
232 constexpr size_t skipBegin = maxEntries / 2;
233 const size_t skipEnd = queue.size() - maxEntries / 2;
234 // skip from maxEntries / 2 ... size() - maxEntries/2
235 // only print from 0 .. skipBegin and then from skipEnd .. size()
236
237 std::string dump;
238 for (size_t i = 0; i < queue.size(); i++) {
239 const DispatchEntry& entry = *queue[i];
240 if (i >= skipBegin && i < skipEnd) {
241 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
242 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
243 continue;
244 }
245 dump.append(INDENT4);
246 dump += entry.eventEntry->getDescription();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800247 dump += StringPrintf(", seq=%" PRIu32 ", targetFlags=%s, resolvedAction=%d, age=%" PRId64
248 "ms",
249 entry.seq, entry.targetFlags.string().c_str(), entry.resolvedAction,
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500250 ns2ms(currentTime - entry.eventEntry->eventTime));
251 if (entry.deliveryTime != 0) {
252 // This entry was delivered, so add information on how long we've been waiting
253 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
254 }
255 dump.append("\n");
256 }
257 return dump;
258}
259
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700260/**
261 * Find the entry in std::unordered_map by key, and return it.
262 * If the entry is not found, return a default constructed entry.
263 *
264 * Useful when the entries are vectors, since an empty vector will be returned
265 * if the entry is not found.
266 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
267 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700268template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000269V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700270 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700271 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800272}
273
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000274bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700275 if (first == second) {
276 return true;
277 }
278
279 if (first == nullptr || second == nullptr) {
280 return false;
281 }
282
283 return first->getToken() == second->getToken();
284}
285
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000286bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000287 if (first == nullptr || second == nullptr) {
288 return false;
289 }
290 return first->applicationInfo.token != nullptr &&
291 first->applicationInfo.token == second->applicationInfo.token;
292}
293
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800294template <typename T>
295size_t firstMarkedBit(T set) {
296 // TODO: replace with std::countr_zero from <bit> when that's available
297 LOG_ALWAYS_FATAL_IF(set.none());
298 size_t i = 0;
299 while (!set.test(i)) {
300 i++;
301 }
302 return i;
303}
304
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800305std::unique_ptr<DispatchEntry> createDispatchEntry(
306 const InputTarget& inputTarget, std::shared_ptr<EventEntry> eventEntry,
307 ftl::Flags<InputTarget::Flags> inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700308 if (inputTarget.useDefaultPointerTransform()) {
309 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700310 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700311 inputTarget.displayTransform,
312 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000313 }
314
315 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
316 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
317
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700318 std::vector<PointerCoords> pointerCoords;
319 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000320
321 // Use the first pointer information to normalize all other pointers. This could be any pointer
322 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700323 // uses the transform for the normalized pointer.
324 const ui::Transform& firstPointerTransform =
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800325 inputTarget.pointerTransforms[firstMarkedBit(inputTarget.pointerIds)];
chaviw1ff3d1e2020-07-01 15:53:47 -0700326 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000327
328 // Iterate through all pointers in the event to normalize against the first.
329 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
330 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
331 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700332 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000333
334 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700335 // First, apply the current pointer's transform to update the coordinates into
336 // window space.
337 pointerCoords[pointerIndex].transform(currTransform);
338 // Next, apply the inverse transform of the normalized coordinates so the
339 // current coordinates are transformed into the normalized coordinate space.
340 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000341 }
342
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700343 std::unique_ptr<MotionEntry> combinedMotionEntry =
344 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
345 motionEntry.deviceId, motionEntry.source,
346 motionEntry.displayId, motionEntry.policyFlags,
347 motionEntry.action, motionEntry.actionButton,
348 motionEntry.flags, motionEntry.metaState,
349 motionEntry.buttonState, motionEntry.classification,
350 motionEntry.edgeFlags, motionEntry.xPrecision,
351 motionEntry.yPrecision, motionEntry.xCursorPosition,
352 motionEntry.yCursorPosition, motionEntry.downTime,
353 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000354 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000355
356 if (motionEntry.injectionState) {
357 combinedMotionEntry->injectionState = motionEntry.injectionState;
358 combinedMotionEntry->injectionState->refCount += 1;
359 }
360
361 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700362 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700363 firstPointerTransform, inputTarget.displayTransform,
364 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000365 return dispatchEntry;
366}
367
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000368status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
369 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700370 std::unique_ptr<InputChannel> uniqueServerChannel;
371 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
372
373 serverChannel = std::move(uniqueServerChannel);
374 return result;
375}
376
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500377template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000378bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500379 if (lhs == nullptr && rhs == nullptr) {
380 return true;
381 }
382 if (lhs == nullptr || rhs == nullptr) {
383 return false;
384 }
385 return *lhs == *rhs;
386}
387
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000388KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000389 KeyEvent event;
390 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
391 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
392 entry.repeatCount, entry.downTime, entry.eventTime);
393 return event;
394}
395
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000396bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000397 // Do not keep track of gesture monitors. They receive every event and would disproportionately
398 // affect the statistics.
399 if (connection.monitor) {
400 return false;
401 }
402 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
403 if (!connection.responsive) {
404 return false;
405 }
406 return true;
407}
408
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000409bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000410 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
411 const int32_t& inputEventId = eventEntry.id;
412 if (inputEventId != dispatchEntry.resolvedEventId) {
413 // Event was transmuted
414 return false;
415 }
416 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
417 return false;
418 }
419 // Only track latency for events that originated from hardware
420 if (eventEntry.isSynthesized()) {
421 return false;
422 }
423 const EventEntry::Type& inputEventEntryType = eventEntry.type;
424 if (inputEventEntryType == EventEntry::Type::KEY) {
425 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
426 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
427 return false;
428 }
429 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
430 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
431 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
432 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
433 return false;
434 }
435 } else {
436 // Not a key or a motion
437 return false;
438 }
439 if (!shouldReportMetricsForConnection(connection)) {
440 return false;
441 }
442 return true;
443}
444
Prabir Pradhancef936d2021-07-21 16:17:52 +0000445/**
446 * Connection is responsive if it has no events in the waitQueue that are older than the
447 * current time.
448 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000449bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000450 const nsecs_t currentTime = now();
451 for (const DispatchEntry* entry : connection.waitQueue) {
452 if (entry->timeoutTime < currentTime) {
453 return false;
454 }
455 }
456 return true;
457}
458
Antonio Kantekf16f2832021-09-28 04:39:20 +0000459// Returns true if the event type passed as argument represents a user activity.
460bool isUserActivityEvent(const EventEntry& eventEntry) {
461 switch (eventEntry.type) {
462 case EventEntry::Type::FOCUS:
463 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
464 case EventEntry::Type::DRAG:
465 case EventEntry::Type::TOUCH_MODE_CHANGED:
466 case EventEntry::Type::SENSOR:
467 case EventEntry::Type::CONFIGURATION_CHANGED:
468 return false;
469 case EventEntry::Type::DEVICE_RESET:
470 case EventEntry::Type::KEY:
471 case EventEntry::Type::MOTION:
472 return true;
473 }
474}
475
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800476// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000477bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000478 bool isStylus, const ui::Transform& displayTransform) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800479 const auto inputConfig = windowInfo.inputConfig;
480 if (windowInfo.displayId != displayId ||
481 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800482 return false;
483 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700484 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800485 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800486 return false;
487 }
Prabir Pradhan33e3baa2022-12-06 20:30:22 +0000488
489 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
490 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
491 // the window. Points on the right and bottom edges should not be inside the window, so we need
492 // to be careful about performing a hit test when the display is rotated, since the "right" and
493 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
494 // logical display in which WM determined the bounds. Perform the hit test in the logical
495 // display space to ensure these edges are considered correctly in all orientations.
496 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
497 const auto p = displayTransform.transform(x, y);
498 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800499 return false;
500 }
501 return true;
502}
503
Prabir Pradhand65552b2021-10-07 11:23:50 -0700504bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
505 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000506 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700507}
508
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800509// Determines if the given window can be targeted as InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000510// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
511// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
512// be sent to such a window, but it is not a foreground event and doesn't use
Siarhei Vishniakou253f4642022-11-09 13:42:06 -0800513// InputTarget::Flags::FOREGROUND.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000514bool canReceiveForegroundTouches(const WindowInfo& info) {
515 // A non-touchable window can still receive touch events (e.g. in the case of
516 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
517 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
518}
519
Antonio Kantek48710e42022-03-24 14:19:30 -0700520bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
521 if (windowHandle == nullptr) {
522 return false;
523 }
524 const WindowInfo* windowInfo = windowHandle->getInfo();
525 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
526 return true;
527 }
528 return false;
529}
530
Prabir Pradhan5735a322022-04-11 17:23:34 +0000531// Checks targeted injection using the window's owner's uid.
532// Returns an empty string if an entry can be sent to the given window, or an error message if the
533// entry is a targeted injection whose uid target doesn't match the window owner.
534std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
535 const EventEntry& entry) {
536 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
537 // The event was not injected, or the injected event does not target a window.
538 return {};
539 }
540 const int32_t uid = *entry.injectionState->targetUid;
541 if (window == nullptr) {
542 return StringPrintf("No valid window target for injection into uid %d.", uid);
543 }
544 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
545 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
546 "owned by uid %d.",
547 uid, window->getName().c_str(), window->getInfo()->ownerUid);
548 }
549 return {};
550}
551
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000552std::pair<float, float> resolveTouchedPosition(const MotionEntry& entry) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700553 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
554 // Always dispatch mouse events to cursor position.
555 if (isFromMouse) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000556 return {entry.xCursorPosition, entry.yCursorPosition};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700557 }
558
559 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
Prabir Pradhan82e081e2022-12-06 09:50:09 +0000560 return {entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X),
561 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)};
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700562}
563
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700564std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
565 if (eventEntry.type == EventEntry::Type::KEY) {
566 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
567 return keyEntry.downTime;
568 } else if (eventEntry.type == EventEntry::Type::MOTION) {
569 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
570 return motionEntry.downTime;
571 }
572 return std::nullopt;
573}
574
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000575/**
576 * Compare the old touch state to the new touch state, and generate the corresponding touched
577 * windows (== input targets).
578 * If a window had the hovering pointer, but now it doesn't, produce HOVER_EXIT for that window.
579 * If the pointer just entered the new window, produce HOVER_ENTER.
580 * For pointers remaining in the window, produce HOVER_MOVE.
581 */
582std::vector<TouchedWindow> getHoveringWindowsLocked(const TouchState* oldState,
583 const TouchState& newTouchState,
584 const MotionEntry& entry) {
585 std::vector<TouchedWindow> out;
586 const int32_t maskedAction = MotionEvent::getActionMasked(entry.action);
587 if (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER &&
588 maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE &&
589 maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT) {
590 // Not a hover event - don't need to do anything
591 return out;
592 }
593
594 // We should consider all hovering pointers here. But for now, just use the first one
595 const int32_t pointerId = entry.pointerProperties[0].id;
596
597 std::set<sp<WindowInfoHandle>> oldWindows;
598 if (oldState != nullptr) {
599 oldWindows = oldState->getWindowsWithHoveringPointer(entry.deviceId, pointerId);
600 }
601
602 std::set<sp<WindowInfoHandle>> newWindows =
603 newTouchState.getWindowsWithHoveringPointer(entry.deviceId, pointerId);
604
605 // If the pointer is no longer in the new window set, send HOVER_EXIT.
606 for (const sp<WindowInfoHandle>& oldWindow : oldWindows) {
607 if (newWindows.find(oldWindow) == newWindows.end()) {
608 TouchedWindow touchedWindow;
609 touchedWindow.windowHandle = oldWindow;
610 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_EXIT;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800611 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000612 out.push_back(touchedWindow);
613 }
614 }
615
616 for (const sp<WindowInfoHandle>& newWindow : newWindows) {
617 TouchedWindow touchedWindow;
618 touchedWindow.windowHandle = newWindow;
619 if (oldWindows.find(newWindow) == oldWindows.end()) {
620 // Any windows that have this pointer now, and didn't have it before, should get
621 // HOVER_ENTER
622 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_HOVER_ENTER;
623 } else {
624 // This pointer was already sent to the window. Use ACTION_HOVER_MOVE.
Siarhei Vishniakouc2eb8502023-04-11 18:33:36 -0700625 if (CC_UNLIKELY(maskedAction != AMOTION_EVENT_ACTION_HOVER_MOVE)) {
626 LOG(FATAL) << "Expected ACTION_HOVER_MOVE instead of " << entry.getDescription();
627 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000628 touchedWindow.targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
629 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -0800630 touchedWindow.pointerIds.set(pointerId);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +0000631 if (canReceiveForegroundTouches(*newWindow->getInfo())) {
632 touchedWindow.targetFlags |= InputTarget::Flags::FOREGROUND;
633 }
634 out.push_back(touchedWindow);
635 }
636 return out;
637}
638
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -0800639template <typename T>
640std::vector<T>& operator+=(std::vector<T>& left, const std::vector<T>& right) {
641 left.insert(left.end(), right.begin(), right.end());
642 return left;
643}
644
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000645} // namespace
646
Michael Wrightd02c5b62014-02-10 15:10:22 -0800647// --- InputDispatcher ---
648
Garfield Tan00f511d2019-06-12 16:55:40 -0700649InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800650 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
651
652InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
653 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700654 : mPolicy(policy),
655 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700656 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800657 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700658 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700659 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700660 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800661 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700662 mDispatchEnabled(false),
663 mDispatchFrozen(false),
664 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100665 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000666 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800667 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800668 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000669 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000670 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700671 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800672 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700674 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700675#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700676 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700677#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700678 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679 policy->getDispatcherConfiguration(&mConfig);
680}
681
682InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000683 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684
Prabir Pradhancef936d2021-07-21 16:17:52 +0000685 resetKeyRepeatLocked();
686 releasePendingEventLocked();
687 drainInboundQueueLocked();
688 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000690 while (!mConnectionsByToken.empty()) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700691 std::shared_ptr<Connection> connection = mConnectionsByToken.begin()->second;
Harry Cutts33476232023-01-30 19:57:29 +0000692 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693 }
694}
695
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700696status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700697 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700698 return ALREADY_EXISTS;
699 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700700 mThread = std::make_unique<InputThread>(
701 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
702 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700703}
704
705status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700706 if (mThread && mThread->isCallingThread()) {
707 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700708 return INVALID_OPERATION;
709 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700710 mThread.reset();
711 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700712}
713
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700715 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800717 std::scoped_lock _l(mLock);
718 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719
720 // Run a dispatch loop if there are no pending commands.
721 // The dispatch loop might enqueue commands to run afterwards.
722 if (!haveCommandsLocked()) {
723 dispatchOnceInnerLocked(&nextWakeupTime);
724 }
725
726 // Run all pending commands if there are any.
727 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000728 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700729 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800731
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700732 // If we are still waiting for ack on some events,
733 // we might have to wake up earlier to check if an app is anr'ing.
734 const nsecs_t nextAnrCheck = processAnrsLocked();
735 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
736
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800737 // We are about to enter an infinitely long sleep, because we have no commands or
738 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700739 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800740 mDispatcherEnteredIdle.notify_all();
741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 } // release lock
743
744 // Wait for callback or timeout or wake. (make sure we round up, not down)
745 nsecs_t currentTime = now();
746 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
747 mLooper->pollOnce(timeoutMillis);
748}
749
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700750/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500751 * Raise ANR if there is no focused window.
752 * Before the ANR is raised, do a final state check:
753 * 1. The currently focused application must be the same one we are waiting for.
754 * 2. Ensure we still don't have a focused window.
755 */
756void InputDispatcher::processNoFocusedWindowAnrLocked() {
757 // Check if the application that we are waiting for is still focused.
758 std::shared_ptr<InputApplicationHandle> focusedApplication =
759 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
760 if (focusedApplication == nullptr ||
761 focusedApplication->getApplicationToken() !=
762 mAwaitedFocusedApplication->getApplicationToken()) {
763 // Unexpected because we should have reset the ANR timer when focused application changed
764 ALOGE("Waited for a focused window, but focused application has already changed to %s",
765 focusedApplication->getName().c_str());
766 return; // The focused application has changed.
767 }
768
chaviw98318de2021-05-19 16:45:23 -0500769 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500770 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
771 if (focusedWindowHandle != nullptr) {
772 return; // We now have a focused window. No need for ANR.
773 }
774 onAnrLocked(mAwaitedFocusedApplication);
775}
776
777/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700778 * Check if any of the connections' wait queues have events that are too old.
779 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
780 * Return the time at which we should wake up next.
781 */
782nsecs_t InputDispatcher::processAnrsLocked() {
783 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700784 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700785 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
786 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
787 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500788 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700789 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500790 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700791 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700792 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500793 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700794 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
795 }
796 }
797
798 // Check if any connection ANRs are due
799 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
800 if (currentTime < nextAnrCheck) { // most likely scenario
801 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
802 }
803
804 // If we reached here, we have an unresponsive connection.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700805 std::shared_ptr<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700806 if (connection == nullptr) {
807 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
808 return nextAnrCheck;
809 }
810 connection->responsive = false;
811 // Stop waking up for this unresponsive connection
812 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000813 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700814 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700815}
816
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800817std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -0700818 const std::shared_ptr<Connection>& connection) {
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800819 if (connection->monitor) {
820 return mMonitorDispatchingTimeout;
821 }
822 const sp<WindowInfoHandle> window =
823 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700824 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500825 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700826 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500827 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700828}
829
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
831 nsecs_t currentTime = now();
832
Jeff Browndc5992e2014-04-11 01:27:26 -0700833 // Reset the key repeat timer whenever normal dispatch is suspended while the
834 // device is in a non-interactive state. This is to ensure that we abort a key
835 // repeat if the device is just coming out of sleep.
836 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 resetKeyRepeatLocked();
838 }
839
840 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
841 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100842 if (DEBUG_FOCUS) {
843 ALOGD("Dispatch frozen. Waiting some more.");
844 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 return;
846 }
847
848 // Optimize latency of app switches.
849 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
850 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
851 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
852 if (mAppSwitchDueTime < *nextWakeupTime) {
853 *nextWakeupTime = mAppSwitchDueTime;
854 }
855
856 // Ready to start a new event.
857 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700858 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700859 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 if (isAppSwitchDue) {
861 // The inbound queue is empty so the app switch key we were waiting
862 // for will never arrive. Stop waiting for it.
863 resetPendingAppSwitchLocked(false);
864 isAppSwitchDue = false;
865 }
866
867 // Synthesize a key repeat if appropriate.
868 if (mKeyRepeatState.lastKeyEntry) {
869 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
870 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
871 } else {
872 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
873 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
874 }
875 }
876 }
877
878 // Nothing to do if there is no pending event.
879 if (!mPendingEvent) {
880 return;
881 }
882 } else {
883 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700884 mPendingEvent = mInboundQueue.front();
885 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 traceInboundQueueLengthLocked();
887 }
888
889 // Poke user activity for this event.
890 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700891 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 }
894
895 // Now we have an event to dispatch.
896 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700897 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700899 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700901 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700903 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
905
906 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700907 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 }
909
910 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700911 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700912 const ConfigurationChangedEntry& typedEntry =
913 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700914 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700915 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700916 break;
917 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700919 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700920 const DeviceResetEntry& typedEntry =
921 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700922 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700923 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700924 break;
925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100927 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700928 std::shared_ptr<FocusEntry> typedEntry =
929 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100930 dispatchFocusLocked(currentTime, typedEntry);
931 done = true;
932 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
933 break;
934 }
935
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700936 case EventEntry::Type::TOUCH_MODE_CHANGED: {
937 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
938 dispatchTouchModeChangeLocked(currentTime, typedEntry);
939 done = true;
940 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
941 break;
942 }
943
Prabir Pradhan99987712020-11-10 18:43:05 -0800944 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
945 const auto typedEntry =
946 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
947 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
948 done = true;
949 break;
950 }
951
arthurhungb89ccb02020-12-30 16:19:01 +0800952 case EventEntry::Type::DRAG: {
953 std::shared_ptr<DragEntry> typedEntry =
954 std::static_pointer_cast<DragEntry>(mPendingEvent);
955 dispatchDragLocked(currentTime, typedEntry);
956 done = true;
957 break;
958 }
959
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700960 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700961 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700962 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700963 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700964 resetPendingAppSwitchLocked(true);
965 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700966 } else if (dropReason == DropReason::NOT_DROPPED) {
967 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700968 }
969 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700970 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700971 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700972 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700973 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
974 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700975 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700976 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700977 break;
978 }
979
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700980 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700981 std::shared_ptr<MotionEntry> motionEntry =
982 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700983 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
984 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700986 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700987 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700988 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700989 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
990 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700991 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700992 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700993 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 }
Chris Yef59a2f42020-10-16 12:55:26 -0700995
996 case EventEntry::Type::SENSOR: {
997 std::shared_ptr<SensorEntry> sensorEntry =
998 std::static_pointer_cast<SensorEntry>(mPendingEvent);
999 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
1000 dropReason = DropReason::APP_SWITCH;
1001 }
1002 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
1003 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
1004 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
1005 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
1006 dropReason = DropReason::STALE;
1007 }
1008 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
1009 done = true;
1010 break;
1011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 }
1013
1014 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001015 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001016 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 }
Michael Wright3a981722015-06-10 15:26:13 +01001018 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019
1020 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001021 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022 }
1023}
1024
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08001025bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
1026 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
1027}
1028
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001029/**
1030 * Return true if the events preceding this incoming motion event should be dropped
1031 * Return false otherwise (the default behaviour)
1032 */
1033bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001034 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001035 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001036
1037 // Optimize case where the current application is unresponsive and the user
1038 // decides to touch a window in a different application.
1039 // If the application takes too long to catch up then we drop all events preceding
1040 // the touch into the other window.
1041 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001042 const int32_t displayId = motionEntry.displayId;
1043 const auto [x, y] = resolveTouchedPosition(motionEntry);
Harry Cutts33476232023-01-30 19:57:29 +00001044 const bool isStylus = isPointerFromStylus(motionEntry, /*pointerIndex=*/0);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07001045
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001046 auto [touchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001047 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001048 touchedWindowHandle->getApplicationToken() !=
1049 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001050 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001051 ALOGI("Pruning input queue because user touched a different application while waiting "
1052 "for %s",
1053 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001054 return true;
1055 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001056
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001057 // Alternatively, maybe there's a spy window that could handle this event.
1058 const std::vector<sp<WindowInfoHandle>> touchedSpies =
1059 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
1060 for (const auto& windowHandle : touchedSpies) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001061 const std::shared_ptr<Connection> connection =
1062 getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +00001063 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001064 // This spy window could take more input. Drop all events preceding this
1065 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001066 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001067 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001068 mAwaitedFocusedApplication->getName().c_str());
1069 return true;
1070 }
1071 }
1072 }
1073
1074 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
1075 // yet been processed by some connections, the dispatcher will wait for these motion
1076 // events to be processed before dispatching the key event. This is because these motion events
1077 // may cause a new window to be launched, which the user might expect to receive focus.
1078 // To prevent waiting forever for such events, just send the key to the currently focused window
1079 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
1080 ALOGD("Received a new pointer down event, stop waiting for events to process and "
1081 "just send the pending key event to the focused window.");
1082 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001083 }
1084 return false;
1085}
1086
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001087bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001088 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001089 mInboundQueue.push_back(std::move(newEntry));
1090 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091 traceInboundQueueLengthLocked();
1092
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001093 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001094 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001095 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1096 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001097 // Optimize app switch latency.
1098 // If the application takes too long to catch up then we drop all events preceding
1099 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001100 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001101 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001102 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001103 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001104 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001105 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001106 if (DEBUG_APP_SWITCH) {
1107 ALOGD("App switch is pending!");
1108 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001109 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001110 mAppSwitchSawKeyDown = false;
1111 needWake = true;
1112 }
1113 }
1114 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001115
1116 // If a new up event comes in, and the pending event with same key code has been asked
1117 // to try again later because of the policy. We have to reset the intercept key wake up
1118 // time for it may have been handled in the policy and could be dropped.
1119 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1120 mPendingEvent->type == EventEntry::Type::KEY) {
1121 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1122 if (pendingKey.keyCode == keyEntry.keyCode &&
1123 pendingKey.interceptKeyResult ==
Michael Wright5caf55a2022-11-24 22:31:42 +00001124 KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
1125 pendingKey.interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001126 pendingKey.interceptKeyWakeupTime = 0;
1127 needWake = true;
1128 }
1129 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001130 break;
1131 }
1132
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001133 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001134 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1135 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001136 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1137 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001138 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001140 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001142 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001143 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1144 break;
1145 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001146 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001147 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001148 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001149 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001150 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1151 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001152 // nothing to do
1153 break;
1154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 }
1156
1157 return needWake;
1158}
1159
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001160void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001161 // Do not store sensor event in recent queue to avoid flooding the queue.
1162 if (entry->type != EventEntry::Type::SENSOR) {
1163 mRecentQueue.push_back(entry);
1164 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001165 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001166 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 }
1168}
1169
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001170std::pair<sp<WindowInfoHandle>, std::vector<InputTarget>>
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001171InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y, bool isStylus,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001172 bool ignoreDragWindow) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 // Traverse windows from front to back to find touched window.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001174 std::vector<InputTarget> outsideTargets;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001175 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001176 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001177 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001178 continue;
1179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001181 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001182 if (!info.isSpy() &&
1183 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001184 return {windowHandle, outsideTargets};
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001185 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001186
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001187 if (info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
1188 addWindowTargetLocked(windowHandle, InputTarget::Flags::DISPATCH_AS_OUTSIDE,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001189 /*pointerIds=*/{}, /*firstDownTimeInTarget=*/std::nullopt,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001190 outsideTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 }
1192 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001193 return {nullptr, {}};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194}
1195
Prabir Pradhand65552b2021-10-07 11:23:50 -07001196std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhan82e081e2022-12-06 09:50:09 +00001197 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001198 // Traverse windows from front to back and gather the touched spy windows.
1199 std::vector<sp<WindowInfoHandle>> spyWindows;
1200 const auto& windowHandles = getWindowHandlesLocked(displayId);
1201 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1202 const WindowInfo& info = *windowHandle->getInfo();
1203
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00001204 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001205 continue;
1206 }
1207 if (!info.isSpy()) {
1208 // The first touched non-spy window was found, so return the spy windows touched so far.
1209 return spyWindows;
1210 }
1211 spyWindows.push_back(windowHandle);
1212 }
1213 return spyWindows;
1214}
1215
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001216void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 const char* reason;
1218 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001219 case DropReason::POLICY:
Prabir Pradhan65613802023-02-22 23:36:58 +00001220 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001221 ALOGD("Dropped event because policy consumed it.");
1222 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001223 reason = "inbound event was dropped because the policy consumed it";
1224 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001225 case DropReason::DISABLED:
1226 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001227 ALOGI("Dropped event because input dispatch is disabled.");
1228 }
1229 reason = "inbound event was dropped because input dispatch is disabled";
1230 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001231 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001232 ALOGI("Dropped event because of pending overdue app switch.");
1233 reason = "inbound event was dropped because of pending overdue app switch";
1234 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001235 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001236 ALOGI("Dropped event because the current application is not responding and the user "
1237 "has started interacting with a different application.");
1238 reason = "inbound event was dropped because the current application is not responding "
1239 "and the user has started interacting with a different application";
1240 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001241 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001242 ALOGI("Dropped event because it is stale.");
1243 reason = "inbound event was dropped because it is stale";
1244 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001245 case DropReason::NO_POINTER_CAPTURE:
1246 ALOGI("Dropped event because there is no window with Pointer Capture.");
1247 reason = "inbound event was dropped because there is no window with Pointer Capture";
1248 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001249 case DropReason::NOT_DROPPED: {
1250 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001251 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 }
1254
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001255 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001256 case EventEntry::Type::KEY: {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001257 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001259 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001261 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001262 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1263 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001264 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS, reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001265 synthesizeCancelationEventsForAllConnectionsLocked(options);
1266 } else {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001267 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
1268 reason);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001269 synthesizeCancelationEventsForAllConnectionsLocked(options);
1270 }
1271 break;
1272 }
Chris Yef59a2f42020-10-16 12:55:26 -07001273 case EventEntry::Type::SENSOR: {
1274 break;
1275 }
arthurhungb89ccb02020-12-30 16:19:01 +08001276 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1277 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001278 break;
1279 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001280 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001281 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001282 case EventEntry::Type::CONFIGURATION_CHANGED:
1283 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001284 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001285 break;
1286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287 }
1288}
1289
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001290static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001291 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1292 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293}
1294
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001295bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1296 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1297 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1298 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299}
1300
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07001301bool InputDispatcher::isAppSwitchPendingLocked() const {
Colin Cross5b799302022-10-18 21:52:41 -07001302 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303}
1304
1305void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001306 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001308 if (DEBUG_APP_SWITCH) {
1309 if (handled) {
1310 ALOGD("App switch has arrived.");
1311 } else {
1312 ALOGD("App switch was abandoned.");
1313 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315}
1316
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001318 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319}
1320
Prabir Pradhancef936d2021-07-21 16:17:52 +00001321bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001322 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 return false;
1324 }
1325
1326 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001327 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001328 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001329 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1330 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001331 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 return true;
1333}
1334
Prabir Pradhancef936d2021-07-21 16:17:52 +00001335void InputDispatcher::postCommandLocked(Command&& command) {
1336 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337}
1338
1339void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001340 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001341 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001342 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 releaseInboundEventLocked(entry);
1344 }
1345 traceInboundQueueLengthLocked();
1346}
1347
1348void InputDispatcher::releasePendingEventLocked() {
1349 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001351 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352 }
1353}
1354
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001355void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001357 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001358 if (DEBUG_DISPATCH_CYCLE) {
1359 ALOGD("Injected inbound event was dropped.");
1360 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001361 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 }
1363 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001364 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001365 }
1366 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367}
1368
1369void InputDispatcher::resetKeyRepeatLocked() {
1370 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001371 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 }
1373}
1374
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001375std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1376 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377
Michael Wright2e732952014-09-24 13:26:59 -07001378 uint32_t policyFlags = entry->policyFlags &
1379 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001381 std::shared_ptr<KeyEntry> newEntry =
1382 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1383 entry->source, entry->displayId, policyFlags, entry->action,
1384 entry->flags, entry->keyCode, entry->scanCode,
1385 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001387 newEntry->syntheticRepeat = true;
1388 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001390 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391}
1392
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001393bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001394 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001395 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1396 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1397 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398
1399 // Reset key repeating in case a keyboard device was added or removed or something.
1400 resetKeyRepeatLocked();
1401
1402 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001403 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1404 scoped_unlock unlock(mLock);
1405 mPolicy->notifyConfigurationChanged(eventTime);
1406 };
1407 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 return true;
1409}
1410
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001411bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1412 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001413 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1414 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1415 entry.deviceId);
1416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001417
liushenxiang42232912021-05-21 20:24:09 +08001418 // Reset key repeating in case a keyboard device was disabled or enabled.
1419 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1420 resetKeyRepeatLocked();
1421 }
1422
Michael Wrightfb04fd52022-11-24 22:31:11 +00001423 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001424 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001425 synthesizeCancelationEventsForAllConnectionsLocked(options);
1426 return true;
1427}
1428
Vishnu Nairad321cd2020-08-20 16:40:21 -07001429void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001430 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001431 if (mPendingEvent != nullptr) {
1432 // Move the pending event to the front of the queue. This will give the chance
1433 // for the pending event to get dispatched to the newly focused window
1434 mInboundQueue.push_front(mPendingEvent);
1435 mPendingEvent = nullptr;
1436 }
1437
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001438 std::unique_ptr<FocusEntry> focusEntry =
1439 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1440 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001441
1442 // This event should go to the front of the queue, but behind all other focus events
1443 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001444 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001445 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001446 [](const std::shared_ptr<EventEntry>& event) {
1447 return event->type == EventEntry::Type::FOCUS;
1448 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001449
1450 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001451 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001452}
1453
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001454void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001455 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001456 if (channel == nullptr) {
1457 return; // Window has gone away
1458 }
1459 InputTarget target;
1460 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001461 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001462 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001463 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1464 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001465 std::string reason = std::string("reason=").append(entry->reason);
1466 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001467 dispatchEventLocked(currentTime, entry, {target});
1468}
1469
Prabir Pradhan99987712020-11-10 18:43:05 -08001470void InputDispatcher::dispatchPointerCaptureChangedLocked(
1471 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1472 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001473 dropReason = DropReason::NOT_DROPPED;
1474
Prabir Pradhan99987712020-11-10 18:43:05 -08001475 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001476 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001477
1478 if (entry->pointerCaptureRequest.enable) {
1479 // Enable Pointer Capture.
1480 if (haveWindowWithPointerCapture &&
1481 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001482 // This can happen if pointer capture is disabled and re-enabled before we notify the
1483 // app of the state change, so there is no need to notify the app.
1484 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1485 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001486 }
1487 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001488 // This can happen if a window requests capture and immediately releases capture.
1489 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001490 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001491 return;
1492 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001493 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1494 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1495 return;
1496 }
1497
Vishnu Nairc519ff72021-01-21 08:23:08 -08001498 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001499 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1500 mWindowTokenWithPointerCapture = token;
1501 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001502 // Disable Pointer Capture.
1503 // We do not check if the sequence number matches for requests to disable Pointer Capture
1504 // for two reasons:
1505 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1506 // to disable capture with the same sequence number: one generated by
1507 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1508 // Capture being disabled in InputReader.
1509 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1510 // actual Pointer Capture state that affects events being generated by input devices is
1511 // in InputReader.
1512 if (!haveWindowWithPointerCapture) {
1513 // Pointer capture was already forcefully disabled because of focus change.
1514 dropReason = DropReason::NOT_DROPPED;
1515 return;
1516 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001517 token = mWindowTokenWithPointerCapture;
1518 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001519 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001520 setPointerCaptureLocked(false);
1521 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001522 }
1523
1524 auto channel = getInputChannelLocked(token);
1525 if (channel == nullptr) {
1526 // Window has gone away, clean up Pointer Capture state.
1527 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001528 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001529 setPointerCaptureLocked(false);
1530 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001531 return;
1532 }
1533 InputTarget target;
1534 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001535 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan99987712020-11-10 18:43:05 -08001536 entry->dispatchInProgress = true;
1537 dispatchEventLocked(currentTime, entry, {target});
1538
1539 dropReason = DropReason::NOT_DROPPED;
1540}
1541
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001542void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1543 const std::shared_ptr<TouchModeEntry>& entry) {
1544 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001545 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001546 if (windowHandles.empty()) {
1547 return;
1548 }
1549 const std::vector<InputTarget> inputTargets =
1550 getInputTargetsFromWindowHandlesLocked(windowHandles);
1551 if (inputTargets.empty()) {
1552 return;
1553 }
1554 entry->dispatchInProgress = true;
1555 dispatchEventLocked(currentTime, entry, inputTargets);
1556}
1557
1558std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1559 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1560 std::vector<InputTarget> inputTargets;
1561 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001562 const sp<IBinder>& token = handle->getToken();
1563 if (token == nullptr) {
1564 continue;
1565 }
1566 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1567 if (channel == nullptr) {
1568 continue; // Window has gone away
1569 }
1570 InputTarget target;
1571 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001572 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001573 inputTargets.push_back(target);
1574 }
1575 return inputTargets;
1576}
1577
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001578bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001579 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001581 if (!entry->dispatchInProgress) {
1582 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1583 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1584 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1585 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001586 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 // We have seen two identical key downs in a row which indicates that the device
1588 // driver is automatically generating key repeats itself. We take note of the
1589 // repeat here, but we disable our own next key repeat timer since it is clear that
1590 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001591 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1592 // Make sure we don't get key down from a different device. If a different
1593 // device Id has same key pressed down, the new device Id will replace the
1594 // current one to hold the key repeat with repeat count reset.
1595 // In the future when got a KEY_UP on the device id, drop it and do not
1596 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1598 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001599 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 } else {
1601 // Not a repeat. Save key down state in case we do see a repeat later.
1602 resetKeyRepeatLocked();
1603 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1604 }
1605 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001606 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1607 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001608 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan65613802023-02-22 23:36:58 +00001609 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001610 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1611 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001612 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 resetKeyRepeatLocked();
1614 }
1615
1616 if (entry->repeatCount == 1) {
1617 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1618 } else {
1619 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1620 }
1621
1622 entry->dispatchInProgress = true;
1623
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001624 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001625 }
1626
1627 // Handle case where the policy asked us to try again later last time.
Michael Wright5caf55a2022-11-24 22:31:42 +00001628 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 if (currentTime < entry->interceptKeyWakeupTime) {
1630 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1631 *nextWakeupTime = entry->interceptKeyWakeupTime;
1632 }
1633 return false; // wait until next wakeup
1634 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001635 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 entry->interceptKeyWakeupTime = 0;
1637 }
1638
1639 // Give the policy a chance to intercept the key.
Michael Wright5caf55a2022-11-24 22:31:42 +00001640 if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001642 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001643 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001644
1645 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1646 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1647 };
1648 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 return false; // wait for the command to run
1650 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00001651 entry->interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 }
Michael Wright5caf55a2022-11-24 22:31:42 +00001653 } else if (entry->interceptKeyResult == KeyEntry::InterceptKeyResult::SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001654 if (*dropReason == DropReason::NOT_DROPPED) {
1655 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001656 }
1657 }
1658
1659 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001660 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001661 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001662 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1663 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001664 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 return true;
1666 }
1667
1668 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001669 InputEventInjectionResult injectionResult;
1670 sp<WindowInfoHandle> focusedWindow =
1671 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1672 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001673 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 return false;
1675 }
1676
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001677 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001678 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 return true;
1680 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001681 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1682
1683 std::vector<InputTarget> inputTargets;
1684 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001685 InputTarget::Flags::FOREGROUND | InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001686 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001687
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001688 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001689 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690
1691 // Dispatch the key.
1692 dispatchEventLocked(currentTime, entry, inputTargets);
1693 return true;
1694}
1695
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001696void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001697 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1698 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1699 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1700 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1701 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1702 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1703 entry.metaState, entry.repeatCount, entry.downTime);
1704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705}
1706
Prabir Pradhancef936d2021-07-21 16:17:52 +00001707void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1708 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001709 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001710 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1711 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1712 "source=0x%x, sensorType=%s",
1713 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001714 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001715 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001716 auto command = [this, entry]() REQUIRES(mLock) {
1717 scoped_unlock unlock(mLock);
1718
1719 if (entry->accuracyChanged) {
1720 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1721 }
1722 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1723 entry->hwTimestamp, entry->values);
1724 };
1725 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001726}
1727
1728bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001729 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1730 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001731 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001732 }
Chris Yef59a2f42020-10-16 12:55:26 -07001733 { // acquire lock
1734 std::scoped_lock _l(mLock);
1735
1736 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1737 std::shared_ptr<EventEntry> entry = *it;
1738 if (entry->type == EventEntry::Type::SENSOR) {
1739 it = mInboundQueue.erase(it);
1740 releaseInboundEventLocked(entry);
1741 }
1742 }
1743 }
1744 return true;
1745}
1746
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001747bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001748 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001749 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001751 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 entry->dispatchInProgress = true;
1753
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001754 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 }
1756
1757 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001758 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001759 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001760 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1761 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 return true;
1763 }
1764
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001765 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766
1767 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001768 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769
1770 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001771 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 if (isPointerEvent) {
1773 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001774
1775 if (mDragState &&
1776 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1777 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1778 pilferPointersLocked(mDragState->dragWindow->getToken());
1779 }
1780
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08001781 inputTargets =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001782 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001783 /*byref*/ injectionResult);
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08001784 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED &&
1785 !inputTargets.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 } else {
1787 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001788 sp<WindowInfoHandle> focusedWindow =
1789 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1790 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1791 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1792 addWindowTargetLocked(focusedWindow,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001793 InputTarget::Flags::FOREGROUND |
1794 InputTarget::Flags::DISPATCH_AS_IS,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08001795 /*pointerIds=*/{}, getDownTime(*entry), inputTargets);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001798 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 return false;
1800 }
1801
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001802 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001803 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001804 return true;
1805 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001806 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001807 CancelationOptions::Mode mode(
1808 isPointerEvent ? CancelationOptions::Mode::CANCEL_POINTER_EVENTS
1809 : CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001810 CancelationOptions options(mode, "input event injection failed");
1811 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 return true;
1813 }
1814
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001815 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001816 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817
1818 // Dispatch the motion.
1819 if (conflictingPointerActions) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001820 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001821 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 synthesizeCancelationEventsForAllConnectionsLocked(options);
1823 }
1824 dispatchEventLocked(currentTime, entry, inputTargets);
1825 return true;
1826}
1827
chaviw98318de2021-05-19 16:45:23 -05001828void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001829 bool isExiting, const int32_t rawX,
1830 const int32_t rawY) {
1831 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001832 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001833 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1834 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001835
1836 enqueueInboundEventLocked(std::move(dragEntry));
1837}
1838
1839void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1840 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1841 if (channel == nullptr) {
1842 return; // Window has gone away
1843 }
1844 InputTarget target;
1845 target.inputChannel = channel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08001846 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
arthurhungb89ccb02020-12-30 16:19:01 +08001847 entry->dispatchInProgress = true;
1848 dispatchEventLocked(currentTime, entry, {target});
1849}
1850
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001851void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001852 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001853 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=%s, displayId=%" PRId32
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001854 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001855 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001856 "metaState=0x%x, buttonState=0x%x,"
1857 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08001858 prefix, entry.eventTime, entry.deviceId,
1859 inputEventSourceToString(entry.source).c_str(), entry.displayId, entry.policyFlags,
1860 MotionEvent::actionToString(entry.action).c_str(), entry.actionButton, entry.flags,
1861 entry.metaState, entry.buttonState, entry.edgeFlags, entry.xPrecision,
1862 entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001864 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001865 ALOGD(" Pointer %d: id=%d, toolType=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001866 "x=%f, y=%f, pressure=%f, size=%f, "
1867 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1868 "orientation=%f",
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -07001869 i, entry.pointerProperties[i].id,
1870 ftl::enum_string(entry.pointerProperties[i].toolType).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001871 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1872 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1873 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1874 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1875 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1876 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1877 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1878 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1879 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1880 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882}
1883
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001884void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1885 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001886 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001887 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001888 if (DEBUG_DISPATCH_CYCLE) {
1889 ALOGD("dispatchEventToCurrentInputTargets");
1890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001892 updateInteractionTokensLocked(*eventEntry, inputTargets);
1893
Michael Wrightd02c5b62014-02-10 15:10:22 -08001894 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1895
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001896 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001898 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001899 std::shared_ptr<Connection> connection =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001900 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001901 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001902 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001904 if (DEBUG_FOCUS) {
1905 ALOGD("Dropping event delivery to target with channel '%s' because it "
1906 "is no longer registered with the input dispatcher.",
1907 inputTarget.inputChannel->getName().c_str());
1908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909 }
1910 }
1911}
1912
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07001913void InputDispatcher::cancelEventsForAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001914 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1915 // If the policy decides to close the app, we will get a channel removal event via
1916 // unregisterInputChannel, and will clean up the connection that way. We are already not
1917 // sending new pointers to the connection when it blocked, but focused events will continue to
1918 // pile up.
1919 ALOGW("Canceling events for %s because it is unresponsive",
1920 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001921 if (connection->status == Connection::Status::NORMAL) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00001922 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001923 "application not responding");
1924 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 }
1926}
1927
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001928void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001929 if (DEBUG_FOCUS) {
1930 ALOGD("Resetting ANR timeouts.");
1931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932
1933 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001934 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001935 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936}
1937
Tiger Huang721e26f2018-07-24 22:26:19 +08001938/**
1939 * Get the display id that the given event should go to. If this event specifies a valid display id,
1940 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1941 * Focused display is the display that the user most recently interacted with.
1942 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001943int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001944 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001945 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001946 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001947 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1948 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001949 break;
1950 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001951 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001952 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1953 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001954 break;
1955 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001956 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001957 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001958 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001959 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001960 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001961 case EventEntry::Type::SENSOR:
1962 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001963 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001964 return ADISPLAY_ID_NONE;
1965 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001966 }
1967 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1968}
1969
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001970bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1971 const char* focusedWindowName) {
1972 if (mAnrTracker.empty()) {
1973 // already processed all events that we waited for
1974 mKeyIsWaitingForEventsTimeout = std::nullopt;
1975 return false;
1976 }
1977
1978 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1979 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001980 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001981 mKeyIsWaitingForEventsTimeout = currentTime +
1982 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1983 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001984 return true;
1985 }
1986
1987 // We still have pending events, and already started the timer
1988 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1989 return true; // Still waiting
1990 }
1991
1992 // Waited too long, and some connection still hasn't processed all motions
1993 // Just send the key to the focused window
1994 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1995 focusedWindowName);
1996 mKeyIsWaitingForEventsTimeout = std::nullopt;
1997 return false;
1998}
1999
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002000sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
2001 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
2002 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002003 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002004 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005
Tiger Huang721e26f2018-07-24 22:26:19 +08002006 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05002007 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07002008 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08002009 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
2010
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 // If there is no currently focused window and no focused application
2012 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002013 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
2014 ALOGI("Dropping %s event because there is no focused window or focused application in "
2015 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08002016 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002017 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 }
2019
Vishnu Nair062a8672021-09-03 16:07:44 -07002020 // Drop key events if requested by input feature
2021 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002022 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07002023 }
2024
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002025 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
2026 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
2027 // start interacting with another application via touch (app switch). This code can be removed
2028 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
2029 // an app is expected to have a focused window.
2030 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
2031 if (!mNoFocusedWindowTimeoutTime.has_value()) {
2032 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002033 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
2034 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
2035 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002036 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05002037 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002038 ALOGW("Waiting because no window has focus but %s may eventually add a "
2039 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05002040 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002041 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002042 outInjectionResult = InputEventInjectionResult::PENDING;
2043 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002044 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
2045 // Already raised ANR. Drop the event
2046 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08002047 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002048 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002049 } else {
2050 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002051 outInjectionResult = InputEventInjectionResult::PENDING;
2052 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002053 }
2054 }
2055
2056 // we have a valid, non-null focused window
2057 resetNoFocusedWindowTimeoutLocked();
2058
Prabir Pradhan5735a322022-04-11 17:23:34 +00002059 // Verify targeted injection.
2060 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
2061 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002062 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2063 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 }
2065
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002066 if (focusedWindowHandle->getInfo()->inputConfig.test(
2067 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002068 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002069 outInjectionResult = InputEventInjectionResult::PENDING;
2070 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002071 }
2072
2073 // If the event is a key event, then we must wait for all previous events to
2074 // complete before delivering it because previous events may have the
2075 // side-effect of transferring focus to a different window and we want to
2076 // ensure that the following keys are sent to the new window.
2077 //
2078 // Suppose the user touches a button in a window then immediately presses "A".
2079 // If the button causes a pop-up window to appear then we want to ensure that
2080 // the "A" key is delivered to the new pop-up window. This is because users
2081 // often anticipate pending UI changes when typing on a keyboard.
2082 // To obtain this behavior, we must serialize key events with respect to all
2083 // prior input events.
2084 if (entry.type == EventEntry::Type::KEY) {
2085 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2086 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002087 outInjectionResult = InputEventInjectionResult::PENDING;
2088 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 }
2091
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002092 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2093 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094}
2095
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002096/**
2097 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2098 * that are currently unresponsive.
2099 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002100std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2101 const std::vector<Monitor>& monitors) const {
2102 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002103 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002104 [this](const Monitor& monitor) REQUIRES(mLock) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07002105 std::shared_ptr<Connection> connection =
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002106 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002107 if (connection == nullptr) {
2108 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002109 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 return false;
2111 }
2112 if (!connection->responsive) {
2113 ALOGW("Unresponsive monitor %s will not get the new gesture",
2114 connection->inputChannel->getName().c_str());
2115 return false;
2116 }
2117 return true;
2118 });
2119 return responsiveMonitors;
2120}
2121
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002122/**
2123 * In general, touch should be always split between windows. Some exceptions:
2124 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2125 * from the same device, *and* the window that's receiving the current pointer does not support
2126 * split touch.
2127 * 2. Don't split mouse events
2128 */
2129bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2130 const MotionEntry& entry) const {
2131 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2132 // We should never split mouse events
2133 return false;
2134 }
2135 for (const TouchedWindow& touchedWindow : touchState.windows) {
2136 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2137 // Spy windows should not affect whether or not touch is split.
2138 continue;
2139 }
2140 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2141 continue;
2142 }
Arthur Hungc539dbb2022-12-08 07:45:36 +00002143 if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
2144 gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
2145 // Wallpaper window should not affect whether or not touch is split
2146 continue;
2147 }
2148
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002149 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2150 // being sent there. For now, use deviceId from touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002151 if (entry.deviceId == touchState.deviceId && touchedWindow.pointerIds.any()) {
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002152 return false;
2153 }
2154 }
2155 return true;
2156}
2157
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002158std::vector<InputTarget> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002159 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2160 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002161 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002163 std::vector<InputTarget> targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 // For security reasons, we defer updating the touch state until we are sure that
2165 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002166 const int32_t displayId = entry.displayId;
2167 const int32_t action = entry.action;
2168 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169
2170 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002171 outInjectionResult = InputEventInjectionResult::PENDING;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002173 // Copy current touch state into tempTouchState.
2174 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2175 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002176 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002177 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002178 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2179 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002180 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002181 }
2182
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002183 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002184 const bool switchedDevice = (oldState != nullptr) &&
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002185 (oldState->deviceId != entry.deviceId || oldState->source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002186
2187 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2188 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2189 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002190 // A DOWN could be generated from POINTER_DOWN if the initial pointers did not land into any
2191 // touchable windows.
2192 const bool wasDown = oldState != nullptr && oldState->isDown();
2193 const bool isDown = (maskedAction == AMOTION_EVENT_ACTION_DOWN) ||
2194 (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN && !wasDown);
2195 const bool newGesture = isDown || maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction;
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002196 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08002197
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002198 // If pointers are already down, let's finish the current gesture and ignore the new events
2199 // from another device. However, if the new event is a down event, let's cancel the current
2200 // touch and let the new one take over.
2201 if (switchedDevice && wasDown && !isDown) {
2202 LOG(INFO) << "Dropping event because a pointer for device " << oldState->deviceId
2203 << " is already down in display " << displayId << ": " << entry.getDescription();
2204 // TODO(b/211379801): test multiple simultaneous input streams.
2205 outInjectionResult = InputEventInjectionResult::FAILED;
2206 return {}; // wrong device
2207 }
2208
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 if (newGesture) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002210 // If a new gesture is starting, clear the touch state completely.
2211 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002212 tempTouchState.deviceId = entry.deviceId;
2213 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002215 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002216 ALOGI("Dropping move event because a pointer for a different device is already active "
2217 "in display %" PRId32,
2218 displayId);
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08002219 // TODO(b/211379801): test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002220 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002221 return {}; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 }
2223
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002224 if (isHoverAction) {
2225 // For hover actions, we will treat 'tempTouchState' as a new state, so let's erase
2226 // all of the existing hovering pointers and recompute.
2227 tempTouchState.clearHoveringPointers();
2228 }
2229
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2231 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002232 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002233 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002234 // Outside targets should be added upon first dispatched DOWN event. That means, this should
2235 // be a pointer that would generate ACTION_DOWN, *and* touch should not already be down.
Prabir Pradhand65552b2021-10-07 11:23:50 -07002236 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002237 auto [newTouchedWindowHandle, outsideTargets] =
2238 findTouchedWindowAtLocked(displayId, x, y, isStylus);
Michael Wright3dd60e22019-03-27 22:06:44 +00002239
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002240 if (isDown) {
2241 targets += outsideTargets;
2242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002244 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002245 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002247 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002248 }
2249
Prabir Pradhan5735a322022-04-11 17:23:34 +00002250 // Verify targeted injection.
2251 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2252 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002253 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002254 newTouchedWindowHandle = nullptr;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002255 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002256 }
2257
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002258 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002259 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002260 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2261 // New window supports splitting, but we should never split mouse events.
2262 isSplit = !isFromMouse;
2263 } else if (isSplit) {
2264 // New window does not support splitting but we have already split events.
2265 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002266 newTouchedWindowHandle = nullptr;
2267 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002268 } else {
2269 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002270 // be delivered to a new window which supports split touch. Pointers from a mouse device
2271 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002272 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002273 }
2274
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002275 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002276 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002277 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002278 // Process the foreground window first so that it is the first to receive the event.
2279 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002280 }
2281
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002282 if (newTouchedWindows.empty()) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00002283 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2284 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002285 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002286 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002287 return {};
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002288 }
2289
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002290 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002291 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002292 continue;
2293 }
2294
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002295 if (isHoverAction) {
2296 const int32_t pointerId = entry.pointerProperties[0].id;
2297 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2298 // Pointer left. Remove it
2299 tempTouchState.removeHoveringPointer(entry.deviceId, pointerId);
2300 } else {
2301 // The "windowHandle" is the target of this hovering pointer.
2302 tempTouchState.addHoveringPointerToWindow(windowHandle, entry.deviceId,
2303 pointerId);
2304 }
2305 }
2306
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002307 // Set target flags.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002308 ftl::Flags<InputTarget::Flags> targetFlags = InputTarget::Flags::DISPATCH_AS_IS;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002309
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002310 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2311 // There should only be one touched window that can be "foreground" for the pointer.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002312 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002313 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002314
2315 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002316 targetFlags |= InputTarget::Flags::SPLIT;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002317 }
2318 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002319 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002320 } else if (isWindowObscuredLocked(windowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002321 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002322 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002323
2324 // Update the temporary touch state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002325 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002326 if (!isHoverAction) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002327 pointerIds.set(entry.pointerProperties[pointerIndex].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002328 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002329
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002330 const bool isDownOrPointerDown = maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2331 maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN;
2332
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002333 // TODO(b/211379801): Currently, even if pointerIds are empty (hover case), we would
2334 // still add a window to the touch state. We should avoid doing that, but some of the
2335 // later checks ("at least one foreground window") rely on this in order to dispatch
2336 // the event properly, so that needs to be updated, possibly by looking at InputTargets.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002337 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002338 isDownOrPointerDown
2339 ? std::make_optional(entry.eventTime)
2340 : std::nullopt);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002341
2342 // If this is the pointer going down and the touched window has a wallpaper
2343 // then also add the touched wallpaper windows so they are locked in for the duration
2344 // of the touch gesture.
2345 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2346 // engine only supports touch events. We would need to add a mechanism similar
2347 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002348 if (isDownOrPointerDown) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00002349 if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
2350 windowHandle->getInfo()->inputConfig.test(
2351 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
2352 sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
2353 if (wallpaper != nullptr) {
2354 ftl::Flags<InputTarget::Flags> wallpaperFlags =
2355 InputTarget::Flags::WINDOW_IS_OBSCURED |
2356 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
2357 InputTarget::Flags::DISPATCH_AS_IS;
2358 if (isSplit) {
2359 wallpaperFlags |= InputTarget::Flags::SPLIT;
2360 }
2361 tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
2362 entry.eventTime);
2363 }
2364 }
2365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002367
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002368 // If a window is already pilfering some pointers, give it this new pointer as well and
2369 // make it pilfering. This will prevent other non-spy windows from getting this pointer,
2370 // which is a specific behaviour that we want.
2371 const int32_t pointerId = entry.pointerProperties[pointerIndex].id;
2372 for (TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002373 if (touchedWindow.pointerIds.test(pointerId) &&
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002374 touchedWindow.pilferedPointerIds.count() > 0) {
2375 // This window is already pilfering some pointers, and this new pointer is also
2376 // going to it. Therefore, take over this pointer and don't give it to anyone
2377 // else.
2378 touchedWindow.pilferedPointerIds.set(pointerId);
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002379 }
2380 }
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08002381
2382 // Restrict all pilfered pointers to the pilfering windows.
2383 tempTouchState.cancelPointersForNonPilferingWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384 } else {
2385 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2386
2387 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002388 if (!tempTouchState.isDown()) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002389 LOG(INFO) << "Dropping event because the pointer is not down or we previously "
2390 "dropped the pointer down event in display "
2391 << displayId << ": " << entry.getDescription();
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002392 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002393 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 }
2395
arthurhung6d4bed92021-03-17 11:59:33 +08002396 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002397
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002399 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002400 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002401 const auto [x, y] = resolveTouchedPosition(entry);
Harry Cutts33476232023-01-30 19:57:29 +00002402 const bool isStylus = isPointerFromStylus(entry, /*pointerIndex=*/0);
chaviw98318de2021-05-19 16:45:23 -05002403 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002404 tempTouchState.getFirstForegroundWindowHandle();
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002405 LOG_ALWAYS_FATAL_IF(oldTouchedWindowHandle == nullptr);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002406 auto [newTouchedWindowHandle, _] = findTouchedWindowAtLocked(displayId, x, y, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002407
Prabir Pradhan5735a322022-04-11 17:23:34 +00002408 // Verify targeted injection.
2409 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2410 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002411 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002412 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002413 }
2414
Vishnu Nair062a8672021-09-03 16:07:44 -07002415 // Drop touch events if requested by input feature
2416 if (newTouchedWindowHandle != nullptr &&
2417 shouldDropInput(entry, newTouchedWindowHandle)) {
2418 newTouchedWindowHandle = nullptr;
2419 }
2420
Siarhei Vishniakou0f6558d2023-04-21 12:05:13 -07002421 if (!haveSameToken(oldTouchedWindowHandle, newTouchedWindowHandle)) {
2422 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2423 oldTouchedWindowHandle->getName().c_str(),
2424 newTouchedWindowHandle->getName().c_str(), displayId);
2425
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426 // Make a slippery exit from the old window.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002427 std::bitset<MAX_POINTER_ID + 1> pointerIds;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002428 const int32_t pointerId = entry.pointerProperties[0].id;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002429 pointerIds.set(pointerId);
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002430
2431 const TouchedWindow& touchedWindow =
2432 tempTouchState.getTouchedWindow(oldTouchedWindowHandle);
2433 addWindowTargetLocked(oldTouchedWindowHandle,
2434 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT, pointerIds,
2435 touchedWindow.firstDownTimeInTarget, targets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436
2437 // Make a slippery entrance into the new window.
2438 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002439 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 }
2441
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002442 ftl::Flags<InputTarget::Flags> targetFlags =
2443 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002444 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002445 targetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 if (isSplit) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002448 targetFlags |= InputTarget::Flags::SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 }
2450 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002451 targetFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002452 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002453 targetFlags |= InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 }
2455
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002456 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2457 entry.eventTime);
Arthur Hungc539dbb2022-12-08 07:45:36 +00002458
2459 // Check if the wallpaper window should deliver the corresponding event.
2460 slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002461 tempTouchState, pointerId, targets);
2462 tempTouchState.removeTouchedPointerFromWindow(pointerId, oldTouchedWindowHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 }
2464 }
Arthur Hung96483742022-11-15 03:30:48 +00002465
2466 // Update the pointerIds for non-splittable when it received pointer down.
2467 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2468 // If no split, we suppose all touched windows should receive pointer down.
2469 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2470 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2471 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2472 // Ignore drag window for it should just track one pointer.
2473 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2474 continue;
2475 }
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002476 touchedWindow.pointerIds.set(entry.pointerProperties[pointerIndex].id);
Arthur Hung96483742022-11-15 03:30:48 +00002477 }
2478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 }
2480
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002481 // Update dispatching for hover enter and exit.
Sam Dubeyf886dec2023-01-27 13:28:19 +00002482 {
2483 std::vector<TouchedWindow> hoveringWindows =
2484 getHoveringWindowsLocked(oldState, tempTouchState, entry);
2485 for (const TouchedWindow& touchedWindow : hoveringWindows) {
2486 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2487 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2488 targets);
2489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 }
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002491 // Ensure that we have at least one foreground window or at least one window that cannot be a
2492 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2493 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2494 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002495 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2496 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002497 return !canReceiveForegroundTouches(
2498 *touchedWindow.windowHandle->getInfo()) ||
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002499 touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002500 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002501 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2502 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002503 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002504 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 }
2506
Prabir Pradhan5735a322022-04-11 17:23:34 +00002507 // Ensure that all touched windows are valid for injection.
2508 if (entry.injectionState != nullptr) {
2509 std::string errs;
2510 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002511 if (touchedWindow.targetFlags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00002512 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2513 // dispatched to any uid, since the coords will be zeroed out later.
2514 continue;
2515 }
2516 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2517 if (err) errs += "\n - " + *err;
2518 }
2519 if (!errs.empty()) {
2520 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2521 "%d:%s",
2522 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002523 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Siarhei Vishniakou8619eb32022-12-01 21:30:59 -08002524 return {};
Prabir Pradhan5735a322022-04-11 17:23:34 +00002525 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002526 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002527
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002528 // Check whether windows listening for outside touches are owned by the same UID. If the owner
2529 // has a different UID, then we will not reveal coordinate information to this window.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002531 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002532 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002533 if (foregroundWindowHandle) {
2534 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002535 for (InputTarget& target : targets) {
2536 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
2537 sp<WindowInfoHandle> targetWindow =
2538 getWindowHandleLocked(target.inputChannel->getConnectionToken());
2539 if (targetWindow->getInfo()->ownerUid != foregroundWindowUid) {
2540 target.flags |= InputTarget::Flags::ZERO_COORDS;
Michael Wright3dd60e22019-03-27 22:06:44 +00002541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002542 }
2543 }
2544 }
2545 }
2546
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002547 // Success! Output targets from the touch state.
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002548 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002549 if (touchedWindow.pointerIds.none() && !touchedWindow.hasHoveringPointers(entry.deviceId)) {
Siarhei Vishniakoue0431e42023-01-28 17:01:39 -08002550 // Windows with hovering pointers are getting persisted inside TouchState.
2551 // Do not send this event to those windows.
2552 continue;
2553 }
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002554 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
2555 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2556 targets);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002557 }
Sam Dubey39d37cf2022-12-07 18:05:35 +00002558
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002559 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Sam Dubeyf886dec2023-01-27 13:28:19 +00002560 // Drop the outside or hover touch windows since we will not care about them
2561 // in the next iteration.
2562 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002565 if (switchedDevice) {
2566 if (DEBUG_FOCUS) {
2567 ALOGD("Conflicting pointer actions: Switched to a different device.");
2568 }
2569 *outConflictingPointerActions = true;
2570 }
2571
2572 if (isHoverAction) {
2573 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002574 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002575 ALOGD_IF(DEBUG_FOCUS,
2576 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002577 *outConflictingPointerActions = true;
2578 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002579 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2580 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2581 tempTouchState.deviceId = entry.deviceId;
2582 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002583 }
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002584 } else if (maskedAction == AMOTION_EVENT_ACTION_UP) {
2585 // Pointer went up.
2586 tempTouchState.removeTouchedPointer(entry.pointerProperties[0].id);
Siarhei Vishniakoub581f7f2022-12-07 20:23:06 +00002587 } else if (maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002588 // All pointers up or canceled.
2589 tempTouchState.reset();
2590 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2591 // First pointer went down.
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002592 if (oldState && (oldState->isDown() || oldState->hasHoveringPointers())) {
2593 ALOGD("Conflicting pointer actions: Down received while already down or hovering.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002594 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002595 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002596 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2597 // One pointer went up.
2598 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2599 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002601 for (size_t i = 0; i < tempTouchState.windows.size();) {
2602 TouchedWindow& touchedWindow = tempTouchState.windows[i];
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002603 touchedWindow.pointerIds.reset(pointerId);
2604 if (touchedWindow.pointerIds.none()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002605 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2606 continue;
2607 }
2608 i += 1;
2609 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610 }
2611
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002612 // Save changes unless the action was scroll in which case the temporary touch
2613 // state was only valid for this one action.
2614 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002615 if (displayId >= 0) {
Siarhei Vishniakouf372b812023-02-14 18:06:51 -08002616 tempTouchState.clearWindowsWithoutPointers();
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002617 mTouchStatesByDisplay[displayId] = tempTouchState;
2618 } else {
2619 mTouchStatesByDisplay.erase(displayId);
2620 }
2621 }
2622
Siarhei Vishniakou0b0374d2022-11-17 17:40:53 -08002623 if (tempTouchState.windows.empty()) {
2624 mTouchStatesByDisplay.erase(displayId);
2625 }
2626
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002627 return targets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628}
2629
arthurhung6d4bed92021-03-17 11:59:33 +08002630void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002631 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2632 // have an explicit reason to support it.
2633 constexpr bool isStylus = false;
2634
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002635 auto [dropWindow, _] =
Harry Cutts33476232023-01-30 19:57:29 +00002636 findTouchedWindowAtLocked(displayId, x, y, isStylus, /*ignoreDragWindow=*/true);
arthurhung6d4bed92021-03-17 11:59:33 +08002637 if (dropWindow) {
2638 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002639 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002640 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002641 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002642 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002643 }
2644 mDragState.reset();
2645}
2646
2647void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002648 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002649 return;
2650 }
2651
arthurhung6d4bed92021-03-17 11:59:33 +08002652 if (!mDragState->isStartDrag) {
2653 mDragState->isStartDrag = true;
2654 mDragState->isStylusButtonDownAtStart =
2655 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2656 }
2657
Arthur Hung54745652022-04-20 07:17:41 +00002658 // Find the pointer index by id.
2659 int32_t pointerIndex = 0;
2660 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2661 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2662 if (pointerProperties.id == mDragState->pointerId) {
2663 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002664 }
Arthur Hung54745652022-04-20 07:17:41 +00002665 }
arthurhung6d4bed92021-03-17 11:59:33 +08002666
Arthur Hung54745652022-04-20 07:17:41 +00002667 if (uint32_t(pointerIndex) == entry.pointerCount) {
2668 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002669 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002670 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002671 return;
2672 }
2673
2674 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2675 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2676 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2677
2678 switch (maskedAction) {
2679 case AMOTION_EVENT_ACTION_MOVE: {
2680 // Handle the special case : stylus button no longer pressed.
2681 bool isStylusButtonDown =
2682 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2683 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2684 finishDragAndDrop(entry.displayId, x, y);
2685 return;
2686 }
2687
2688 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2689 // until we have an explicit reason to support it.
2690 constexpr bool isStylus = false;
2691
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08002692 auto [hoverWindowHandle, _] = findTouchedWindowAtLocked(entry.displayId, x, y, isStylus,
Harry Cutts33476232023-01-30 19:57:29 +00002693 /*ignoreDragWindow=*/true);
Arthur Hung54745652022-04-20 07:17:41 +00002694 // enqueue drag exit if needed.
2695 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2696 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2697 if (mDragState->dragHoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002698 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, /*isExiting=*/true, x,
Arthur Hung54745652022-04-20 07:17:41 +00002699 y);
2700 }
2701 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2702 }
2703 // enqueue drag location if needed.
2704 if (hoverWindowHandle != nullptr) {
Harry Cutts33476232023-01-30 19:57:29 +00002705 enqueueDragEventLocked(hoverWindowHandle, /*isExiting=*/false, x, y);
Arthur Hung54745652022-04-20 07:17:41 +00002706 }
2707 break;
2708 }
2709
2710 case AMOTION_EVENT_ACTION_POINTER_UP:
2711 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2712 break;
2713 }
2714 // The drag pointer is up.
2715 [[fallthrough]];
2716 case AMOTION_EVENT_ACTION_UP:
2717 finishDragAndDrop(entry.displayId, x, y);
2718 break;
2719 case AMOTION_EVENT_ACTION_CANCEL: {
2720 ALOGD("Receiving cancel when drag and drop.");
2721 sendDropWindowCommandLocked(nullptr, 0, 0);
2722 mDragState.reset();
2723 break;
2724 }
arthurhungb89ccb02020-12-30 16:19:01 +08002725 }
2726}
2727
chaviw98318de2021-05-19 16:45:23 -05002728void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002729 ftl::Flags<InputTarget::Flags> targetFlags,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08002730 std::bitset<MAX_POINTER_ID + 1> pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002731 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002732 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002733 std::vector<InputTarget>::iterator it =
2734 std::find_if(inputTargets.begin(), inputTargets.end(),
2735 [&windowHandle](const InputTarget& inputTarget) {
2736 return inputTarget.inputChannel->getConnectionToken() ==
2737 windowHandle->getToken();
2738 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002739
chaviw98318de2021-05-19 16:45:23 -05002740 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002741
2742 if (it == inputTargets.end()) {
2743 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002744 std::shared_ptr<InputChannel> inputChannel =
2745 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002746 if (inputChannel == nullptr) {
2747 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2748 return;
2749 }
2750 inputTarget.inputChannel = inputChannel;
2751 inputTarget.flags = targetFlags;
2752 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002753 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002754 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2755 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002756 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002757 } else {
Siarhei Vishniakoua06bb552023-02-07 09:38:56 -08002758 // DisplayInfo not found for this window on display windowInfo->displayId.
2759 // TODO(b/198444055): Make this an error message after 'setInputWindows' API is removed.
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002760 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002761 inputTargets.push_back(inputTarget);
2762 it = inputTargets.end() - 1;
2763 }
2764
2765 ALOG_ASSERT(it->flags == targetFlags);
2766 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2767
chaviw1ff3d1e2020-07-01 15:53:47 -07002768 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769}
2770
Michael Wright3dd60e22019-03-27 22:06:44 +00002771void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002772 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002773 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2774 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002775
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002776 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2777 InputTarget target;
2778 target.inputChannel = monitor.inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002779 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002780 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2781 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002782 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2783 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002784 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002785 target.setDefaultPointerTransform(target.displayTransform);
2786 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787 }
2788}
2789
Robert Carrc9bf1d32020-04-13 17:21:08 -07002790/**
2791 * Indicate whether one window handle should be considered as obscuring
2792 * another window handle. We only check a few preconditions. Actually
2793 * checking the bounds is left to the caller.
2794 */
chaviw98318de2021-05-19 16:45:23 -05002795static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2796 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002797 // Compare by token so cloned layers aren't counted
2798 if (haveSameToken(windowHandle, otherHandle)) {
2799 return false;
2800 }
2801 auto info = windowHandle->getInfo();
2802 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002803 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002804 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002805 } else if (otherInfo->alpha == 0 &&
2806 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002807 // Those act as if they were invisible, so we don't need to flag them.
2808 // We do want to potentially flag touchable windows even if they have 0
2809 // opacity, since they can consume touches and alter the effects of the
2810 // user interaction (eg. apps that rely on
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08002811 // Flags::WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002812 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2813 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002814 } else if (info->ownerUid == otherInfo->ownerUid) {
2815 // If ownerUid is the same we don't generate occlusion events as there
2816 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002817 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002818 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002819 return false;
2820 } else if (otherInfo->displayId != info->displayId) {
2821 return false;
2822 }
2823 return true;
2824}
2825
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002826/**
2827 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2828 * untrusted, one should check:
2829 *
2830 * 1. If result.hasBlockingOcclusion is true.
2831 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2832 * BLOCK_UNTRUSTED.
2833 *
2834 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2835 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2836 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2837 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2838 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2839 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2840 *
2841 * If neither of those is true, then it means the touch can be allowed.
2842 */
2843InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002844 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2845 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002846 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002847 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002848 TouchOcclusionInfo info;
2849 info.hasBlockingOcclusion = false;
2850 info.obscuringOpacity = 0;
2851 info.obscuringUid = -1;
2852 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002853 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002854 if (windowHandle == otherHandle) {
2855 break; // All future windows are below us. Exit early.
2856 }
chaviw98318de2021-05-19 16:45:23 -05002857 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002858 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2859 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002860 if (DEBUG_TOUCH_OCCLUSION) {
2861 info.debugInfo.push_back(
2862 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2863 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002864 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2865 // we perform the checks below to see if the touch can be propagated or not based on the
2866 // window's touch occlusion mode
2867 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2868 info.hasBlockingOcclusion = true;
2869 info.obscuringUid = otherInfo->ownerUid;
2870 info.obscuringPackage = otherInfo->packageName;
2871 break;
2872 }
2873 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2874 uint32_t uid = otherInfo->ownerUid;
2875 float opacity =
2876 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2877 // Given windows A and B:
2878 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2879 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2880 opacityByUid[uid] = opacity;
2881 if (opacity > info.obscuringOpacity) {
2882 info.obscuringOpacity = opacity;
2883 info.obscuringUid = uid;
2884 info.obscuringPackage = otherInfo->packageName;
2885 }
2886 }
2887 }
2888 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002889 if (DEBUG_TOUCH_OCCLUSION) {
2890 info.debugInfo.push_back(
2891 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2892 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002893 return info;
2894}
2895
chaviw98318de2021-05-19 16:45:23 -05002896std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002897 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002898 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2899 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2900 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2901 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002902 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2903 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2904 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2905 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2906 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002907 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07002908 binderToString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002909}
2910
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002911bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2912 if (occlusionInfo.hasBlockingOcclusion) {
2913 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2914 occlusionInfo.obscuringUid);
2915 return false;
2916 }
2917 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2918 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2919 "%.2f, maximum allowed = %.2f)",
2920 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2921 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2922 return false;
2923 }
2924 return true;
2925}
2926
chaviw98318de2021-05-19 16:45:23 -05002927bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002928 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002930 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2931 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002932 if (windowHandle == otherHandle) {
2933 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934 }
chaviw98318de2021-05-19 16:45:23 -05002935 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002936 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002937 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 return true;
2939 }
2940 }
2941 return false;
2942}
2943
chaviw98318de2021-05-19 16:45:23 -05002944bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002945 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002946 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2947 const WindowInfo* windowInfo = windowHandle->getInfo();
2948 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002949 if (windowHandle == otherHandle) {
2950 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002951 }
chaviw98318de2021-05-19 16:45:23 -05002952 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002953 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002954 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002955 return true;
2956 }
2957 }
2958 return false;
2959}
2960
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002961std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002962 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002963 if (applicationHandle != nullptr) {
2964 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002965 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002966 } else {
2967 return applicationHandle->getName();
2968 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002969 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002970 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002972 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973 }
2974}
2975
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002976void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002977 if (!isUserActivityEvent(eventEntry)) {
2978 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002979 return;
2980 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002981 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002982 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002983 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002984 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002985 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002986 if (DEBUG_DISPATCH_CYCLE) {
2987 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002989 return;
2990 }
2991 }
2992
2993 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002994 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002995 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002996 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2997 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002998 return;
2999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003001 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003002 eventType = USER_ACTIVITY_EVENT_TOUCH;
3003 }
3004 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003006 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003007 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3008 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003009 return;
3010 }
3011 eventType = USER_ACTIVITY_EVENT_BUTTON;
3012 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00003014 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003015 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08003016 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003017 break;
3018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 }
3020
Prabir Pradhancef936d2021-07-21 16:17:52 +00003021 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
3022 REQUIRES(mLock) {
3023 scoped_unlock unlock(mLock);
3024 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
3025 };
3026 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027}
3028
3029void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003030 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003031 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003032 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003033 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003034 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003035 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003036 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003037 ATRACE_NAME(message.c_str());
3038 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003039 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003040 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=%s, "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003041 "globalScaleFactor=%f, pointerIds=%s %s",
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003042 connection->getInputChannelName().c_str(), inputTarget.flags.string().c_str(),
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003043 inputTarget.globalScaleFactor, bitsetToString(inputTarget.pointerIds).c_str(),
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003044 inputTarget.getPointerInfoString().c_str());
3045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046
3047 // Skip this event if the connection status is not normal.
3048 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003049 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003050 if (DEBUG_DISPATCH_CYCLE) {
3051 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003052 connection->getInputChannelName().c_str(),
3053 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055 return;
3056 }
3057
3058 // Split a motion event if needed.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003059 if (inputTarget.flags.test(InputTarget::Flags::SPLIT)) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003060 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003061 "Entry type %s should not have Flags::SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08003062 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003064 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003065 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003066 if (!inputTarget.firstDownTimeInTarget.has_value()) {
3067 logDispatchStateLocked();
3068 LOG(FATAL) << "Splitting motion events requires a down time to be set for the "
3069 "target on connection "
3070 << connection->getInputChannelName() << " for "
3071 << originalMotionEntry.getDescription();
3072 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003073 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003074 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
3075 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076 if (!splitMotionEntry) {
3077 return; // split event was dropped
3078 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00003079 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
3080 std::string reason = std::string("reason=pointer cancel on split window");
3081 android_log_event_list(LOGTAG_INPUT_CANCEL)
3082 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3083 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003084 if (DEBUG_FOCUS) {
3085 ALOGD("channel '%s' ~ Split motion event.",
3086 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003087 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003088 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003089 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
3090 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091 return;
3092 }
3093 }
3094
3095 // Not splitting. Enqueue dispatch entries for the event as is.
3096 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
3097}
3098
3099void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003100 const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003101 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003102 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003103 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003104 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003105 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003106 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00003107 ATRACE_NAME(message.c_str());
3108 }
Siarhei Vishniakou5cee1e32022-11-29 12:35:39 -08003109 LOG_ALWAYS_FATAL_IF(!inputTarget.flags.any(InputTarget::DISPATCH_MASK),
3110 "No dispatch flags are set for %s", eventEntry->getDescription().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003111
hongzuo liu95785e22022-09-06 02:51:35 +00003112 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113
3114 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003115 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003116 InputTarget::Flags::DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003117 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003118 InputTarget::Flags::DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003119 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003120 InputTarget::Flags::DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003121 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003122 InputTarget::Flags::DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003123 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003124 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003125 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003126 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127
3128 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003129 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 startDispatchCycleLocked(currentTime, connection);
3131 }
3132}
3133
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003134void InputDispatcher::enqueueDispatchEntryLocked(const std::shared_ptr<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003135 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003136 const InputTarget& inputTarget,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003137 ftl::Flags<InputTarget::Flags> dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003138 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003139 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3140 connection->getInputChannelName().c_str(),
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003141 dispatchMode.string().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003142 ATRACE_NAME(message.c_str());
3143 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003144 ftl::Flags<InputTarget::Flags> inputTargetFlags = inputTarget.flags;
3145 if (!inputTargetFlags.any(dispatchMode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 return;
3147 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003148
3149 inputTargetFlags.clear(InputTarget::DISPATCH_MASK);
3150 inputTargetFlags |= dispatchMode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151
3152 // This is a new event.
3153 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003154 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003155 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003157 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3158 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003159 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003161 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003162 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003163 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003164 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003165 dispatchEntry->resolvedAction = keyEntry.action;
3166 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003168 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3169 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003170 if (DEBUG_DISPATCH_CYCLE) {
3171 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3172 "event",
3173 connection->getInputChannelName().c_str());
3174 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003175 return; // skip the inconsistent event
3176 }
3177 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003180 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003181 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003182 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3183 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3184 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3185 static_cast<int32_t>(IdGenerator::Source::OTHER);
3186 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003187 if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003188 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003189 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003190 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003191 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_HOVER_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003192 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003193 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003194 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003195 } else if (dispatchMode.test(InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003196 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3197 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003198 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003199 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003200 }
3201 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003202 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3203 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003204 if (DEBUG_DISPATCH_CYCLE) {
3205 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3206 "enter event",
3207 connection->getInputChannelName().c_str());
3208 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003209 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3210 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003211 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003214 dispatchEntry->resolvedFlags = motionEntry.flags;
Siarhei Vishniakou1ae72f12023-01-29 12:55:30 -08003215 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_CANCEL) {
3216 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_CANCELED;
3217 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003218 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003219 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3220 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003221 if (dispatchEntry->targetFlags.test(InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003222 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3223 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003225 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3226 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003227 if (DEBUG_DISPATCH_CYCLE) {
3228 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3229 "event",
3230 connection->getInputChannelName().c_str());
3231 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003232 return; // skip the inconsistent event
3233 }
3234
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003235 dispatchEntry->resolvedEventId =
3236 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3237 ? mIdGenerator.nextId()
3238 : motionEntry.id;
3239 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3240 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3241 ") to MotionEvent(id=0x%" PRIx32 ").",
3242 motionEntry.id, dispatchEntry->resolvedEventId);
3243 ATRACE_NAME(message.c_str());
3244 }
3245
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003246 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3247 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3248 // Skip reporting pointer down outside focus to the policy.
3249 break;
3250 }
3251
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003252 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003253 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254
3255 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003257 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003258 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003259 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3260 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003261 break;
3262 }
Chris Yef59a2f42020-10-16 12:55:26 -07003263 case EventEntry::Type::SENSOR: {
3264 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3265 break;
3266 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003267 case EventEntry::Type::CONFIGURATION_CHANGED:
3268 case EventEntry::Type::DEVICE_RESET: {
3269 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003270 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003271 break;
3272 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273 }
3274
3275 // Remember that we are waiting for this dispatch to complete.
3276 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003277 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278 }
3279
3280 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003281 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003282 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003283}
3284
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003285/**
3286 * This function is purely for debugging. It helps us understand where the user interaction
3287 * was taking place. For example, if user is touching launcher, we will see a log that user
3288 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3289 * We will see both launcher and wallpaper in that list.
3290 * Once the interaction with a particular set of connections starts, no new logs will be printed
3291 * until the set of interacted connections changes.
3292 *
3293 * The following items are skipped, to reduce the logspam:
3294 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3295 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3296 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3297 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3298 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003299 */
3300void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3301 const std::vector<InputTarget>& targets) {
3302 // Skip ACTION_UP events, and all events other than keys and motions
3303 if (entry.type == EventEntry::Type::KEY) {
3304 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3305 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3306 return;
3307 }
3308 } else if (entry.type == EventEntry::Type::MOTION) {
3309 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3310 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3311 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3312 return;
3313 }
3314 } else {
3315 return; // Not a key or a motion
3316 }
3317
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003318 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003319 std::vector<std::shared_ptr<Connection>> newConnections;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003320 for (const InputTarget& target : targets) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003321 if (target.flags.test(InputTarget::Flags::DISPATCH_AS_OUTSIDE)) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003322 continue; // Skip windows that receive ACTION_OUTSIDE
3323 }
3324
3325 sp<IBinder> token = target.inputChannel->getConnectionToken();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003326 std::shared_ptr<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003327 if (connection == nullptr) {
3328 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003329 }
3330 newConnectionTokens.insert(std::move(token));
3331 newConnections.emplace_back(connection);
3332 }
3333 if (newConnectionTokens == mInteractionConnectionTokens) {
3334 return; // no change
3335 }
3336 mInteractionConnectionTokens = newConnectionTokens;
3337
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003338 std::string targetList;
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003339 for (const std::shared_ptr<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003340 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003341 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003342 std::string message = "Interaction with: " + targetList;
3343 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003344 message += "<none>";
3345 }
3346 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3347}
3348
chaviwfd6d3512019-03-25 13:23:49 -07003349void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003350 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003351 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003352 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3353 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003354 return;
3355 }
3356
Vishnu Nairc519ff72021-01-21 08:23:08 -08003357 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003358 if (focusedToken == token) {
3359 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003360 return;
3361 }
3362
Prabir Pradhancef936d2021-07-21 16:17:52 +00003363 auto command = [this, token]() REQUIRES(mLock) {
3364 scoped_unlock unlock(mLock);
3365 mPolicy->onPointerDownOutsideFocus(token);
3366 };
3367 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368}
3369
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003370status_t InputDispatcher::publishMotionEvent(Connection& connection,
3371 DispatchEntry& dispatchEntry) const {
3372 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3373 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3374
3375 PointerCoords scaledCoords[MAX_POINTERS];
3376 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3377
3378 // Set the X and Y offset and X and Y scale depending on the input source.
3379 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003380 !(dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS))) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003381 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3382 if (globalScaleFactor != 1.0f) {
3383 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3384 scaledCoords[i] = motionEntry.pointerCoords[i];
3385 // Don't apply window scale here since we don't want scale to affect raw
3386 // coordinates. The scale will be sent back to the client and applied
3387 // later when requesting relative coordinates.
Harry Cutts33476232023-01-30 19:57:29 +00003388 scaledCoords[i].scale(globalScaleFactor, /*windowXScale=*/1, /*windowYScale=*/1);
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003389 }
3390 usingCoords = scaledCoords;
3391 }
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003392 } else if (dispatchEntry.targetFlags.test(InputTarget::Flags::ZERO_COORDS)) {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003393 // We don't want the dispatch target to know the coordinates
3394 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3395 scaledCoords[i].clear();
3396 }
3397 usingCoords = scaledCoords;
3398 }
3399
3400 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3401
3402 // Publish the motion event.
3403 return connection.inputPublisher
3404 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3405 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3406 std::move(hmac), dispatchEntry.resolvedAction,
3407 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3408 motionEntry.edgeFlags, motionEntry.metaState,
3409 motionEntry.buttonState, motionEntry.classification,
3410 dispatchEntry.transform, motionEntry.xPrecision,
3411 motionEntry.yPrecision, motionEntry.xCursorPosition,
3412 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3413 motionEntry.downTime, motionEntry.eventTime,
3414 motionEntry.pointerCount, motionEntry.pointerProperties,
3415 usingCoords);
3416}
3417
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003419 const std::shared_ptr<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003420 if (ATRACE_ENABLED()) {
3421 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003422 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003423 ATRACE_NAME(message.c_str());
3424 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003425 if (DEBUG_DISPATCH_CYCLE) {
3426 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003429 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003430 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003432 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003433 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003434
3435 // Publish the event.
3436 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003437 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3438 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003439 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003440 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3441 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003442 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3443 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3444 << connection->getInputChannelName();
3445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003447 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003448 status = connection->inputPublisher
3449 .publishKeyEvent(dispatchEntry->seq,
3450 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3451 keyEntry.source, keyEntry.displayId,
3452 std::move(hmac), dispatchEntry->resolvedAction,
3453 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3454 keyEntry.scanCode, keyEntry.metaState,
3455 keyEntry.repeatCount, keyEntry.downTime,
3456 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003457 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458 }
3459
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003460 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08003461 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3462 LOG(DEBUG) << "Publishing " << *dispatchEntry << " to "
3463 << connection->getInputChannelName();
3464 }
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003465 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003466 break;
3467 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003468
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003469 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003470 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003471 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003472 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003473 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003474 break;
3475 }
3476
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003477 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3478 const TouchModeEntry& touchModeEntry =
3479 static_cast<const TouchModeEntry&>(eventEntry);
3480 status = connection->inputPublisher
3481 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3482 touchModeEntry.inTouchMode);
3483
3484 break;
3485 }
3486
Prabir Pradhan99987712020-11-10 18:43:05 -08003487 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3488 const auto& captureEntry =
3489 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3490 status = connection->inputPublisher
3491 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003492 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003493 break;
3494 }
3495
arthurhungb89ccb02020-12-30 16:19:01 +08003496 case EventEntry::Type::DRAG: {
3497 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3498 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3499 dragEntry.id, dragEntry.x,
3500 dragEntry.y,
3501 dragEntry.isExiting);
3502 break;
3503 }
3504
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003505 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003506 case EventEntry::Type::DEVICE_RESET:
3507 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003508 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003509 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003510 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
3513
3514 // Check the result.
3515 if (status) {
3516 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003517 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003519 "This is unexpected because the wait queue is empty, so the pipe "
3520 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003521 "event to it, status=%s(%d)",
3522 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3523 status);
Harry Cutts33476232023-01-30 19:57:29 +00003524 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525 } else {
3526 // Pipe is full and we are waiting for the app to finish process some events
3527 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003528 if (DEBUG_DISPATCH_CYCLE) {
3529 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3530 "waiting for the application to catch up",
3531 connection->getInputChannelName().c_str());
3532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 }
3534 } else {
3535 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003536 "status=%s(%d)",
3537 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3538 status);
Harry Cutts33476232023-01-30 19:57:29 +00003539 abortBrokenDispatchCycleLocked(currentTime, connection, /*notify=*/true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 }
3541 return;
3542 }
3543
3544 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003545 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3546 connection->outboundQueue.end(),
3547 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003548 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003549 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003550 if (connection->responsive) {
3551 mAnrTracker.insert(dispatchEntry->timeoutTime,
3552 connection->inputChannel->getConnectionToken());
3553 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003554 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555 }
3556}
3557
chaviw09c8d2d2020-08-24 15:48:26 -07003558std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3559 size_t size;
3560 switch (event.type) {
3561 case VerifiedInputEvent::Type::KEY: {
3562 size = sizeof(VerifiedKeyEvent);
3563 break;
3564 }
3565 case VerifiedInputEvent::Type::MOTION: {
3566 size = sizeof(VerifiedMotionEvent);
3567 break;
3568 }
3569 }
3570 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3571 return mHmacKeyManager.sign(start, size);
3572}
3573
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003574const std::array<uint8_t, 32> InputDispatcher::getSignature(
3575 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003576 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3577 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003578 // Only sign events up and down events as the purely move events
3579 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003580 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003581 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003582
3583 VerifiedMotionEvent verifiedEvent =
3584 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3585 verifiedEvent.actionMasked = actionMasked;
3586 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3587 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003588}
3589
3590const std::array<uint8_t, 32> InputDispatcher::getSignature(
3591 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3592 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3593 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3594 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003595 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003596}
3597
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003599 const std::shared_ptr<Connection>& connection,
3600 uint32_t seq, bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003601 if (DEBUG_DISPATCH_CYCLE) {
3602 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3603 connection->getInputChannelName().c_str(), seq, toString(handled));
3604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003606 if (connection->status == Connection::Status::BROKEN ||
3607 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 return;
3609 }
3610
3611 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003612 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3613 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3614 };
3615 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616}
3617
3618void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003619 const std::shared_ptr<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003620 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003621 if (DEBUG_DISPATCH_CYCLE) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07003622 LOG(DEBUG) << "channel '" << connection->getInputChannelName() << "'~ " << __func__
3623 << " - notify=" << toString(notify);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003624 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625
3626 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003627 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003628 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003629 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003630 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631
3632 // The connection appears to be unrecoverably broken.
3633 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003634 if (connection->status == Connection::Status::NORMAL) {
3635 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636
3637 if (notify) {
3638 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003639 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3640 connection->getInputChannelName().c_str());
3641
3642 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003643 scoped_unlock unlock(mLock);
3644 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3645 };
3646 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647 }
3648 }
3649}
3650
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003651void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3652 while (!queue.empty()) {
3653 DispatchEntry* dispatchEntry = queue.front();
3654 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003655 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656 }
3657}
3658
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003659void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003661 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 }
3663 delete dispatchEntry;
3664}
3665
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003666int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3667 std::scoped_lock _l(mLock);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003668 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003669 if (connection == nullptr) {
3670 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3671 connectionToken.get(), events);
3672 return 0; // remove the callback
3673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003675 bool notify;
3676 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3677 if (!(events & ALOOPER_EVENT_INPUT)) {
3678 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3679 "events=0x%x",
3680 connection->getInputChannelName().c_str(), events);
3681 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682 }
3683
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003684 nsecs_t currentTime = now();
3685 bool gotOne = false;
3686 status_t status = OK;
3687 for (;;) {
3688 Result<InputPublisher::ConsumerResponse> result =
3689 connection->inputPublisher.receiveConsumerResponse();
3690 if (!result.ok()) {
3691 status = result.error().code();
3692 break;
3693 }
3694
3695 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3696 const InputPublisher::Finished& finish =
3697 std::get<InputPublisher::Finished>(*result);
3698 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3699 finish.consumeTime);
3700 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003701 if (shouldReportMetricsForConnection(*connection)) {
3702 const InputPublisher::Timeline& timeline =
3703 std::get<InputPublisher::Timeline>(*result);
3704 mLatencyTracker
3705 .trackGraphicsLatency(timeline.inputEventId,
3706 connection->inputChannel->getConnectionToken(),
3707 std::move(timeline.graphicsTimeline));
3708 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003709 }
3710 gotOne = true;
3711 }
3712 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003713 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003714 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 return 1;
3716 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717 }
3718
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003719 notify = status != DEAD_OBJECT || !connection->monitor;
3720 if (notify) {
3721 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3722 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3723 status);
3724 }
3725 } else {
3726 // Monitor channels are never explicitly unregistered.
3727 // We do it automatically when the remote endpoint is closed so don't warn about them.
3728 const bool stillHaveWindowHandle =
3729 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3730 notify = !connection->monitor && stillHaveWindowHandle;
3731 if (notify) {
3732 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3733 connection->getInputChannelName().c_str(), events);
3734 }
3735 }
3736
3737 // Remove the channel.
3738 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3739 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740}
3741
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003742void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003744 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003745 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 }
3747}
3748
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003749void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003750 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003751 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003752 for (const Monitor& monitor : monitors) {
3753 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003754 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003755 }
3756}
3757
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003759 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003760 std::shared_ptr<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003761 if (connection == nullptr) {
3762 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003764
3765 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766}
3767
3768void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003769 const std::shared_ptr<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003770 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 return;
3772 }
3773
3774 nsecs_t currentTime = now();
3775
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003776 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003777 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003779 if (cancelationEvents.empty()) {
3780 return;
3781 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003782 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3783 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003784 "with reality: %s, mode=%s.",
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003785 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
Siarhei Vishniakou2e3e4432023-02-09 18:34:11 -08003786 ftl::enum_string(options.mode).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003787 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003788
Arthur Hungb3307ee2021-10-14 10:57:37 +00003789 std::string reason = std::string("reason=").append(options.reason);
3790 android_log_event_list(LOGTAG_INPUT_CANCEL)
3791 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3792
Svet Ganov5d3bc372020-01-26 23:11:07 -08003793 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003794 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003795 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3796 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003797 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003798 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003799 target.globalScaleFactor = windowInfo->globalScaleFactor;
3800 }
3801 target.inputChannel = connection->inputChannel;
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003802 target.flags = InputTarget::Flags::DISPATCH_AS_IS;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003803
hongzuo liu95785e22022-09-06 02:51:35 +00003804 const bool wasEmpty = connection->outboundQueue.empty();
3805
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003806 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003807 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003808 switch (cancelationEventEntry->type) {
3809 case EventEntry::Type::KEY: {
3810 logOutboundKeyDetails("cancel - ",
3811 static_cast<const KeyEntry&>(*cancelationEventEntry));
3812 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003814 case EventEntry::Type::MOTION: {
3815 logOutboundMotionDetails("cancel - ",
3816 static_cast<const MotionEntry&>(*cancelationEventEntry));
3817 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003819 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003820 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003821 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3822 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003823 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003824 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003825 break;
3826 }
3827 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003828 case EventEntry::Type::DEVICE_RESET:
3829 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003830 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003831 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003832 break;
3833 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
3835
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003836 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003837 InputTarget::Flags::DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003839
hongzuo liu95785e22022-09-06 02:51:35 +00003840 // If the outbound queue was previously empty, start the dispatch cycle going.
3841 if (wasEmpty && !connection->outboundQueue.empty()) {
3842 startDispatchCycleLocked(currentTime, connection);
3843 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844}
3845
Svet Ganov5d3bc372020-01-26 23:11:07 -08003846void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003847 const nsecs_t downTime, const std::shared_ptr<Connection>& connection,
Arthur Hungc539dbb2022-12-08 07:45:36 +00003848 ftl::Flags<InputTarget::Flags> targetFlags) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003849 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003850 return;
3851 }
3852
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003853 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003854 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003855
3856 if (downEvents.empty()) {
3857 return;
3858 }
3859
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003860 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003861 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3862 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003863 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003864
3865 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003866 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003867 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3868 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003869 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003870 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003871 target.globalScaleFactor = windowInfo->globalScaleFactor;
3872 }
3873 target.inputChannel = connection->inputChannel;
Arthur Hungc539dbb2022-12-08 07:45:36 +00003874 target.flags = targetFlags;
Svet Ganov5d3bc372020-01-26 23:11:07 -08003875
hongzuo liu95785e22022-09-06 02:51:35 +00003876 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003877 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003878 switch (downEventEntry->type) {
3879 case EventEntry::Type::MOTION: {
3880 logOutboundMotionDetails("down - ",
3881 static_cast<const MotionEntry&>(*downEventEntry));
3882 break;
3883 }
3884
3885 case EventEntry::Type::KEY:
3886 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003887 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003888 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003889 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003890 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003891 case EventEntry::Type::SENSOR:
3892 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003893 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003894 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003895 break;
3896 }
3897 }
3898
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003899 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08003900 InputTarget::Flags::DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003901 }
3902
hongzuo liu95785e22022-09-06 02:51:35 +00003903 // If the outbound queue was previously empty, start the dispatch cycle going.
3904 if (wasEmpty && !connection->outboundQueue.empty()) {
3905 startDispatchCycleLocked(downTime, connection);
3906 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003907}
3908
Arthur Hungc539dbb2022-12-08 07:45:36 +00003909void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
3910 const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
3911 if (windowHandle != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07003912 std::shared_ptr<Connection> wallpaperConnection =
3913 getConnectionLocked(windowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00003914 if (wallpaperConnection != nullptr) {
3915 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
3916 }
3917 }
3918}
3919
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003920std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003921 const MotionEntry& originalMotionEntry, std::bitset<MAX_POINTER_ID + 1> pointerIds,
3922 nsecs_t splitDownTime) {
3923 ALOG_ASSERT(pointerIds.any());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924
3925 uint32_t splitPointerIndexMap[MAX_POINTERS];
3926 PointerProperties splitPointerProperties[MAX_POINTERS];
3927 PointerCoords splitPointerCoords[MAX_POINTERS];
3928
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003929 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930 uint32_t splitPointerCount = 0;
3931
3932 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003933 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003935 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003937 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3939 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3940 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003941 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942 splitPointerCount += 1;
3943 }
3944 }
3945
3946 if (splitPointerCount != pointerIds.count()) {
3947 // This is bad. We are missing some of the pointers that we expected to deliver.
3948 // Most likely this indicates that we received an ACTION_MOVE events that has
3949 // different pointer ids than we expected based on the previous ACTION_DOWN
3950 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3951 // in this way.
3952 ALOGW("Dropping split motion event because the pointer count is %d but "
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003953 "we expected there to be %zu pointers. This probably means we received "
Siarhei Vishniakou16e4fa02023-02-16 17:48:56 -08003954 "a broken sequence of pointer ids from the input device: %s",
3955 splitPointerCount, pointerIds.count(), originalMotionEntry.getDescription().c_str());
Yi Kong9b14ac62018-07-17 13:48:38 -07003956 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 }
3958
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003959 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003961 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3962 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3964 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003965 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 uint32_t pointerId = uint32_t(pointerProperties.id);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08003967 if (pointerIds.test(pointerId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 if (pointerIds.count() == 1) {
3969 // The first/last pointer went down/up.
3970 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003971 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003972 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3973 ? AMOTION_EVENT_ACTION_CANCEL
3974 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 } else {
3976 // A secondary pointer went down/up.
3977 uint32_t splitPointerIndex = 0;
3978 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3979 splitPointerIndex += 1;
3980 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003981 action = maskedAction |
3982 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 }
3984 } else {
3985 // An unrelated pointer changed.
3986 action = AMOTION_EVENT_ACTION_MOVE;
3987 }
3988 }
3989
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003990 if (action == AMOTION_EVENT_ACTION_DOWN) {
3991 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3992 "Split motion event has mismatching downTime and eventTime for "
Siarhei Vishniakou060f82b2023-01-27 06:39:14 -08003993 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64,
3994 originalMotionEntry.getDescription().c_str(), splitDownTime);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003995 }
3996
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003997 int32_t newId = mIdGenerator.nextId();
3998 if (ATRACE_ENABLED()) {
3999 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
4000 ") to MotionEvent(id=0x%" PRIx32 ").",
4001 originalMotionEntry.id, newId);
4002 ATRACE_NAME(message.c_str());
4003 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004004 std::unique_ptr<MotionEntry> splitMotionEntry =
4005 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
4006 originalMotionEntry.deviceId, originalMotionEntry.source,
4007 originalMotionEntry.displayId,
4008 originalMotionEntry.policyFlags, action,
4009 originalMotionEntry.actionButton,
4010 originalMotionEntry.flags, originalMotionEntry.metaState,
4011 originalMotionEntry.buttonState,
4012 originalMotionEntry.classification,
4013 originalMotionEntry.edgeFlags,
4014 originalMotionEntry.xPrecision,
4015 originalMotionEntry.yPrecision,
4016 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00004017 originalMotionEntry.yCursorPosition, splitDownTime,
4018 splitPointerCount, splitPointerProperties,
4019 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07004021 if (originalMotionEntry.injectionState) {
4022 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023 splitMotionEntry->injectionState->refCount += 1;
4024 }
4025
4026 return splitMotionEntry;
4027}
4028
Prabir Pradhan678438e2023-04-13 19:32:51 +00004029void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004030 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004031 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args.eventTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033
Antonio Kantekf16f2832021-09-28 04:39:20 +00004034 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004035 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004036 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004038 std::unique_ptr<ConfigurationChangedEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004039 std::make_unique<ConfigurationChangedEntry>(args.id, args.eventTime);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004040 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041 } // release lock
4042
4043 if (needWake) {
4044 mLooper->wake();
4045 }
4046}
4047
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004048/**
4049 * If one of the meta shortcuts is detected, process them here:
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004050 * Meta + Backspace; Meta + Grave; Meta + Left arrow -> generate BACK
4051 * Most System shortcuts are handled in PhoneWindowManager.java except 'Back' shortcuts. Unlike
4052 * Back, other shortcuts DO NOT need to be sent to applications and are fully handled by the system.
4053 * But for Back key and Back shortcuts, we need to send KEYCODE_BACK to applications which can
4054 * potentially handle the back key presses.
4055 * Note: We don't send any Meta based KeyEvents to applications, so we need to convert to a KeyEvent
4056 * where meta modifier is off before sending. Currently only use case is 'Back'.
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004057 */
4058void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004059 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004060 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
4061 int32_t newKeyCode = AKEYCODE_UNKNOWN;
Vaibhav Devmurari34cd5b02023-02-23 14:51:18 +00004062 if (keyCode == AKEYCODE_DEL || keyCode == AKEYCODE_GRAVE || keyCode == AKEYCODE_DPAD_LEFT) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004063 newKeyCode = AKEYCODE_BACK;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004064 }
4065 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004066 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004067 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004068 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004069 keyCode = newKeyCode;
4070 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4071 }
4072 } else if (action == AKEY_EVENT_ACTION_UP) {
4073 // In order to maintain a consistent stream of up and down events, check to see if the key
4074 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
4075 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004076 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004077 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004078 auto replacementIt = mReplacedKeys.find(replacement);
4079 if (replacementIt != mReplacedKeys.end()) {
4080 keyCode = replacementIt->second;
4081 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05004082 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
4083 }
4084 }
4085}
4086
Prabir Pradhan678438e2023-04-13 19:32:51 +00004087void InputDispatcher::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004088 ALOGD_IF(debugInboundEventDetails(),
4089 "notifyKey - id=%" PRIx32 ", eventTime=%" PRId64
4090 ", deviceId=%d, source=%s, displayId=%" PRId32
4091 "policyFlags=0x%x, action=%s, flags=0x%x, keyCode=%s, scanCode=0x%x, metaState=0x%x, "
4092 "downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004093 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4094 args.displayId, args.policyFlags, KeyEvent::actionToString(args.action), args.flags,
4095 KeyEvent::getLabel(args.keyCode), args.scanCode, args.metaState, args.downTime);
4096 if (!validateKeyEvent(args.action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 return;
4098 }
4099
Prabir Pradhan678438e2023-04-13 19:32:51 +00004100 uint32_t policyFlags = args.policyFlags;
4101 int32_t flags = args.flags;
4102 int32_t metaState = args.metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07004103 // InputDispatcher tracks and generates key repeats on behalf of
4104 // whatever notifies it, so repeatCount should always be set to 0
4105 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
4107 policyFlags |= POLICY_FLAG_VIRTUAL;
4108 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
4109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 if (policyFlags & POLICY_FLAG_FUNCTION) {
4111 metaState |= AMETA_FUNCTION_ON;
4112 }
4113
4114 policyFlags |= POLICY_FLAG_TRUSTED;
4115
Prabir Pradhan678438e2023-04-13 19:32:51 +00004116 int32_t keyCode = args.keyCode;
4117 accelerateMetaShortcuts(args.deviceId, args.action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07004118
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 KeyEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004120 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC, args.action,
4121 flags, keyCode, args.scanCode, metaState, repeatCount, args.downTime,
4122 args.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123
Michael Wright2b3c3302018-03-02 17:19:13 +00004124 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004126 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4127 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004128 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130
Antonio Kantekf16f2832021-09-28 04:39:20 +00004131 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 { // acquire lock
4133 mLock.lock();
4134
4135 if (shouldSendKeyToInputFilterLocked(args)) {
4136 mLock.unlock();
4137
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004138 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4140 return; // event was consumed by the filter
4141 }
4142
4143 mLock.lock();
4144 }
4145
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004146 std::unique_ptr<KeyEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004147 std::make_unique<KeyEntry>(args.id, args.eventTime, args.deviceId, args.source,
4148 args.displayId, policyFlags, args.action, flags, keyCode,
4149 args.scanCode, metaState, repeatCount, args.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004151 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 mLock.unlock();
4153 } // release lock
4154
4155 if (needWake) {
4156 mLooper->wake();
4157 }
4158}
4159
Prabir Pradhan678438e2023-04-13 19:32:51 +00004160bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs& args) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 return mInputFilterEnabled;
4162}
4163
Prabir Pradhan678438e2023-04-13 19:32:51 +00004164void InputDispatcher::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004165 if (debugInboundEventDetails()) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004166 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=%s, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004167 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004168 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004169 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4170 "yCursorPosition=%f, downTime=%" PRId64,
Prabir Pradhan678438e2023-04-13 19:32:51 +00004171 args.id, args.eventTime, args.deviceId, inputEventSourceToString(args.source).c_str(),
4172 args.displayId, args.policyFlags, MotionEvent::actionToString(args.action).c_str(),
4173 args.actionButton, args.flags, args.metaState, args.buttonState, args.edgeFlags,
4174 args.xPrecision, args.yPrecision, args.xCursorPosition, args.yCursorPosition,
4175 args.downTime);
4176 for (uint32_t i = 0; i < args.pointerCount; i++) {
Prabir Pradhan96282b02023-02-24 22:36:17 +00004177 ALOGD(" Pointer %d: id=%d, toolType=%s, x=%f, y=%f, pressure=%f, size=%f, "
4178 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, orientation=%f",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004179 i, args.pointerProperties[i].id,
4180 ftl::enum_string(args.pointerProperties[i].toolType).c_str(),
4181 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4182 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4183 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4184 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4185 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4186 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4187 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4188 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4189 args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 }
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004192
Prabir Pradhan678438e2023-04-13 19:32:51 +00004193 if (!validateMotionEvent(args.action, args.actionButton, args.pointerCount,
4194 args.pointerProperties)) {
4195 LOG(ERROR) << "Invalid event: " << args.dump();
Siarhei Vishniakou4ca97272023-03-01 11:31:35 -08004196 return;
4197 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198
Prabir Pradhan678438e2023-04-13 19:32:51 +00004199 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004201
4202 android::base::Timer t;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004203 mPolicy->interceptMotionBeforeQueueing(args.displayId, args.eventTime, policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004204 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4205 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004206 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208
Antonio Kantekf16f2832021-09-28 04:39:20 +00004209 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 { // acquire lock
4211 mLock.lock();
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004212 if (!(policyFlags & POLICY_FLAG_PASS_TO_USER)) {
4213 // Set the flag anyway if we already have an ongoing gesture. That would allow us to
4214 // complete the processing of the current stroke.
Prabir Pradhan678438e2023-04-13 19:32:51 +00004215 const auto touchStateIt = mTouchStatesByDisplay.find(args.displayId);
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004216 if (touchStateIt != mTouchStatesByDisplay.end()) {
4217 const TouchState& touchState = touchStateIt->second;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004218 if (touchState.deviceId == args.deviceId && touchState.isDown()) {
Siarhei Vishniakou5bf25d92023-02-08 15:43:38 -08004219 policyFlags |= POLICY_FLAG_PASS_TO_USER;
4220 }
4221 }
4222 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223
4224 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004225 ui::Transform displayTransform;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004226 if (const auto it = mDisplayInfos.find(args.displayId); it != mDisplayInfos.end()) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004227 displayTransform = it->second.transform;
4228 }
4229
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230 mLock.unlock();
4231
4232 MotionEvent event;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004233 event.initialize(args.id, args.deviceId, args.source, args.displayId, INVALID_HMAC,
4234 args.action, args.actionButton, args.flags, args.edgeFlags,
4235 args.metaState, args.buttonState, args.classification,
4236 displayTransform, args.xPrecision, args.yPrecision,
4237 args.xCursorPosition, args.yCursorPosition, displayTransform,
4238 args.downTime, args.eventTime, args.pointerCount,
4239 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240
4241 policyFlags |= POLICY_FLAG_FILTERED;
4242 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4243 return; // event was consumed by the filter
4244 }
4245
4246 mLock.lock();
4247 }
4248
4249 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004250 std::unique_ptr<MotionEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004251 std::make_unique<MotionEntry>(args.id, args.eventTime, args.deviceId, args.source,
4252 args.displayId, policyFlags, args.action,
4253 args.actionButton, args.flags, args.metaState,
4254 args.buttonState, args.classification, args.edgeFlags,
4255 args.xPrecision, args.yPrecision,
4256 args.xCursorPosition, args.yCursorPosition,
4257 args.downTime, args.pointerCount,
4258 args.pointerProperties, args.pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259
Prabir Pradhan678438e2023-04-13 19:32:51 +00004260 if (args.id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4261 IdGenerator::getSource(args.id) == IdGenerator::Source::INPUT_READER &&
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004262 !mInputFilterEnabled) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004263 const bool isDown = args.action == AMOTION_EVENT_ACTION_DOWN;
4264 mLatencyTracker.trackListener(args.id, isDown, args.eventTime, args.readTime);
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004265 }
4266
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004267 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 mLock.unlock();
4269 } // release lock
4270
4271 if (needWake) {
4272 mLooper->wake();
4273 }
4274}
4275
Prabir Pradhan678438e2023-04-13 19:32:51 +00004276void InputDispatcher::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004277 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004278 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4279 " sensorType=%s",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004280 args.id, args.eventTime, args.deviceId, args.source,
4281 ftl::enum_string(args.sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004282 }
Chris Yef59a2f42020-10-16 12:55:26 -07004283
Antonio Kantekf16f2832021-09-28 04:39:20 +00004284 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004285 { // acquire lock
4286 mLock.lock();
4287
4288 // Just enqueue a new sensor event.
4289 std::unique_ptr<SensorEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004290 std::make_unique<SensorEntry>(args.id, args.eventTime, args.deviceId, args.source,
4291 /* policyFlags=*/0, args.hwTimestamp, args.sensorType,
4292 args.accuracy, args.accuracyChanged, args.values);
Chris Yef59a2f42020-10-16 12:55:26 -07004293
4294 needWake = enqueueInboundEventLocked(std::move(newEntry));
4295 mLock.unlock();
4296 } // release lock
4297
4298 if (needWake) {
4299 mLooper->wake();
4300 }
4301}
4302
Prabir Pradhan678438e2023-04-13 19:32:51 +00004303void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004304 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004305 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args.eventTime,
4306 args.deviceId, args.isOn);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004307 }
Prabir Pradhan678438e2023-04-13 19:32:51 +00004308 mPolicy->notifyVibratorState(args.deviceId, args.isOn);
Chris Yefb552902021-02-03 17:18:37 -08004309}
4310
Prabir Pradhan678438e2023-04-13 19:32:51 +00004311bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs& args) {
Jackal Guof9696682018-10-05 12:23:23 +08004312 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313}
4314
Prabir Pradhan678438e2023-04-13 19:32:51 +00004315void InputDispatcher::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004316 if (debugInboundEventDetails()) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004317 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4318 "switchMask=0x%08x",
Prabir Pradhan678438e2023-04-13 19:32:51 +00004319 args.eventTime, args.policyFlags, args.switchValues, args.switchMask);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321
Prabir Pradhan678438e2023-04-13 19:32:51 +00004322 uint32_t policyFlags = args.policyFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 policyFlags |= POLICY_FLAG_TRUSTED;
Prabir Pradhan678438e2023-04-13 19:32:51 +00004324 mPolicy->notifySwitch(args.eventTime, args.switchValues, args.switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325}
4326
Prabir Pradhan678438e2023-04-13 19:32:51 +00004327void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004328 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004329 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args.eventTime,
4330 args.deviceId);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332
Antonio Kantekf16f2832021-09-28 04:39:20 +00004333 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004335 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004337 std::unique_ptr<DeviceResetEntry> newEntry =
Prabir Pradhan678438e2023-04-13 19:32:51 +00004338 std::make_unique<DeviceResetEntry>(args.id, args.eventTime, args.deviceId);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004339 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 } // release lock
4341
4342 if (needWake) {
4343 mLooper->wake();
4344 }
4345}
4346
Prabir Pradhan678438e2023-04-13 19:32:51 +00004347void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004348 if (debugInboundEventDetails()) {
Prabir Pradhan678438e2023-04-13 19:32:51 +00004349 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args.eventTime,
4350 args.request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004351 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004352
Antonio Kantekf16f2832021-09-28 04:39:20 +00004353 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004354 { // acquire lock
4355 std::scoped_lock _l(mLock);
Prabir Pradhan678438e2023-04-13 19:32:51 +00004356 auto entry =
4357 std::make_unique<PointerCaptureChangedEntry>(args.id, args.eventTime, args.request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004358 needWake = enqueueInboundEventLocked(std::move(entry));
4359 } // release lock
4360
4361 if (needWake) {
4362 mLooper->wake();
4363 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004364}
4365
Prabir Pradhan5735a322022-04-11 17:23:34 +00004366InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4367 std::optional<int32_t> targetUid,
4368 InputEventInjectionSync syncMode,
4369 std::chrono::milliseconds timeout,
4370 uint32_t policyFlags) {
Prabir Pradhan65613802023-02-22 23:36:58 +00004371 if (debugInboundEventDetails()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004372 LOG(DEBUG) << __func__ << ": targetUid=" << toString(targetUid)
4373 << ", syncMode=" << ftl::enum_string(syncMode) << ", timeout=" << timeout.count()
4374 << "ms, policyFlags=0x" << std::hex << policyFlags << std::dec
4375 << ", event=" << *event;
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004376 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004377 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378
Prabir Pradhan5735a322022-04-11 17:23:34 +00004379 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004381 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004382 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4383 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4384 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4385 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4386 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004387 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004388 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004389 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004390 }
4391
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004392 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 switch (event->getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004394 case InputEventType::KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004395 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4396 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004397 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004398 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004401 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004402 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4403 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4404 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004405 int32_t keyCode = incomingKey.getKeyCode();
4406 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004407 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004408 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004409 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004410 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004411 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4412 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4413 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004415 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4416 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004417 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004418
4419 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4420 android::base::Timer t;
4421 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4422 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4423 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4424 std::to_string(t.duration().count()).c_str());
4425 }
4426 }
4427
4428 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004429 std::unique_ptr<KeyEntry> injectedEntry =
4430 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004431 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004432 incomingKey.getDisplayId(), policyFlags, action,
4433 flags, keyCode, incomingKey.getScanCode(), metaState,
4434 incomingKey.getRepeatCount(),
4435 incomingKey.getDownTime());
4436 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004437 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438 }
4439
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004440 case InputEventType::MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004441 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004442 const int32_t action = motionEvent.getAction();
4443 const bool isPointerEvent =
4444 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4445 // If a pointer event has no displayId specified, inject it to the default display.
4446 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4447 ? ADISPLAY_ID_DEFAULT
4448 : event->getDisplayId();
4449 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004450 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004451 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004452 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004453 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004454 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004455 }
4456
4457 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004458 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004459 android::base::Timer t;
4460 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4461 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4462 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4463 std::to_string(t.duration().count()).c_str());
4464 }
4465 }
4466
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004467 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4468 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4469 }
4470
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004471 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004472 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4473 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004474 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004475 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4476 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004477 displayId, policyFlags, action, actionButton,
4478 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004479 motionEvent.getButtonState(),
4480 motionEvent.getClassification(),
4481 motionEvent.getEdgeFlags(),
4482 motionEvent.getXPrecision(),
4483 motionEvent.getYPrecision(),
4484 motionEvent.getRawXCursorPosition(),
4485 motionEvent.getRawYCursorPosition(),
4486 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004487 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004488 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004489 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004490 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004491 sampleEventTimes += 1;
4492 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004493 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004494 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4495 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004496 displayId, policyFlags, action, actionButton,
4497 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004498 motionEvent.getButtonState(),
4499 motionEvent.getClassification(),
4500 motionEvent.getEdgeFlags(),
4501 motionEvent.getXPrecision(),
4502 motionEvent.getYPrecision(),
4503 motionEvent.getRawXCursorPosition(),
4504 motionEvent.getRawYCursorPosition(),
4505 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004506 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004507 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004508 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4509 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004510 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004511 }
4512 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004515 default:
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004516 LOG(WARNING) << "Cannot inject " << ftl::enum_string(event->getType()) << " events";
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004517 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 }
4519
Prabir Pradhan5735a322022-04-11 17:23:34 +00004520 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004521 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522 injectionState->injectionIsAsync = true;
4523 }
4524
4525 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004526 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527
4528 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004529 while (!injectedEntries.empty()) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004530 if (DEBUG_INJECTION) {
4531 LOG(DEBUG) << "Injecting " << injectedEntries.front()->getDescription();
4532 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004533 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004534 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535 }
4536
4537 mLock.unlock();
4538
4539 if (needWake) {
4540 mLooper->wake();
4541 }
4542
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004543 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004545 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004547 if (syncMode == InputEventInjectionSync::NONE) {
4548 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 } else {
4550 for (;;) {
4551 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004552 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 break;
4554 }
4555
4556 nsecs_t remainingTimeout = endTime - now();
4557 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004558 if (DEBUG_INJECTION) {
4559 ALOGD("injectInputEvent - Timed out waiting for injection result "
4560 "to become available.");
4561 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004562 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 break;
4564 }
4565
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004566 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567 }
4568
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004569 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4570 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004571 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004572 if (DEBUG_INJECTION) {
4573 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4574 injectionState->pendingForegroundDispatches);
4575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576 nsecs_t remainingTimeout = endTime - now();
4577 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004578 if (DEBUG_INJECTION) {
4579 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4580 "dispatches to finish.");
4581 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004582 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583 break;
4584 }
4585
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004586 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 }
4588 }
4589 }
4590
4591 injectionState->release();
4592 } // release lock
4593
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004594 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004595 LOG(DEBUG) << "injectInputEvent - Finished with result "
4596 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004597 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598
4599 return injectionResult;
4600}
4601
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004602std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004603 std::array<uint8_t, 32> calculatedHmac;
4604 std::unique_ptr<VerifiedInputEvent> result;
4605 switch (event.getType()) {
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004606 case InputEventType::KEY: {
Gang Wange9087892020-01-07 12:17:14 -05004607 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4608 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4609 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004610 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004611 break;
4612 }
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07004613 case InputEventType::MOTION: {
Gang Wange9087892020-01-07 12:17:14 -05004614 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4615 VerifiedMotionEvent verifiedMotionEvent =
4616 verifiedMotionEventFromMotionEvent(motionEvent);
4617 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004618 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004619 break;
4620 }
4621 default: {
4622 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4623 return nullptr;
4624 }
4625 }
4626 if (calculatedHmac == INVALID_HMAC) {
4627 return nullptr;
4628 }
tyiu1573a672023-02-21 22:38:32 +00004629 if (0 != CRYPTO_memcmp(calculatedHmac.data(), event.getHmac().data(), calculatedHmac.size())) {
Gang Wange9087892020-01-07 12:17:14 -05004630 return nullptr;
4631 }
4632 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004633}
4634
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004635void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004636 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004637 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004639 if (DEBUG_INJECTION) {
Siarhei Vishniakoud010b012023-01-18 15:00:53 -08004640 LOG(DEBUG) << "Setting input event injection result to "
4641 << ftl::enum_string(injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004644 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 // Log the outcome since the injector did not wait for the injection result.
4646 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004647 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004648 ALOGV("Asynchronous input event injection succeeded.");
4649 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004650 case InputEventInjectionResult::TARGET_MISMATCH:
4651 ALOGV("Asynchronous input event injection target mismatch.");
4652 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004653 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004654 ALOGW("Asynchronous input event injection failed.");
4655 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004656 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004657 ALOGW("Asynchronous input event injection timed out.");
4658 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004659 case InputEventInjectionResult::PENDING:
4660 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4661 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662 }
4663 }
4664
4665 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004666 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667 }
4668}
4669
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004670void InputDispatcher::transformMotionEntryForInjectionLocked(
4671 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004672 // Input injection works in the logical display coordinate space, but the input pipeline works
4673 // display space, so we need to transform the injected events accordingly.
4674 const auto it = mDisplayInfos.find(entry.displayId);
4675 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004676 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004677
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004678 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4679 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4680 const vec2 cursor =
4681 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4682 {entry.xCursorPosition, entry.yCursorPosition});
4683 entry.xCursorPosition = cursor.x;
4684 entry.yCursorPosition = cursor.y;
4685 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004686 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004687 entry.pointerCoords[i] =
4688 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4689 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004690 }
4691}
4692
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004693void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4694 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695 if (injectionState) {
4696 injectionState->pendingForegroundDispatches += 1;
4697 }
4698}
4699
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004700void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4701 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 if (injectionState) {
4703 injectionState->pendingForegroundDispatches -= 1;
4704
4705 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004706 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 }
4708 }
4709}
4710
chaviw98318de2021-05-19 16:45:23 -05004711const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004712 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004713 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004714 auto it = mWindowHandlesByDisplay.find(displayId);
4715 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004716}
4717
chaviw98318de2021-05-19 16:45:23 -05004718sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004719 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004720 if (windowHandleToken == nullptr) {
4721 return nullptr;
4722 }
4723
Arthur Hungb92218b2018-08-14 12:00:21 +08004724 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004725 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4726 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004727 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004728 return windowHandle;
4729 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730 }
4731 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004732 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733}
4734
chaviw98318de2021-05-19 16:45:23 -05004735sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4736 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004737 if (windowHandleToken == nullptr) {
4738 return nullptr;
4739 }
4740
chaviw98318de2021-05-19 16:45:23 -05004741 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004742 if (windowHandle->getToken() == windowHandleToken) {
4743 return windowHandle;
4744 }
4745 }
4746 return nullptr;
4747}
4748
chaviw98318de2021-05-19 16:45:23 -05004749sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4750 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004751 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004752 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4753 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004754 if (handle->getId() == windowHandle->getId() &&
4755 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004756 if (windowHandle->getInfo()->displayId != it.first) {
4757 ALOGE("Found window %s in display %" PRId32
4758 ", but it should belong to display %" PRId32,
4759 windowHandle->getName().c_str(), it.first,
4760 windowHandle->getInfo()->displayId);
4761 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004762 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004764 }
4765 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004766 return nullptr;
4767}
4768
chaviw98318de2021-05-19 16:45:23 -05004769sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004770 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4771 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772}
4773
Prabir Pradhan33e3baa2022-12-06 20:30:22 +00004774ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4775 auto displayInfoIt = mDisplayInfos.find(displayId);
4776 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4777 : kIdentityTransform;
4778}
4779
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004780bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4781 const MotionEntry& motionEntry) const {
4782 const WindowInfo& info = *window->getInfo();
4783
4784 // Skip spy window targets that are not valid for targeted injection.
4785 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004786 return false;
4787 }
4788
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004789 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4790 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4791 return false;
4792 }
4793
4794 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4795 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4796 window->getName().c_str());
4797 return false;
4798 }
4799
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07004800 std::shared_ptr<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004801 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004802 ALOGW("Not sending touch to %s because there's no corresponding connection",
4803 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004804 return false;
4805 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004806
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004807 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004808 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004809 return false;
4810 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004811
4812 // Drop events that can't be trusted due to occlusion
4813 const auto [x, y] = resolveTouchedPosition(motionEntry);
4814 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4815 if (!isTouchTrustedLocked(occlusionInfo)) {
4816 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhan82e081e2022-12-06 09:50:09 +00004817 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x, y);
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004818 for (const auto& log : occlusionInfo.debugInfo) {
4819 ALOGD("%s", log.c_str());
4820 }
4821 }
4822 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4823 occlusionInfo.obscuringUid);
4824 return false;
4825 }
4826
4827 // Drop touch events if requested by input feature
4828 if (shouldDropInput(motionEntry, window)) {
4829 return false;
4830 }
4831
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004832 return true;
4833}
4834
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004835std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4836 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004837 auto connectionIt = mConnectionsByToken.find(token);
4838 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004839 return nullptr;
4840 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004841 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004842}
4843
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004844void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004845 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4846 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004847 // Remove all handles on a display if there are no windows left.
4848 mWindowHandlesByDisplay.erase(displayId);
4849 return;
4850 }
4851
4852 // Since we compare the pointer of input window handles across window updates, we need
4853 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004854 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4855 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4856 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004857 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004858 }
4859
chaviw98318de2021-05-19 16:45:23 -05004860 std::vector<sp<WindowInfoHandle>> newHandles;
4861 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004862 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004863 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004864 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004865 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004866 const bool canReceiveInput =
4867 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4868 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004869 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004870 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004871 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004872 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004873 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004874 }
4875
4876 if (info->displayId != displayId) {
4877 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4878 handle->getName().c_str(), displayId, info->displayId);
4879 continue;
4880 }
4881
Robert Carredd13602020-04-13 17:24:34 -07004882 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4883 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004884 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004885 oldHandle->updateFrom(handle);
4886 newHandles.push_back(oldHandle);
4887 } else {
4888 newHandles.push_back(handle);
4889 }
4890 }
4891
4892 // Insert or replace
4893 mWindowHandlesByDisplay[displayId] = newHandles;
4894}
4895
Arthur Hung72d8dc32020-03-28 00:48:39 +00004896void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004897 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004898 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004899 { // acquire lock
4900 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004901 for (const auto& [displayId, handles] : handlesPerDisplay) {
4902 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004903 }
4904 }
4905 // Wake up poll loop since it may need to make new input dispatching choices.
4906 mLooper->wake();
4907}
4908
Arthur Hungb92218b2018-08-14 12:00:21 +08004909/**
4910 * Called from InputManagerService, update window handle list by displayId that can receive input.
4911 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4912 * If set an empty list, remove all handles from the specific display.
4913 * For focused handle, check if need to change and send a cancel event to previous one.
4914 * For removed handle, check if need to send a cancel event if already in touch.
4915 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004916void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004917 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004918 if (DEBUG_FOCUS) {
4919 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004920 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004921 windowList += iwh->getName() + " ";
4922 }
4923 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925
Prabir Pradhand65552b2021-10-07 11:23:50 -07004926 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004927 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004928 const WindowInfo& info = *window->getInfo();
4929
4930 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004931 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004932 if (noInputWindow && window->getToken() != nullptr) {
4933 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4934 window->getName().c_str());
4935 window->releaseChannel();
4936 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004937
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004938 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004939 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4940 !info.inputConfig.test(
4941 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004942 "%s has feature SPY, but is not a trusted overlay.",
4943 window->getName().c_str());
4944
Prabir Pradhand65552b2021-10-07 11:23:50 -07004945 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004946 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4947 !info.inputConfig.test(
4948 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004949 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4950 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004951 }
4952
Arthur Hung72d8dc32020-03-28 00:48:39 +00004953 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004954 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004956 // Save the old windows' orientation by ID before it gets updated.
4957 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004958 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004959 oldWindowOrientations.emplace(handle->getId(),
4960 handle->getInfo()->transform.getOrientation());
4961 }
4962
chaviw98318de2021-05-19 16:45:23 -05004963 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004964
chaviw98318de2021-05-19 16:45:23 -05004965 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004966
Vishnu Nairc519ff72021-01-21 08:23:08 -08004967 std::optional<FocusResolver::FocusChanges> changes =
4968 mFocusResolver.setInputWindows(displayId, windowHandles);
4969 if (changes) {
4970 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004973 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4974 mTouchStatesByDisplay.find(displayId);
4975 if (stateIt != mTouchStatesByDisplay.end()) {
4976 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004977 for (size_t i = 0; i < state.windows.size();) {
4978 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004979 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004980 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004981 ALOGD("Touched window was removed: %s in display %" PRId32,
4982 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004983 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004984 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004985 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4986 if (touchedInputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00004987 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hung72d8dc32020-03-28 00:48:39 +00004988 "touched window was removed");
4989 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004990 // Since we are about to drop the touch, cancel the events for the wallpaper as
4991 // well.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08004992 if (touchedWindow.targetFlags.test(InputTarget::Flags::FOREGROUND) &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004993 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4994 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004995 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
Arthur Hungc539dbb2022-12-08 07:45:36 +00004996 synthesizeCancelationEventsForWindowLocked(wallpaper, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004999 state.windows.erase(state.windows.begin() + i);
5000 } else {
5001 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002 }
5003 }
arthurhungb89ccb02020-12-30 16:19:01 +08005004
arthurhung6d4bed92021-03-17 11:59:33 +08005005 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08005006 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00005007 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08005008 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08005009 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00005010 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
5011 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08005012 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08005013 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005014 }
Arthur Hung25e2af12020-03-26 12:58:37 +00005015
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005016 // Determine if the orientation of any of the input windows have changed, and cancel all
5017 // pointer events if necessary.
5018 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
5019 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
5020 if (newWindowHandle != nullptr &&
5021 newWindowHandle->getInfo()->transform.getOrientation() !=
5022 oldWindowOrientations[oldWindowHandle->getId()]) {
5023 std::shared_ptr<InputChannel> inputChannel =
5024 getInputChannelLocked(newWindowHandle->getToken());
5025 if (inputChannel != nullptr) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00005026 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00005027 "touched window's orientation changed");
5028 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07005029 }
5030 }
5031 }
5032
Arthur Hung72d8dc32020-03-28 00:48:39 +00005033 // Release information for windows that are no longer present.
5034 // This ensures that unused input channels are released promptly.
5035 // Otherwise, they might stick around until the window handle is destroyed
5036 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05005037 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07005038 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00005039 if (DEBUG_FOCUS) {
5040 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00005041 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00005042 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00005043 }
chaviw291d88a2019-02-14 10:33:58 -08005044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005045}
5046
5047void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07005048 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005049 if (DEBUG_FOCUS) {
5050 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
5051 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
5052 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05005053 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005054 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07005055 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005056 } // release lock
5057
5058 // Wake up poll loop since it may need to make new input dispatching choices.
5059 mLooper->wake();
5060}
5061
Vishnu Nair599f1412021-06-21 10:39:58 -07005062void InputDispatcher::setFocusedApplicationLocked(
5063 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
5064 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
5065 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
5066
5067 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
5068 return; // This application is already focused. No need to wake up or change anything.
5069 }
5070
5071 // Set the new application handle.
5072 if (inputApplicationHandle != nullptr) {
5073 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
5074 } else {
5075 mFocusedApplicationHandlesByDisplay.erase(displayId);
5076 }
5077
5078 // No matter what the old focused application was, stop waiting on it because it is
5079 // no longer focused.
5080 resetNoFocusedWindowTimeoutLocked();
5081}
5082
Tiger Huang721e26f2018-07-24 22:26:19 +08005083/**
5084 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
5085 * the display not specified.
5086 *
5087 * We track any unreleased events for each window. If a window loses the ability to receive the
5088 * released event, we will send a cancel event to it. So when the focused display is changed, we
5089 * cancel all the unreleased display-unspecified events for the focused window on the old focused
5090 * display. The display-specified events won't be affected.
5091 */
5092void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005093 if (DEBUG_FOCUS) {
5094 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
5095 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005096 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005097 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08005098
5099 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005100 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08005101 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005102 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005103 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07005104 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08005105 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005106 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005107 options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005108 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00005109 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08005110 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
5111 }
5112 }
5113 mFocusedDisplayId = displayId;
5114
Chris Ye3c2d6f52020-08-09 10:39:48 -07005115 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08005116 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005117 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08005118
Vishnu Nairad321cd2020-08-20 16:40:21 -07005119 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08005120 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08005121 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005122 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08005123 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08005124 }
5125 }
5126 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005127 } // release lock
5128
5129 // Wake up poll loop since it may need to make new input dispatching choices.
5130 mLooper->wake();
5131}
5132
Michael Wrightd02c5b62014-02-10 15:10:22 -08005133void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005134 if (DEBUG_FOCUS) {
5135 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
5136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137
5138 bool changed;
5139 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005140 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141
5142 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5143 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005144 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 }
5146
5147 if (mDispatchEnabled && !enabled) {
5148 resetAndDropEverythingLocked("dispatcher is being disabled");
5149 }
5150
5151 mDispatchEnabled = enabled;
5152 mDispatchFrozen = frozen;
5153 changed = true;
5154 } else {
5155 changed = false;
5156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 } // release lock
5158
5159 if (changed) {
5160 // Wake up poll loop since it may need to make new input dispatching choices.
5161 mLooper->wake();
5162 }
5163}
5164
5165void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005166 if (DEBUG_FOCUS) {
5167 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5168 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169
5170 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005171 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172
5173 if (mInputFilterEnabled == enabled) {
5174 return;
5175 }
5176
5177 mInputFilterEnabled = enabled;
5178 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5179 } // release lock
5180
5181 // Wake up poll loop since there might be work to do to drop everything.
5182 mLooper->wake();
5183}
5184
Antonio Kanteka042c022022-07-06 16:51:07 -07005185bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5186 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005187 bool needWake = false;
5188 {
5189 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005190 ALOGD_IF(DEBUG_TOUCH_MODE,
5191 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5192 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5193 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5194 mTouchModePerDisplay.count(displayId) == 0
5195 ? "not set"
5196 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5197
Antonio Kantek15beb512022-06-13 22:35:41 +00005198 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5199 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005200 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005201 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005202 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005203 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5204 !recentWindowsAreOwnedByLocked(pid, uid)) {
5205 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5206 "window nor none of the previously interacted window",
5207 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005208 return false;
5209 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005210 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005211 mTouchModePerDisplay[displayId] = inTouchMode;
5212 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5213 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005214 needWake = enqueueInboundEventLocked(std::move(entry));
5215 } // release lock
5216
5217 if (needWake) {
5218 mLooper->wake();
5219 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005220 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005221}
5222
Antonio Kantek48710e42022-03-24 14:19:30 -07005223bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5224 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5225 if (focusedToken == nullptr) {
5226 return false;
5227 }
5228 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5229 return isWindowOwnedBy(windowHandle, pid, uid);
5230}
5231
5232bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5233 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5234 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5235 const sp<WindowInfoHandle> windowHandle =
5236 getWindowHandleLocked(connectionToken);
5237 return isWindowOwnedBy(windowHandle, pid, uid);
5238 }) != mInteractionConnectionTokens.end();
5239}
5240
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005241void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5242 if (opacity < 0 || opacity > 1) {
5243 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5244 return;
5245 }
5246
5247 std::scoped_lock lock(mLock);
5248 mMaximumObscuringOpacityForTouch = opacity;
5249}
5250
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005251std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5252InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005253 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5254 for (TouchedWindow& w : state.windows) {
5255 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005256 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005257 }
5258 }
5259 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005260 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005261}
5262
arthurhungb89ccb02020-12-30 16:19:01 +08005263bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5264 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005265 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005266 if (DEBUG_FOCUS) {
5267 ALOGD("Trivial transfer to same window.");
5268 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005269 return true;
5270 }
5271
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005273 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274
Arthur Hungabbb9d82021-09-01 14:52:30 +00005275 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005276 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005277 if (state == nullptr || touchedWindow == nullptr) {
5278 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279 return false;
5280 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005281
Arthur Hungabbb9d82021-09-01 14:52:30 +00005282 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5283 if (toWindowHandle == nullptr) {
5284 ALOGW("Cannot transfer focus because to window not found.");
5285 return false;
5286 }
5287
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005288 if (DEBUG_FOCUS) {
5289 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005290 touchedWindow->windowHandle->getName().c_str(),
5291 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005292 }
5293
Arthur Hungabbb9d82021-09-01 14:52:30 +00005294 // Erase old window.
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005295 ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005296 std::bitset<MAX_POINTER_ID + 1> pointerIds = touchedWindow->pointerIds;
Arthur Hungc539dbb2022-12-08 07:45:36 +00005297 sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
Arthur Hungabbb9d82021-09-01 14:52:30 +00005298 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299
Arthur Hungabbb9d82021-09-01 14:52:30 +00005300 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005301 nsecs_t downTimeInTarget = now();
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005302 ftl::Flags<InputTarget::Flags> newTargetFlags =
5303 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005304 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005305 newTargetFlags |= InputTarget::Flags::FOREGROUND;
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005306 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005307 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308
Arthur Hungabbb9d82021-09-01 14:52:30 +00005309 // Store the dragging window.
5310 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005311 if (pointerIds.count() != 1) {
5312 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5313 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005314 return false;
5315 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005316 // Track the pointer id for drag window and generate the drag state.
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005317 const size_t id = firstMarkedBit(pointerIds);
Arthur Hung54745652022-04-20 07:17:41 +00005318 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319 }
5320
Arthur Hungabbb9d82021-09-01 14:52:30 +00005321 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005322 std::shared_ptr<Connection> fromConnection = getConnectionLocked(fromToken);
5323 std::shared_ptr<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005324 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005325 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005326 CancelationOptions
Michael Wrightfb04fd52022-11-24 22:31:11 +00005327 options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005328 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Arthur Hungc539dbb2022-12-08 07:45:36 +00005330 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
5331 newTargetFlags);
5332
5333 // Check if the wallpaper window should deliver the corresponding event.
5334 transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
5335 *state, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337 } // release lock
5338
5339 // Wake up poll loop since it may need to make new input dispatching choices.
5340 mLooper->wake();
5341 return true;
5342}
5343
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005344/**
5345 * Get the touched foreground window on the given display.
5346 * Return null if there are no windows touched on that display, or if more than one foreground
5347 * window is being touched.
5348 */
5349sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5350 auto stateIt = mTouchStatesByDisplay.find(displayId);
5351 if (stateIt == mTouchStatesByDisplay.end()) {
5352 ALOGI("No touch state on display %" PRId32, displayId);
5353 return nullptr;
5354 }
5355
5356 const TouchState& state = stateIt->second;
5357 sp<WindowInfoHandle> touchedForegroundWindow;
5358 // If multiple foreground windows are touched, return nullptr
5359 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakou253f4642022-11-09 13:42:06 -08005360 if (window.targetFlags.test(InputTarget::Flags::FOREGROUND)) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005361 if (touchedForegroundWindow != nullptr) {
5362 ALOGI("Two or more foreground windows: %s and %s",
5363 touchedForegroundWindow->getName().c_str(),
5364 window.windowHandle->getName().c_str());
5365 return nullptr;
5366 }
5367 touchedForegroundWindow = window.windowHandle;
5368 }
5369 }
5370 return touchedForegroundWindow;
5371}
5372
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005373// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005374bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005375 sp<IBinder> fromToken;
5376 { // acquire lock
5377 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005378 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005379 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005380 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5381 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005382 return false;
5383 }
5384
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005385 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5386 if (from == nullptr) {
5387 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5388 return false;
5389 }
5390
5391 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005392 } // release lock
5393
5394 return transferTouchFocus(fromToken, destChannelToken);
5395}
5396
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005398 if (DEBUG_FOCUS) {
5399 ALOGD("Resetting and dropping all events (%s).", reason);
5400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401
Michael Wrightfb04fd52022-11-24 22:31:11 +00005402 CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403 synthesizeCancelationEventsForAllConnectionsLocked(options);
5404
5405 resetKeyRepeatLocked();
5406 releasePendingEventLocked();
5407 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005408 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005409
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005410 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005411 mTouchStatesByDisplay.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005412 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413}
5414
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005415void InputDispatcher::logDispatchStateLocked() const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005416 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005417 dumpDispatchStateLocked(dump);
5418
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005419 std::istringstream stream(dump);
5420 std::string line;
5421
5422 while (std::getline(stream, line, '\n')) {
5423 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 }
5425}
5426
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005427std::string InputDispatcher::dumpPointerCaptureStateLocked() const {
Prabir Pradhan99987712020-11-10 18:43:05 -08005428 std::string dump;
5429
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005430 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5431 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005432
5433 std::string windowName = "None";
5434 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005435 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005436 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5437 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5438 : "token has capture without window";
5439 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005440 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005441
5442 return dump;
5443}
5444
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005445void InputDispatcher::dumpDispatchStateLocked(std::string& dump) const {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005446 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5447 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5448 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005449 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005450
Tiger Huang721e26f2018-07-24 22:26:19 +08005451 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5452 dump += StringPrintf(INDENT "FocusedApplications:\n");
5453 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5454 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005455 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005456 const std::chrono::duration timeout =
5457 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005458 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005459 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005460 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005461 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005462 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005463 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005464 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005465
Vishnu Nairc519ff72021-01-21 08:23:08 -08005466 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005467 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005469 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005470 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005471 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005472 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5473 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474 }
5475 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005476 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005477 }
5478
arthurhung6d4bed92021-03-17 11:59:33 +08005479 if (mDragState) {
5480 dump += StringPrintf(INDENT "DragState:\n");
5481 mDragState->dump(dump, INDENT2);
5482 }
5483
Arthur Hungb92218b2018-08-14 12:00:21 +08005484 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005485 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5486 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5487 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5488 const auto& displayInfo = it->second;
5489 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5490 displayInfo.logicalHeight);
5491 displayInfo.transform.dump(dump, "transform", INDENT4);
5492 } else {
5493 dump += INDENT2 "No DisplayInfo found!\n";
5494 }
5495
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005496 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005497 dump += INDENT2 "Windows:\n";
5498 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005499 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5500 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005501
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005502 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005503 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005504 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005505 "applicationInfo.name=%s, "
5506 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005507 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005508 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005509 windowInfo->displayId,
5510 windowInfo->inputConfig.string().c_str(),
5511 windowInfo->alpha, windowInfo->frameLeft,
5512 windowInfo->frameTop, windowInfo->frameRight,
5513 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005514 windowInfo->applicationInfo.name.c_str(),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005515 binderToString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005516 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005517 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005518 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005519 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005520 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005521 millis(windowInfo->dispatchingTimeout),
Siarhei Vishniakou63b63612023-04-12 11:00:23 -07005522 binderToString(windowInfo->token).c_str(),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005523 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005524 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005525 }
5526 } else {
5527 dump += INDENT2 "Windows: <none>\n";
5528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005529 }
5530 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005531 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 }
5533
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005534 if (!mGlobalMonitorsByDisplay.empty()) {
5535 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5536 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005537 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005538 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005540 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541 }
5542
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005543 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005544
5545 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005546 if (!mRecentQueue.empty()) {
5547 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005548 for (const std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005549 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005550 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005551 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005552 }
5553 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005554 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555 }
5556
5557 // Dump event currently being dispatched.
5558 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005559 dump += INDENT "PendingEvent:\n";
5560 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005561 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005562 dump += StringPrintf(", age=%" PRId64 "ms\n",
5563 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005565 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566 }
5567
5568 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005569 if (!mInboundQueue.empty()) {
5570 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005571 for (const std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005572 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005573 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005574 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575 }
5576 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005577 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578 }
5579
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005580 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005581 dump += INDENT "ReplacedKeys:\n";
Michael Wright3cec4462022-11-24 22:05:46 +00005582 for (const auto& [replacement, newKeyCode] : mReplacedKeys) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005583 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005584 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005585 }
5586 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005587 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005588 }
5589
Prabir Pradhancef936d2021-07-21 16:17:52 +00005590 if (!mCommandQueue.empty()) {
5591 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5592 } else {
5593 dump += INDENT "CommandQueue: <empty>\n";
5594 }
5595
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005596 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005597 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005598 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005599 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005600 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005601 connection->inputChannel->getFd().get(),
5602 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005603 connection->getWindowName().c_str(),
5604 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005605 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005607 if (!connection->outboundQueue.empty()) {
5608 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5609 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005610 dump += dumpQueue(connection->outboundQueue, currentTime);
5611
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005613 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614 }
5615
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005616 if (!connection->waitQueue.empty()) {
5617 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5618 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005619 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005621 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622 }
5623 }
5624 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005625 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626 }
5627
5628 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005629 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5630 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005631 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005632 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633 }
5634
Antonio Kantek15beb512022-06-13 22:35:41 +00005635 if (!mTouchModePerDisplay.empty()) {
5636 dump += INDENT "TouchModePerDisplay:\n";
5637 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5638 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5639 std::to_string(touchMode).c_str());
5640 }
5641 } else {
5642 dump += INDENT "TouchModePerDisplay: <none>\n";
5643 }
5644
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005645 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005646 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5647 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5648 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005649 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005650 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005651}
5652
Siarhei Vishniakou4c9d6ff2023-04-18 11:23:20 -07005653void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) const {
Michael Wright3dd60e22019-03-27 22:06:44 +00005654 const size_t numMonitors = monitors.size();
5655 for (size_t i = 0; i < numMonitors; i++) {
5656 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005657 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005658 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5659 dump += "\n";
5660 }
5661}
5662
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005663class LooperEventCallback : public LooperCallback {
5664public:
5665 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5666 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5667
5668private:
5669 std::function<int(int events)> mCallback;
5670};
5671
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005672Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005673 if (DEBUG_CHANNEL_CREATION) {
5674 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5675 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005677 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005678 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005679 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005680
5681 if (result) {
5682 return base::Error(result) << "Failed to open input channel pair with name " << name;
5683 }
5684
Michael Wrightd02c5b62014-02-10 15:10:22 -08005685 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005686 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005687 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005688 int fd = serverChannel->getFd();
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005689 std::shared_ptr<Connection> connection =
5690 std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
5691 mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005692
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005693 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5694 ALOGE("Created a new connection, but the token %p is already known", token.get());
5695 }
5696 mConnectionsByToken.emplace(token, connection);
5697
5698 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5699 this, std::placeholders::_1, token);
5700
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005701 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5702 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005703 } // release lock
5704
5705 // Wake the looper because some connections have changed.
5706 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005707 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708}
5709
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005710Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005711 const std::string& name,
5712 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005713 std::shared_ptr<InputChannel> serverChannel;
5714 std::unique_ptr<InputChannel> clientChannel;
5715 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5716 if (result) {
5717 return base::Error(result) << "Failed to open input channel pair with name " << name;
5718 }
5719
Michael Wright3dd60e22019-03-27 22:06:44 +00005720 { // acquire lock
5721 std::scoped_lock _l(mLock);
5722
5723 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005724 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5725 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005726 }
5727
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005728 std::shared_ptr<Connection> connection =
5729 std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005730 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005731 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005732
5733 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5734 ALOGE("Created a new connection, but the token %p is already known", token.get());
5735 }
5736 mConnectionsByToken.emplace(token, connection);
5737 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5738 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005739
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005740 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005741
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005742 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5743 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005744 }
Garfield Tan15601662020-09-22 15:32:38 -07005745
Michael Wright3dd60e22019-03-27 22:06:44 +00005746 // Wake the looper because some connections have changed.
5747 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005748 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005749}
5750
Garfield Tan15601662020-09-22 15:32:38 -07005751status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005752 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005753 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005754
Harry Cutts33476232023-01-30 19:57:29 +00005755 status_t status = removeInputChannelLocked(connectionToken, /*notify=*/false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005756 if (status) {
5757 return status;
5758 }
5759 } // release lock
5760
5761 // Wake the poll loop because removing the connection may have changed the current
5762 // synchronization state.
5763 mLooper->wake();
5764 return OK;
5765}
5766
Garfield Tan15601662020-09-22 15:32:38 -07005767status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5768 bool notify) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005769 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005770 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005771 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005772 return BAD_VALUE;
5773 }
5774
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005775 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005776
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005778 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005779 }
5780
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005781 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782
5783 nsecs_t currentTime = now();
5784 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5785
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005786 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005787 return OK;
5788}
5789
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005790void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005791 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5792 auto& [displayId, monitors] = *it;
5793 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5794 return monitor.inputChannel->getConnectionToken() == connectionToken;
5795 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005796
Michael Wright3dd60e22019-03-27 22:06:44 +00005797 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005798 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005799 } else {
5800 ++it;
5801 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005802 }
5803}
5804
Michael Wright3dd60e22019-03-27 22:06:44 +00005805status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005806 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005807 return pilferPointersLocked(token);
5808}
Michael Wright3dd60e22019-03-27 22:06:44 +00005809
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005810status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005811 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5812 if (!requestingChannel) {
5813 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5814 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005815 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005816
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005817 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005818 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.none()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005819 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5820 " Ignoring.");
5821 return BAD_VALUE;
5822 }
5823
5824 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005825 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005826 // Send cancel events to all the input channels we're stealing from.
Michael Wrightfb04fd52022-11-24 22:31:11 +00005827 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005828 "input channel stole pointer stream");
5829 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005830 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005831 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005832 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005833 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005834 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005835 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005836 if (channel != nullptr && channel->getConnectionToken() != token) {
5837 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5838 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5839 canceledWindows += channel->getName();
5840 }
5841 }
5842 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5843 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5844 canceledWindows.c_str());
5845
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005846 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005847 // This only blocks relevant pointers to be sent to other windows
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08005848 window.pilferedPointerIds |= window.pointerIds;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005849
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005850 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005851 return OK;
5852}
5853
Prabir Pradhan99987712020-11-10 18:43:05 -08005854void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5855 { // acquire lock
5856 std::scoped_lock _l(mLock);
5857 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005858 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005859 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5860 windowHandle != nullptr ? windowHandle->getName().c_str()
5861 : "token without window");
5862 }
5863
Vishnu Nairc519ff72021-01-21 08:23:08 -08005864 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005865 if (focusedToken != windowToken) {
5866 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5867 enabled ? "enable" : "disable");
5868 return;
5869 }
5870
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005871 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005872 ALOGW("Ignoring request to %s Pointer Capture: "
5873 "window has %s requested pointer capture.",
5874 enabled ? "enable" : "disable", enabled ? "already" : "not");
5875 return;
5876 }
5877
Christine Franksb768bb42021-11-29 12:11:31 -08005878 if (enabled) {
5879 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5880 mIneligibleDisplaysForPointerCapture.end(),
5881 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5882 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5883 return;
5884 }
5885 }
5886
Prabir Pradhan99987712020-11-10 18:43:05 -08005887 setPointerCaptureLocked(enabled);
5888 } // release lock
5889
5890 // Wake the thread to process command entries.
5891 mLooper->wake();
5892}
5893
Christine Franksb768bb42021-11-29 12:11:31 -08005894void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5895 { // acquire lock
5896 std::scoped_lock _l(mLock);
5897 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5898 if (!isEligible) {
5899 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5900 }
5901 } // release lock
5902}
5903
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005904std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5905 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005906 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005907 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005908 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005909 }
5910 }
5911 }
5912 return std::nullopt;
5913}
5914
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005915std::shared_ptr<Connection> InputDispatcher::getConnectionLocked(
5916 const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005917 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005918 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005919 }
5920
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005921 for (const auto& [token, connection] : mConnectionsByToken) {
5922 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005923 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005924 }
5925 }
Robert Carr4e670e52018-08-15 13:26:12 -07005926
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005927 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005928}
5929
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005930std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005931 std::shared_ptr<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005932 if (connection == nullptr) {
5933 return "<nullptr>";
5934 }
5935 return connection->getInputChannelName();
5936}
5937
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005938void InputDispatcher::removeConnectionLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005939 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005940 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005941}
5942
Prabir Pradhancef936d2021-07-21 16:17:52 +00005943void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07005944 const std::shared_ptr<Connection>& connection,
5945 uint32_t seq, bool handled,
5946 nsecs_t consumeTime) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005947 // Handle post-event policy actions.
5948 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5949 if (dispatchEntryIt == connection->waitQueue.end()) {
5950 return;
5951 }
5952 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5953 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5954 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5955 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5956 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5957 }
5958 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5959 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5960 connection->inputChannel->getConnectionToken(),
5961 dispatchEntry->deliveryTime, consumeTime, finishTime);
5962 }
5963
5964 bool restartEvent;
5965 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5966 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5967 restartEvent =
5968 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5969 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5970 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5971 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5972 handled);
5973 } else {
5974 restartEvent = false;
5975 }
5976
5977 // Dequeue the event and start the next cycle.
5978 // Because the lock might have been released, it is possible that the
5979 // contents of the wait queue to have been drained, so we need to double-check
5980 // a few things.
5981 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5982 if (dispatchEntryIt != connection->waitQueue.end()) {
5983 dispatchEntry = *dispatchEntryIt;
5984 connection->waitQueue.erase(dispatchEntryIt);
5985 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5986 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5987 if (!connection->responsive) {
5988 connection->responsive = isConnectionResponsive(*connection);
5989 if (connection->responsive) {
5990 // The connection was unresponsive, and now it's responsive.
5991 processConnectionResponsiveLocked(*connection);
5992 }
5993 }
5994 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005995 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005996 connection->outboundQueue.push_front(dispatchEntry);
5997 traceOutboundQueueLength(*connection);
5998 } else {
5999 releaseDispatchEntry(dispatchEntry);
6000 }
6001 }
6002
6003 // Start the next dispatch cycle for this connection.
6004 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006005}
6006
Prabir Pradhancef936d2021-07-21 16:17:52 +00006007void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
6008 const sp<IBinder>& newToken) {
6009 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
6010 scoped_unlock unlock(mLock);
6011 mPolicy->notifyFocusChanged(oldToken, newToken);
6012 };
6013 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006014}
6015
Prabir Pradhancef936d2021-07-21 16:17:52 +00006016void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
6017 auto command = [this, token, x, y]() REQUIRES(mLock) {
6018 scoped_unlock unlock(mLock);
6019 mPolicy->notifyDropWindow(token, x, y);
6020 };
6021 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08006022}
6023
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006024void InputDispatcher::onAnrLocked(const std::shared_ptr<Connection>& connection) {
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006025 if (connection == nullptr) {
6026 LOG_ALWAYS_FATAL("Caller must check for nullness");
6027 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006028 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
6029 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006030 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006031 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006032 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006033 return;
6034 }
6035 /**
6036 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
6037 * may not be the one that caused the timeout to occur. One possibility is that window timeout
6038 * has changed. This could cause newer entries to time out before the already dispatched
6039 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
6040 * processes the events linearly. So providing information about the oldest entry seems to be
6041 * most useful.
6042 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006043 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006044 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
6045 std::string reason =
6046 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006047 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006048 ns2ms(currentWait),
6049 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006050 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06006051 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006052
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006053 processConnectionUnresponsiveLocked(*connection, std::move(reason));
6054
6055 // Stop waking up for events on this connection, it is already unresponsive
6056 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006057}
6058
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006059void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
6060 std::string reason =
6061 StringPrintf("%s does not have a focused window", application->getName().c_str());
6062 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006063
Prabir Pradhancef936d2021-07-21 16:17:52 +00006064 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
6065 scoped_unlock unlock(mLock);
6066 mPolicy->notifyNoFocusedWindowAnr(application);
6067 };
6068 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00006069}
6070
chaviw98318de2021-05-19 16:45:23 -05006071void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006072 const std::string& reason) {
6073 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
6074 updateLastAnrStateLocked(windowLabel, reason);
6075}
6076
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05006077void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
6078 const std::string& reason) {
6079 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006080 updateLastAnrStateLocked(windowLabel, reason);
6081}
6082
6083void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
6084 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006085 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07006086 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006087 struct tm tm;
6088 localtime_r(&t, &tm);
6089 char timestr[64];
6090 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006091 mLastAnrState.clear();
6092 mLastAnrState += INDENT "ANR:\n";
6093 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07006094 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
6095 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006096 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006097}
6098
Prabir Pradhancef936d2021-07-21 16:17:52 +00006099void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
6100 KeyEntry& entry) {
6101 const KeyEvent event = createKeyEvent(entry);
6102 nsecs_t delay = 0;
6103 { // release lock
6104 scoped_unlock unlock(mLock);
6105 android::base::Timer t;
6106 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
6107 entry.policyFlags);
6108 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
6109 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
6110 std::to_string(t.duration().count()).c_str());
6111 }
6112 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08006113
6114 if (delay < 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006115 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00006116 } else if (delay == 0) {
Michael Wright5caf55a2022-11-24 22:31:42 +00006117 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006118 } else {
Michael Wright5caf55a2022-11-24 22:31:42 +00006119 entry.interceptKeyResult = KeyEntry::InterceptKeyResult::TRY_AGAIN_LATER;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006120 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006121 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006122}
6123
Prabir Pradhancef936d2021-07-21 16:17:52 +00006124void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006125 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006126 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006127 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006128 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006129 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006130 };
6131 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006132}
6133
Prabir Pradhanedd96402022-02-15 01:46:16 -08006134void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6135 std::optional<int32_t> pid) {
6136 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006137 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006138 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006139 };
6140 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006141}
6142
6143/**
6144 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6145 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6146 * command entry to the command queue.
6147 */
6148void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6149 std::string reason) {
6150 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006151 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006152 if (connection.monitor) {
6153 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6154 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006155 pid = findMonitorPidByTokenLocked(connectionToken);
6156 } else {
6157 // The connection is a window
6158 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6159 reason.c_str());
6160 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6161 if (handle != nullptr) {
6162 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006163 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006164 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006165 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006166}
6167
6168/**
6169 * Tell the policy that a connection has become responsive so that it can stop ANR.
6170 */
6171void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6172 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006173 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006174 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006175 pid = findMonitorPidByTokenLocked(connectionToken);
6176 } else {
6177 // The connection is a window
6178 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6179 if (handle != nullptr) {
6180 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006181 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006182 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006183 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006184}
6185
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006186bool InputDispatcher::afterKeyEventLockedInterruptable(
6187 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6188 KeyEntry& keyEntry, bool handled) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006189 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006190 if (!handled) {
6191 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006192 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006193 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006194 return false;
6195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006196
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006197 // Get the fallback key state.
6198 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006199 int32_t originalKeyCode = keyEntry.keyCode;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006200 std::optional<int32_t> fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006201 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006202 connection->inputState.removeFallbackKey(originalKeyCode);
6203 }
6204
6205 if (handled || !dispatchEntry->hasForegroundTarget()) {
6206 // If the application handles the original key for which we previously
6207 // generated a fallback or if the window is not a foreground window,
6208 // then cancel the associated fallback key, if any.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006209 if (fallbackKeyCode) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006210 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006211 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6212 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6213 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6214 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6215 keyEntry.policyFlags);
6216 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006217 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006218 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006219
6220 mLock.unlock();
6221
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006222 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006223 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006224
6225 mLock.lock();
6226
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006227 // Cancel the fallback key.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006228 if (*fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006229 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006230 "application handled the original non-fallback key "
6231 "or is no longer a foreground target, "
6232 "canceling previously dispatched fallback key");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006233 options.keyCode = *fallbackKeyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006234 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006235 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006236 connection->inputState.removeFallbackKey(originalKeyCode);
6237 }
6238 } else {
6239 // If the application did not handle a non-fallback key, first check
6240 // that we are in a good state to perform unhandled key event processing
6241 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006242 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006243 if (!fallbackKeyCode && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006244 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6245 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6246 "since this is not an initial down. "
6247 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6248 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6249 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006250 return false;
6251 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006252
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006253 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006254 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6255 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6256 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6257 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6258 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006259 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006260
6261 mLock.unlock();
6262
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006263 bool fallback =
6264 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006265 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006266
6267 mLock.lock();
6268
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006269 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006270 connection->inputState.removeFallbackKey(originalKeyCode);
6271 return false;
6272 }
6273
6274 // Latch the fallback keycode for this key on an initial down.
6275 // The fallback keycode cannot change at any other point in the lifecycle.
6276 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006277 if (fallback) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006278 *fallbackKeyCode = event.getKeyCode();
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006279 } else {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006280 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006281 }
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006282 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006283 }
6284
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006285 ALOG_ASSERT(fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006286
6287 // Cancel the fallback key if the policy decides not to send it anymore.
6288 // We will continue to dispatch the key to the policy but we will no
6289 // longer dispatch a fallback key to the application.
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006290 if (*fallbackKeyCode != AKEYCODE_UNKNOWN &&
6291 (!fallback || *fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006292 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6293 if (fallback) {
6294 ALOGD("Unhandled key event: Policy requested to send key %d"
6295 "as a fallback for %d, but on the DOWN it had requested "
6296 "to send %d instead. Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006297 event.getKeyCode(), originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006298 } else {
6299 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6300 "but on the DOWN it had requested to send %d. "
6301 "Fallback canceled.",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006302 originalKeyCode, *fallbackKeyCode);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006303 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006304 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006305
Michael Wrightfb04fd52022-11-24 22:31:11 +00006306 CancelationOptions options(CancelationOptions::Mode::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006307 "canceling fallback, policy no longer desires it");
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006308 options.keyCode = *fallbackKeyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006309 synthesizeCancelationEventsForConnectionLocked(connection, options);
6310
6311 fallback = false;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006312 *fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006313 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006314 connection->inputState.setFallbackKey(originalKeyCode, *fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006315 }
6316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006317
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006318 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6319 {
6320 std::string msg;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006321 const std::map<int32_t, int32_t>& fallbackKeys =
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006322 connection->inputState.getFallbackKeys();
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006323 for (const auto& [key, value] : fallbackKeys) {
6324 msg += StringPrintf(", %d->%d", key, value);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006325 }
6326 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6327 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006328 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006329 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006330
6331 if (fallback) {
6332 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006333 keyEntry.eventTime = event.getEventTime();
6334 keyEntry.deviceId = event.getDeviceId();
6335 keyEntry.source = event.getSource();
6336 keyEntry.displayId = event.getDisplayId();
6337 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006338 keyEntry.keyCode = *fallbackKeyCode;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006339 keyEntry.scanCode = event.getScanCode();
6340 keyEntry.metaState = event.getMetaState();
6341 keyEntry.repeatCount = event.getRepeatCount();
6342 keyEntry.downTime = event.getDownTime();
6343 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006344
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006345 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6346 ALOGD("Unhandled key event: Dispatching fallback key. "
6347 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
Siarhei Vishniakou0fe01262023-04-17 08:11:37 -07006348 originalKeyCode, *fallbackKeyCode, keyEntry.metaState);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006349 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006350 return true; // restart the event
6351 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006352 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6353 ALOGD("Unhandled key event: No fallback key.");
6354 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006355
6356 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006357 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006358 }
6359 }
6360 return false;
6361}
6362
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006363bool InputDispatcher::afterMotionEventLockedInterruptable(
6364 const std::shared_ptr<Connection>& connection, DispatchEntry* dispatchEntry,
6365 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006366 return false;
6367}
6368
Michael Wrightd02c5b62014-02-10 15:10:22 -08006369void InputDispatcher::traceInboundQueueLengthLocked() {
6370 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006371 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006372 }
6373}
6374
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006375void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006376 if (ATRACE_ENABLED()) {
6377 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006378 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6379 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006380 }
6381}
6382
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006383void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006384 if (ATRACE_ENABLED()) {
6385 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006386 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6387 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006388 }
6389}
6390
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006391void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006392 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006393
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006394 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006395 dumpDispatchStateLocked(dump);
6396
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006397 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006398 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006399 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006400 }
6401}
6402
6403void InputDispatcher::monitor() {
6404 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006405 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006406 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006407 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006408}
6409
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006410/**
6411 * Wake up the dispatcher and wait until it processes all events and commands.
6412 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6413 * this method can be safely called from any thread, as long as you've ensured that
6414 * the work you are interested in completing has already been queued.
6415 */
6416bool InputDispatcher::waitForIdle() {
6417 /**
6418 * Timeout should represent the longest possible time that a device might spend processing
6419 * events and commands.
6420 */
6421 constexpr std::chrono::duration TIMEOUT = 100ms;
6422 std::unique_lock lock(mLock);
6423 mLooper->wake();
6424 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6425 return result == std::cv_status::no_timeout;
6426}
6427
Vishnu Naire798b472020-07-23 13:52:21 -07006428/**
6429 * Sets focus to the window identified by the token. This must be called
6430 * after updating any input window handles.
6431 *
6432 * Params:
6433 * request.token - input channel token used to identify the window that should gain focus.
6434 * request.focusedToken - the token that the caller expects currently to be focused. If the
6435 * specified token does not match the currently focused window, this request will be dropped.
6436 * If the specified focused token matches the currently focused window, the call will succeed.
6437 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6438 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6439 * when requesting the focus change. This determines which request gets
6440 * precedence if there is a focus change request from another source such as pointer down.
6441 */
Vishnu Nair958da932020-08-21 17:12:37 -07006442void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6443 { // acquire lock
6444 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006445 std::optional<FocusResolver::FocusChanges> changes =
6446 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6447 if (changes) {
6448 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006449 }
6450 } // release lock
6451 // Wake up poll loop since it may need to make new input dispatching choices.
6452 mLooper->wake();
6453}
6454
Vishnu Nairc519ff72021-01-21 08:23:08 -08006455void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6456 if (changes.oldFocus) {
6457 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006458 if (focusedInputChannel) {
Michael Wrightfb04fd52022-11-24 22:31:11 +00006459 CancelationOptions options(CancelationOptions::Mode::CANCEL_NON_POINTER_EVENTS,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006460 "focus left window");
6461 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Harry Cutts33476232023-01-30 19:57:29 +00006462 enqueueFocusEventLocked(changes.oldFocus, /*hasFocus=*/false, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006463 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006464 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006465 if (changes.newFocus) {
Harry Cutts33476232023-01-30 19:57:29 +00006466 enqueueFocusEventLocked(changes.newFocus, /*hasFocus=*/true, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006467 }
6468
Prabir Pradhan99987712020-11-10 18:43:05 -08006469 // If a window has pointer capture, then it must have focus. We need to ensure that this
6470 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6471 // If the window loses focus before it loses pointer capture, then the window can be in a state
6472 // where it has pointer capture but not focus, violating the contract. Therefore we must
6473 // dispatch the pointer capture event before the focus event. Since focus events are added to
6474 // the front of the queue (above), we add the pointer capture event to the front of the queue
6475 // after the focus events are added. This ensures the pointer capture event ends up at the
6476 // front.
6477 disablePointerCaptureForcedLocked();
6478
Vishnu Nairc519ff72021-01-21 08:23:08 -08006479 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006480 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006481 }
6482}
Vishnu Nair958da932020-08-21 17:12:37 -07006483
Prabir Pradhan99987712020-11-10 18:43:05 -08006484void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006485 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006486 return;
6487 }
6488
6489 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6490
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006491 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006492 setPointerCaptureLocked(false);
6493 }
6494
6495 if (!mWindowTokenWithPointerCapture) {
6496 // No need to send capture changes because no window has capture.
6497 return;
6498 }
6499
6500 if (mPendingEvent != nullptr) {
6501 // Move the pending event to the front of the queue. This will give the chance
6502 // for the pending event to be dropped if it is a captured event.
6503 mInboundQueue.push_front(mPendingEvent);
6504 mPendingEvent = nullptr;
6505 }
6506
6507 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006508 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006509 mInboundQueue.push_front(std::move(entry));
6510}
6511
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006512void InputDispatcher::setPointerCaptureLocked(bool enable) {
6513 mCurrentPointerCaptureRequest.enable = enable;
6514 mCurrentPointerCaptureRequest.seq++;
6515 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006516 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006517 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006518 };
6519 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006520}
6521
Vishnu Nair599f1412021-06-21 10:39:58 -07006522void InputDispatcher::displayRemoved(int32_t displayId) {
6523 { // acquire lock
6524 std::scoped_lock _l(mLock);
6525 // Set an empty list to remove all handles from the specific display.
6526 setInputWindowsLocked(/* window handles */ {}, displayId);
6527 setFocusedApplicationLocked(displayId, nullptr);
6528 // Call focus resolver to clean up stale requests. This must be called after input windows
6529 // have been removed for the removed display.
6530 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006531 // Reset pointer capture eligibility, regardless of previous state.
6532 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006533 // Remove the associated touch mode state.
6534 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006535 } // release lock
6536
6537 // Wake up poll loop since it may need to make new input dispatching choices.
6538 mLooper->wake();
6539}
6540
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006541void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6542 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006543 // The listener sends the windows as a flattened array. Separate the windows by display for
6544 // more convenient parsing.
6545 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006546 for (const auto& info : windowInfos) {
6547 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006548 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006549 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006550
6551 { // acquire lock
6552 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006553
6554 // Ensure that we have an entry created for all existing displays so that if a displayId has
6555 // no windows, we can tell that the windows were removed from the display.
6556 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6557 handlesPerDisplay[displayId];
6558 }
6559
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006560 mDisplayInfos.clear();
6561 for (const auto& displayInfo : displayInfos) {
6562 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6563 }
6564
6565 for (const auto& [displayId, handles] : handlesPerDisplay) {
6566 setInputWindowsLocked(handles, displayId);
6567 }
6568 }
6569 // Wake up poll loop since it may need to make new input dispatching choices.
6570 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006571}
6572
Vishnu Nair062a8672021-09-03 16:07:44 -07006573bool InputDispatcher::shouldDropInput(
6574 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006575 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6576 (windowHandle->getInfo()->inputConfig.test(
6577 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006578 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006579 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6580 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006581 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006582 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006583 windowHandle->getInfo()->displayId);
6584 return true;
6585 }
6586 return false;
6587}
6588
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006589void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6590 const std::vector<gui::WindowInfo>& windowInfos,
6591 const std::vector<DisplayInfo>& displayInfos) {
6592 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6593}
6594
Arthur Hungdfd528e2021-12-08 13:23:04 +00006595void InputDispatcher::cancelCurrentTouch() {
6596 {
6597 std::scoped_lock _l(mLock);
6598 ALOGD("Canceling all ongoing pointer gestures on all displays.");
Michael Wrightfb04fd52022-11-24 22:31:11 +00006599 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
Arthur Hungdfd528e2021-12-08 13:23:04 +00006600 "cancel current touch");
6601 synthesizeCancelationEventsForAllConnectionsLocked(options);
6602
6603 mTouchStatesByDisplay.clear();
Arthur Hungdfd528e2021-12-08 13:23:04 +00006604 }
6605 // Wake up poll loop since there might be work to do.
6606 mLooper->wake();
6607}
6608
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006609void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6610 std::scoped_lock _l(mLock);
6611 mMonitorDispatchingTimeout = timeout;
6612}
6613
Arthur Hungc539dbb2022-12-08 07:45:36 +00006614void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
6615 const sp<WindowInfoHandle>& oldWindowHandle,
6616 const sp<WindowInfoHandle>& newWindowHandle,
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006617 TouchState& state, int32_t pointerId,
6618 std::vector<InputTarget>& targets) {
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006619 std::bitset<MAX_POINTER_ID + 1> pointerIds;
6620 pointerIds.set(pointerId);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006621 const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
6622 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6623 const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
6624 newWindowHandle->getInfo()->inputConfig.test(
6625 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6626 const sp<WindowInfoHandle> oldWallpaper =
6627 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6628 const sp<WindowInfoHandle> newWallpaper =
6629 newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
6630 if (oldWallpaper == newWallpaper) {
6631 return;
6632 }
6633
6634 if (oldWallpaper != nullptr) {
Siarhei Vishniakou0026b4c2022-11-10 19:33:29 -08006635 const TouchedWindow& oldTouchedWindow = state.getTouchedWindow(oldWallpaper);
6636 addWindowTargetLocked(oldWallpaper,
6637 oldTouchedWindow.targetFlags |
6638 InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
6639 pointerIds, oldTouchedWindow.firstDownTimeInTarget, targets);
6640 state.removeTouchedPointerFromWindow(pointerId, oldWallpaper);
Arthur Hungc539dbb2022-12-08 07:45:36 +00006641 }
6642
6643 if (newWallpaper != nullptr) {
6644 state.addOrUpdateWindow(newWallpaper,
6645 InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
6646 InputTarget::Flags::WINDOW_IS_OBSCURED |
6647 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
6648 pointerIds);
6649 }
6650}
6651
6652void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
6653 ftl::Flags<InputTarget::Flags> newTargetFlags,
6654 const sp<WindowInfoHandle> fromWindowHandle,
6655 const sp<WindowInfoHandle> toWindowHandle,
Siarhei Vishniakou8a878352023-01-30 14:05:01 -08006656 TouchState& state,
6657 std::bitset<MAX_POINTER_ID + 1> pointerIds) {
Arthur Hungc539dbb2022-12-08 07:45:36 +00006658 const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6659 fromWindowHandle->getInfo()->inputConfig.test(
6660 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6661 const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
6662 toWindowHandle->getInfo()->inputConfig.test(
6663 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
6664
6665 const sp<WindowInfoHandle> oldWallpaper =
6666 oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
6667 const sp<WindowInfoHandle> newWallpaper =
6668 newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
6669 if (oldWallpaper == newWallpaper) {
6670 return;
6671 }
6672
6673 if (oldWallpaper != nullptr) {
6674 CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
6675 "transferring touch focus to another window");
6676 state.removeWindowByToken(oldWallpaper->getToken());
6677 synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
6678 }
6679
6680 if (newWallpaper != nullptr) {
6681 nsecs_t downTimeInTarget = now();
6682 ftl::Flags<InputTarget::Flags> wallpaperFlags =
6683 oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
6684 wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
6685 InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
6686 state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006687 std::shared_ptr<Connection> wallpaperConnection =
6688 getConnectionLocked(newWallpaper->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006689 if (wallpaperConnection != nullptr) {
Siarhei Vishniakou1069fa82023-04-19 12:14:39 -07006690 std::shared_ptr<Connection> toConnection =
6691 getConnectionLocked(toWindowHandle->getToken());
Arthur Hungc539dbb2022-12-08 07:45:36 +00006692 toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
6693 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
6694 wallpaperFlags);
6695 }
6696 }
6697}
6698
6699sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
6700 const sp<WindowInfoHandle>& windowHandle) const {
6701 const std::vector<sp<WindowInfoHandle>>& windowHandles =
6702 getWindowHandlesLocked(windowHandle->getInfo()->displayId);
6703 bool foundWindow = false;
6704 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
6705 if (!foundWindow && otherHandle != windowHandle) {
6706 continue;
6707 }
6708 if (windowHandle == otherHandle) {
6709 foundWindow = true;
6710 continue;
6711 }
6712
6713 if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
6714 return otherHandle;
6715 }
6716 }
6717 return nullptr;
6718}
6719
Garfield Tane84e6f92019-08-29 17:28:41 -07006720} // namespace android::inputdispatcher