blob: e191d937148ad8ba9ece6abe3866b4dc88f7c077 [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>
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080023#include <android-base/properties.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080024#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050025#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070026#include <binder/Binder.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080027#include <ftl/enum.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070028#if defined(__ANDROID__)
chaviw15fab6f2021-06-07 14:15:52 -050029#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou31977182022-09-30 08:51:23 -070030#endif
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080031#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070032#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010033#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070034#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080035
Michael Wright44753b12020-07-08 13:48:11 +010036#include <cerrno>
37#include <cinttypes>
38#include <climits>
39#include <cstddef>
40#include <ctime>
41#include <queue>
42#include <sstream>
43
44#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000045#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070046#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010047
Michael Wrightd02c5b62014-02-10 15:10:22 -080048#define INDENT " "
49#define INDENT2 " "
50#define INDENT3 " "
51#define INDENT4 " "
52
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080053using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000054using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080055using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070056using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050057using android::gui::FocusRequest;
58using android::gui::TouchOcclusionMode;
59using android::gui::WindowInfo;
60using android::gui::WindowInfoHandle;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100061using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080062using android::os::InputEventInjectionResult;
63using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080064
Garfield Tane84e6f92019-08-29 17:28:41 -070065namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080066
Prabir Pradhancef936d2021-07-21 16:17:52 +000067namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000068// Temporarily releases a held mutex for the lifetime of the instance.
69// Named to match std::scoped_lock
70class scoped_unlock {
71public:
72 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
73 ~scoped_unlock() { mMutex.lock(); }
74
75private:
76 std::mutex& mMutex;
77};
78
Michael Wrightd02c5b62014-02-10 15:10:22 -080079// Default input dispatching timeout if there is no focused application or paused window
80// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080081const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
82 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
83 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow for all pending events to be processed when an app switch
86// key is on the way. This is used to preempt input dispatch and drop input events
87// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080090const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
Michael Wrightd02c5b62014-02-10 15:10:22 -080092// 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 +000093constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
94
95// Log a warning when an interception call takes longer than this to process.
96constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -070098// Additional key latency in case a connection is still processing some motion events.
99// This will help with the case when a user touched a button that opens a new window,
100// and gives us the chance to dispatch the key to this new window.
101constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
102
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000104constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
105
Antonio Kantekea47acb2021-12-23 12:41:25 -0800106// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000107constexpr int LOGTAG_INPUT_INTERACTION = 62000;
108constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000109constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000110
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000111inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112 return systemTime(SYSTEM_TIME_MONOTONIC);
113}
114
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000115inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800116 return value ? "true" : "false";
117}
118
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000119inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000120 if (binder == nullptr) {
121 return "<null>";
122 }
123 return StringPrintf("%p", binder.get());
124}
125
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000126inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700127 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
128 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129}
130
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000131bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700133 case AKEY_EVENT_ACTION_DOWN:
134 case AKEY_EVENT_ACTION_UP:
135 return true;
136 default:
137 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138 }
139}
140
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000141bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700142 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143 ALOGE("Key event has invalid action code 0x%x", action);
144 return false;
145 }
146 return true;
147}
148
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000149bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800150 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700151 case AMOTION_EVENT_ACTION_DOWN:
152 case AMOTION_EVENT_ACTION_UP:
153 case AMOTION_EVENT_ACTION_CANCEL:
154 case AMOTION_EVENT_ACTION_MOVE:
155 case AMOTION_EVENT_ACTION_OUTSIDE:
156 case AMOTION_EVENT_ACTION_HOVER_ENTER:
157 case AMOTION_EVENT_ACTION_HOVER_MOVE:
158 case AMOTION_EVENT_ACTION_HOVER_EXIT:
159 case AMOTION_EVENT_ACTION_SCROLL:
160 return true;
161 case AMOTION_EVENT_ACTION_POINTER_DOWN:
162 case AMOTION_EVENT_ACTION_POINTER_UP: {
163 int32_t index = getMotionEventActionPointerIndex(action);
164 return index >= 0 && index < pointerCount;
165 }
166 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
167 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
168 return actionButton != 0;
169 default:
170 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800171 }
172}
173
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000174int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500175 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
176}
177
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000178bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
179 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700180 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 ALOGE("Motion event has invalid action code 0x%x", action);
182 return false;
183 }
184 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800185 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700186 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187 return false;
188 }
189 BitSet32 pointerIdBits;
190 for (size_t i = 0; i < pointerCount; i++) {
191 int32_t id = pointerProperties[i].id;
192 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700193 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
194 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 return false;
196 }
197 if (pointerIdBits.hasBit(id)) {
198 ALOGE("Motion event has duplicate pointer id %d", id);
199 return false;
200 }
201 pointerIdBits.markBit(id);
202 }
203 return true;
204}
205
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000206std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000208 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 }
210
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000211 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800212 bool first = true;
213 Region::const_iterator cur = region.begin();
214 Region::const_iterator const tail = region.end();
215 while (cur != tail) {
216 if (first) {
217 first = false;
218 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800219 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800221 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 cur++;
223 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000224 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800225}
226
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000227std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500228 constexpr size_t maxEntries = 50; // max events to print
229 constexpr size_t skipBegin = maxEntries / 2;
230 const size_t skipEnd = queue.size() - maxEntries / 2;
231 // skip from maxEntries / 2 ... size() - maxEntries/2
232 // only print from 0 .. skipBegin and then from skipEnd .. size()
233
234 std::string dump;
235 for (size_t i = 0; i < queue.size(); i++) {
236 const DispatchEntry& entry = *queue[i];
237 if (i >= skipBegin && i < skipEnd) {
238 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
239 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
240 continue;
241 }
242 dump.append(INDENT4);
243 dump += entry.eventEntry->getDescription();
244 dump += StringPrintf(", seq=%" PRIu32
245 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
246 entry.seq, entry.targetFlags, entry.resolvedAction,
247 ns2ms(currentTime - entry.eventEntry->eventTime));
248 if (entry.deliveryTime != 0) {
249 // This entry was delivered, so add information on how long we've been waiting
250 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
251 }
252 dump.append("\n");
253 }
254 return dump;
255}
256
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700257/**
258 * Find the entry in std::unordered_map by key, and return it.
259 * If the entry is not found, return a default constructed entry.
260 *
261 * Useful when the entries are vectors, since an empty vector will be returned
262 * if the entry is not found.
263 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
264 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700265template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000266V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700267 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700268 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800269}
270
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000271bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700272 if (first == second) {
273 return true;
274 }
275
276 if (first == nullptr || second == nullptr) {
277 return false;
278 }
279
280 return first->getToken() == second->getToken();
281}
282
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000283bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000284 if (first == nullptr || second == nullptr) {
285 return false;
286 }
287 return first->applicationInfo.token != nullptr &&
288 first->applicationInfo.token == second->applicationInfo.token;
289}
290
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000291std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
292 std::shared_ptr<EventEntry> eventEntry,
293 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700294 if (inputTarget.useDefaultPointerTransform()) {
295 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700296 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700297 inputTarget.displayTransform,
298 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000299 }
300
301 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
302 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
303
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700304 std::vector<PointerCoords> pointerCoords;
305 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000306
307 // Use the first pointer information to normalize all other pointers. This could be any pointer
308 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700309 // uses the transform for the normalized pointer.
310 const ui::Transform& firstPointerTransform =
311 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
312 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000313
314 // Iterate through all pointers in the event to normalize against the first.
315 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
316 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
317 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700318 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000319
320 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700321 // First, apply the current pointer's transform to update the coordinates into
322 // window space.
323 pointerCoords[pointerIndex].transform(currTransform);
324 // Next, apply the inverse transform of the normalized coordinates so the
325 // current coordinates are transformed into the normalized coordinate space.
326 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000327 }
328
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700329 std::unique_ptr<MotionEntry> combinedMotionEntry =
330 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
331 motionEntry.deviceId, motionEntry.source,
332 motionEntry.displayId, motionEntry.policyFlags,
333 motionEntry.action, motionEntry.actionButton,
334 motionEntry.flags, motionEntry.metaState,
335 motionEntry.buttonState, motionEntry.classification,
336 motionEntry.edgeFlags, motionEntry.xPrecision,
337 motionEntry.yPrecision, motionEntry.xCursorPosition,
338 motionEntry.yCursorPosition, motionEntry.downTime,
339 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000340 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000341
342 if (motionEntry.injectionState) {
343 combinedMotionEntry->injectionState = motionEntry.injectionState;
344 combinedMotionEntry->injectionState->refCount += 1;
345 }
346
347 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700348 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700349 firstPointerTransform, inputTarget.displayTransform,
350 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000351 return dispatchEntry;
352}
353
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000354status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
355 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700356 std::unique_ptr<InputChannel> uniqueServerChannel;
357 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
358
359 serverChannel = std::move(uniqueServerChannel);
360 return result;
361}
362
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500363template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000364bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500365 if (lhs == nullptr && rhs == nullptr) {
366 return true;
367 }
368 if (lhs == nullptr || rhs == nullptr) {
369 return false;
370 }
371 return *lhs == *rhs;
372}
373
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000374KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000375 KeyEvent event;
376 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
377 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
378 entry.repeatCount, entry.downTime, entry.eventTime);
379 return event;
380}
381
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000382bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000383 // Do not keep track of gesture monitors. They receive every event and would disproportionately
384 // affect the statistics.
385 if (connection.monitor) {
386 return false;
387 }
388 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
389 if (!connection.responsive) {
390 return false;
391 }
392 return true;
393}
394
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000395bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000396 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
397 const int32_t& inputEventId = eventEntry.id;
398 if (inputEventId != dispatchEntry.resolvedEventId) {
399 // Event was transmuted
400 return false;
401 }
402 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
403 return false;
404 }
405 // Only track latency for events that originated from hardware
406 if (eventEntry.isSynthesized()) {
407 return false;
408 }
409 const EventEntry::Type& inputEventEntryType = eventEntry.type;
410 if (inputEventEntryType == EventEntry::Type::KEY) {
411 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
412 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
413 return false;
414 }
415 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
416 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
417 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
418 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
419 return false;
420 }
421 } else {
422 // Not a key or a motion
423 return false;
424 }
425 if (!shouldReportMetricsForConnection(connection)) {
426 return false;
427 }
428 return true;
429}
430
Prabir Pradhancef936d2021-07-21 16:17:52 +0000431/**
432 * Connection is responsive if it has no events in the waitQueue that are older than the
433 * current time.
434 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000435bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000436 const nsecs_t currentTime = now();
437 for (const DispatchEntry* entry : connection.waitQueue) {
438 if (entry->timeoutTime < currentTime) {
439 return false;
440 }
441 }
442 return true;
443}
444
Antonio Kantekf16f2832021-09-28 04:39:20 +0000445// Returns true if the event type passed as argument represents a user activity.
446bool isUserActivityEvent(const EventEntry& eventEntry) {
447 switch (eventEntry.type) {
448 case EventEntry::Type::FOCUS:
449 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
450 case EventEntry::Type::DRAG:
451 case EventEntry::Type::TOUCH_MODE_CHANGED:
452 case EventEntry::Type::SENSOR:
453 case EventEntry::Type::CONFIGURATION_CHANGED:
454 return false;
455 case EventEntry::Type::DEVICE_RESET:
456 case EventEntry::Type::KEY:
457 case EventEntry::Type::MOTION:
458 return true;
459 }
460}
461
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800462// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700463bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
464 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800465 const auto inputConfig = windowInfo.inputConfig;
466 if (windowInfo.displayId != displayId ||
467 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800468 return false;
469 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700470 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800471 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800472 return false;
473 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800474 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800475 return false;
476 }
477 return true;
478}
479
Prabir Pradhand65552b2021-10-07 11:23:50 -0700480bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
481 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
482 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
483 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
484}
485
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000486// Determines if the given window can be targeted as InputTarget::FLAG_FOREGROUND.
487// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
488// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
489// be sent to such a window, but it is not a foreground event and doesn't use
490// InputTarget::FLAG_FOREGROUND.
491bool canReceiveForegroundTouches(const WindowInfo& info) {
492 // A non-touchable window can still receive touch events (e.g. in the case of
493 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
494 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
495}
496
Antonio Kantek48710e42022-03-24 14:19:30 -0700497bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
498 if (windowHandle == nullptr) {
499 return false;
500 }
501 const WindowInfo* windowInfo = windowHandle->getInfo();
502 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
503 return true;
504 }
505 return false;
506}
507
Prabir Pradhan5735a322022-04-11 17:23:34 +0000508// Checks targeted injection using the window's owner's uid.
509// Returns an empty string if an entry can be sent to the given window, or an error message if the
510// entry is a targeted injection whose uid target doesn't match the window owner.
511std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
512 const EventEntry& entry) {
513 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
514 // The event was not injected, or the injected event does not target a window.
515 return {};
516 }
517 const int32_t uid = *entry.injectionState->targetUid;
518 if (window == nullptr) {
519 return StringPrintf("No valid window target for injection into uid %d.", uid);
520 }
521 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
522 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
523 "owned by uid %d.",
524 uid, window->getName().c_str(), window->getInfo()->ownerUid);
525 }
526 return {};
527}
528
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700529Point resolveTouchedPosition(const MotionEntry& entry) {
530 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
531 // Always dispatch mouse events to cursor position.
532 if (isFromMouse) {
533 return Point(static_cast<int32_t>(entry.xCursorPosition),
534 static_cast<int32_t>(entry.yCursorPosition));
535 }
536
537 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
538 return Point(static_cast<int32_t>(
539 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X)),
540 static_cast<int32_t>(
541 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)));
542}
543
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000544} // namespace
545
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546// --- InputDispatcher ---
547
Garfield Tan00f511d2019-06-12 16:55:40 -0700548InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800549 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
550
551InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
552 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700553 : mPolicy(policy),
554 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700555 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800556 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700557 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700558 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700559 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800560 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700561 mDispatchEnabled(false),
562 mDispatchFrozen(false),
563 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100564 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000565 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800566 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800567 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000568 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000569 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700570 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800571 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700573 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700574#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700575 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700576#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700577 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800578 policy->getDispatcherConfiguration(&mConfig);
579}
580
581InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000582 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583
Prabir Pradhancef936d2021-07-21 16:17:52 +0000584 resetKeyRepeatLocked();
585 releasePendingEventLocked();
586 drainInboundQueueLocked();
587 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800588
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000589 while (!mConnectionsByToken.empty()) {
590 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000591 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
592 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593 }
594}
595
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700596status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700597 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700598 return ALREADY_EXISTS;
599 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700600 mThread = std::make_unique<InputThread>(
601 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
602 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700603}
604
605status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700606 if (mThread && mThread->isCallingThread()) {
607 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700608 return INVALID_OPERATION;
609 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700610 mThread.reset();
611 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700612}
613
Michael Wrightd02c5b62014-02-10 15:10:22 -0800614void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700615 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800617 std::scoped_lock _l(mLock);
618 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800619
620 // Run a dispatch loop if there are no pending commands.
621 // The dispatch loop might enqueue commands to run afterwards.
622 if (!haveCommandsLocked()) {
623 dispatchOnceInnerLocked(&nextWakeupTime);
624 }
625
626 // Run all pending commands if there are any.
627 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000628 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700629 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800631
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700632 // If we are still waiting for ack on some events,
633 // we might have to wake up earlier to check if an app is anr'ing.
634 const nsecs_t nextAnrCheck = processAnrsLocked();
635 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
636
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800637 // We are about to enter an infinitely long sleep, because we have no commands or
638 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700639 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800640 mDispatcherEnteredIdle.notify_all();
641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642 } // release lock
643
644 // Wait for callback or timeout or wake. (make sure we round up, not down)
645 nsecs_t currentTime = now();
646 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
647 mLooper->pollOnce(timeoutMillis);
648}
649
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700650/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500651 * Raise ANR if there is no focused window.
652 * Before the ANR is raised, do a final state check:
653 * 1. The currently focused application must be the same one we are waiting for.
654 * 2. Ensure we still don't have a focused window.
655 */
656void InputDispatcher::processNoFocusedWindowAnrLocked() {
657 // Check if the application that we are waiting for is still focused.
658 std::shared_ptr<InputApplicationHandle> focusedApplication =
659 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
660 if (focusedApplication == nullptr ||
661 focusedApplication->getApplicationToken() !=
662 mAwaitedFocusedApplication->getApplicationToken()) {
663 // Unexpected because we should have reset the ANR timer when focused application changed
664 ALOGE("Waited for a focused window, but focused application has already changed to %s",
665 focusedApplication->getName().c_str());
666 return; // The focused application has changed.
667 }
668
chaviw98318de2021-05-19 16:45:23 -0500669 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500670 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
671 if (focusedWindowHandle != nullptr) {
672 return; // We now have a focused window. No need for ANR.
673 }
674 onAnrLocked(mAwaitedFocusedApplication);
675}
676
677/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700678 * Check if any of the connections' wait queues have events that are too old.
679 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
680 * Return the time at which we should wake up next.
681 */
682nsecs_t InputDispatcher::processAnrsLocked() {
683 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700684 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700685 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
686 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
687 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500688 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700689 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500690 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700691 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700692 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500693 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700694 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
695 }
696 }
697
698 // Check if any connection ANRs are due
699 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
700 if (currentTime < nextAnrCheck) { // most likely scenario
701 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
702 }
703
704 // If we reached here, we have an unresponsive connection.
705 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
706 if (connection == nullptr) {
707 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
708 return nextAnrCheck;
709 }
710 connection->responsive = false;
711 // Stop waking up for this unresponsive connection
712 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000713 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700714 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700715}
716
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800717std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
718 const sp<Connection>& connection) {
719 if (connection->monitor) {
720 return mMonitorDispatchingTimeout;
721 }
722 const sp<WindowInfoHandle> window =
723 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700724 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500725 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700726 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500727 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700728}
729
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
731 nsecs_t currentTime = now();
732
Jeff Browndc5992e2014-04-11 01:27:26 -0700733 // Reset the key repeat timer whenever normal dispatch is suspended while the
734 // device is in a non-interactive state. This is to ensure that we abort a key
735 // repeat if the device is just coming out of sleep.
736 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 resetKeyRepeatLocked();
738 }
739
740 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
741 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100742 if (DEBUG_FOCUS) {
743 ALOGD("Dispatch frozen. Waiting some more.");
744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745 return;
746 }
747
748 // Optimize latency of app switches.
749 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
750 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
751 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
752 if (mAppSwitchDueTime < *nextWakeupTime) {
753 *nextWakeupTime = mAppSwitchDueTime;
754 }
755
756 // Ready to start a new event.
757 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700759 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 if (isAppSwitchDue) {
761 // The inbound queue is empty so the app switch key we were waiting
762 // for will never arrive. Stop waiting for it.
763 resetPendingAppSwitchLocked(false);
764 isAppSwitchDue = false;
765 }
766
767 // Synthesize a key repeat if appropriate.
768 if (mKeyRepeatState.lastKeyEntry) {
769 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
770 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
771 } else {
772 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
773 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
774 }
775 }
776 }
777
778 // Nothing to do if there is no pending event.
779 if (!mPendingEvent) {
780 return;
781 }
782 } else {
783 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700784 mPendingEvent = mInboundQueue.front();
785 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 traceInboundQueueLengthLocked();
787 }
788
789 // Poke user activity for this event.
790 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700791 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 }
794
795 // Now we have an event to dispatch.
796 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700797 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700799 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700801 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700803 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 }
805
806 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700807 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 }
809
810 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700811 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700812 const ConfigurationChangedEntry& typedEntry =
813 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700814 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700815 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700816 break;
817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700819 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700820 const DeviceResetEntry& typedEntry =
821 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700823 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 break;
825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100827 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700828 std::shared_ptr<FocusEntry> typedEntry =
829 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100830 dispatchFocusLocked(currentTime, typedEntry);
831 done = true;
832 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
833 break;
834 }
835
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700836 case EventEntry::Type::TOUCH_MODE_CHANGED: {
837 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
838 dispatchTouchModeChangeLocked(currentTime, typedEntry);
839 done = true;
840 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
841 break;
842 }
843
Prabir Pradhan99987712020-11-10 18:43:05 -0800844 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
845 const auto typedEntry =
846 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
847 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
848 done = true;
849 break;
850 }
851
arthurhungb89ccb02020-12-30 16:19:01 +0800852 case EventEntry::Type::DRAG: {
853 std::shared_ptr<DragEntry> typedEntry =
854 std::static_pointer_cast<DragEntry>(mPendingEvent);
855 dispatchDragLocked(currentTime, typedEntry);
856 done = true;
857 break;
858 }
859
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700860 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700861 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700863 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700864 resetPendingAppSwitchLocked(true);
865 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700866 } else if (dropReason == DropReason::NOT_DROPPED) {
867 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700868 }
869 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700870 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700872 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700873 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
874 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700876 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700877 break;
878 }
879
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700880 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700881 std::shared_ptr<MotionEntry> motionEntry =
882 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
884 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700886 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700887 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700889 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
890 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700891 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700892 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700893 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 }
Chris Yef59a2f42020-10-16 12:55:26 -0700895
896 case EventEntry::Type::SENSOR: {
897 std::shared_ptr<SensorEntry> sensorEntry =
898 std::static_pointer_cast<SensorEntry>(mPendingEvent);
899 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
900 dropReason = DropReason::APP_SWITCH;
901 }
902 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
903 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
904 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
905 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
906 dropReason = DropReason::STALE;
907 }
908 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
909 done = true;
910 break;
911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 }
913
914 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700915 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700916 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917 }
Michael Wright3a981722015-06-10 15:26:13 +0100918 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919
920 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -0700921 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 }
923}
924
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800925bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
926 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
927}
928
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700929/**
930 * Return true if the events preceding this incoming motion event should be dropped
931 * Return false otherwise (the default behaviour)
932 */
933bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700934 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700935 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700936
937 // Optimize case where the current application is unresponsive and the user
938 // decides to touch a window in a different application.
939 // If the application takes too long to catch up then we drop all events preceding
940 // the touch into the other window.
941 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700942 const int32_t displayId = motionEntry.displayId;
943 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700944 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700945
chaviw98318de2021-05-19 16:45:23 -0500946 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700947 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700948 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700949 touchedWindowHandle->getApplicationToken() !=
950 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700951 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700952 ALOGI("Pruning input queue because user touched a different application while waiting "
953 "for %s",
954 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700955 return true;
956 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700957
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800958 // Alternatively, maybe there's a spy window that could handle this event.
959 const std::vector<sp<WindowInfoHandle>> touchedSpies =
960 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
961 for (const auto& windowHandle : touchedSpies) {
962 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000963 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800964 // This spy window could take more input. Drop all events preceding this
965 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700966 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800967 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700968 mAwaitedFocusedApplication->getName().c_str());
969 return true;
970 }
971 }
972 }
973
974 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
975 // yet been processed by some connections, the dispatcher will wait for these motion
976 // events to be processed before dispatching the key event. This is because these motion events
977 // may cause a new window to be launched, which the user might expect to receive focus.
978 // To prevent waiting forever for such events, just send the key to the currently focused window
979 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
980 ALOGD("Received a new pointer down event, stop waiting for events to process and "
981 "just send the pending key event to the focused window.");
982 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700983 }
984 return false;
985}
986
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700987bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700988 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700989 mInboundQueue.push_back(std::move(newEntry));
990 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 traceInboundQueueLengthLocked();
992
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700993 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700994 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +0000995 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
996 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700997 // Optimize app switch latency.
998 // If the application takes too long to catch up then we drop all events preceding
999 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001000 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001001 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001002 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001003 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001004 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001005 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001006 if (DEBUG_APP_SWITCH) {
1007 ALOGD("App switch is pending!");
1008 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001009 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001010 mAppSwitchSawKeyDown = false;
1011 needWake = true;
1012 }
1013 }
1014 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001015
1016 // If a new up event comes in, and the pending event with same key code has been asked
1017 // to try again later because of the policy. We have to reset the intercept key wake up
1018 // time for it may have been handled in the policy and could be dropped.
1019 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1020 mPendingEvent->type == EventEntry::Type::KEY) {
1021 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1022 if (pendingKey.keyCode == keyEntry.keyCode &&
1023 pendingKey.interceptKeyResult ==
1024 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1025 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1026 pendingKey.interceptKeyWakeupTime = 0;
1027 needWake = true;
1028 }
1029 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001030 break;
1031 }
1032
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001033 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001034 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1035 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001036 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1037 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001038 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001040 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001042 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001043 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1044 break;
1045 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001046 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001047 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001048 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001049 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001050 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1051 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001052 // nothing to do
1053 break;
1054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 }
1056
1057 return needWake;
1058}
1059
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001060void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001061 // Do not store sensor event in recent queue to avoid flooding the queue.
1062 if (entry->type != EventEntry::Type::SENSOR) {
1063 mRecentQueue.push_back(entry);
1064 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001065 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001066 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
1068}
1069
chaviw98318de2021-05-19 16:45:23 -05001070sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1071 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001072 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001073 bool addOutsideTargets,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07001074 bool ignoreDragWindow) const {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001075 if (addOutsideTargets && touchState == nullptr) {
1076 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001077 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001079 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001080 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001081 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001082 continue;
1083 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001085 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001086 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001087 return windowHandle;
1088 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001089
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001090 if (addOutsideTargets &&
1091 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001092 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1093 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 }
1095 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001096 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097}
1098
Prabir Pradhand65552b2021-10-07 11:23:50 -07001099std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1100 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001101 // Traverse windows from front to back and gather the touched spy windows.
1102 std::vector<sp<WindowInfoHandle>> spyWindows;
1103 const auto& windowHandles = getWindowHandlesLocked(displayId);
1104 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1105 const WindowInfo& info = *windowHandle->getInfo();
1106
Prabir Pradhand65552b2021-10-07 11:23:50 -07001107 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001108 continue;
1109 }
1110 if (!info.isSpy()) {
1111 // The first touched non-spy window was found, so return the spy windows touched so far.
1112 return spyWindows;
1113 }
1114 spyWindows.push_back(windowHandle);
1115 }
1116 return spyWindows;
1117}
1118
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001119void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 const char* reason;
1121 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001122 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001123 if (DEBUG_INBOUND_EVENT_DETAILS) {
1124 ALOGD("Dropped event because policy consumed it.");
1125 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001126 reason = "inbound event was dropped because the policy consumed it";
1127 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001128 case DropReason::DISABLED:
1129 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001130 ALOGI("Dropped event because input dispatch is disabled.");
1131 }
1132 reason = "inbound event was dropped because input dispatch is disabled";
1133 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001134 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001135 ALOGI("Dropped event because of pending overdue app switch.");
1136 reason = "inbound event was dropped because of pending overdue app switch";
1137 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001138 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001139 ALOGI("Dropped event because the current application is not responding and the user "
1140 "has started interacting with a different application.");
1141 reason = "inbound event was dropped because the current application is not responding "
1142 "and the user has started interacting with a different application";
1143 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001144 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001145 ALOGI("Dropped event because it is stale.");
1146 reason = "inbound event was dropped because it is stale";
1147 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001148 case DropReason::NO_POINTER_CAPTURE:
1149 ALOGI("Dropped event because there is no window with Pointer Capture.");
1150 reason = "inbound event was dropped because there is no window with Pointer Capture";
1151 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001152 case DropReason::NOT_DROPPED: {
1153 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001154 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 }
1157
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001158 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001159 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1161 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001162 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001164 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001165 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1166 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001167 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1168 synthesizeCancelationEventsForAllConnectionsLocked(options);
1169 } else {
1170 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1171 synthesizeCancelationEventsForAllConnectionsLocked(options);
1172 }
1173 break;
1174 }
Chris Yef59a2f42020-10-16 12:55:26 -07001175 case EventEntry::Type::SENSOR: {
1176 break;
1177 }
arthurhungb89ccb02020-12-30 16:19:01 +08001178 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1179 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001180 break;
1181 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001182 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001183 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001184 case EventEntry::Type::CONFIGURATION_CHANGED:
1185 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001186 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001187 break;
1188 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 }
1190}
1191
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001192static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001193 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1194 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195}
1196
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001197bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1198 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1199 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1200 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201}
1202
1203bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001204 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205}
1206
1207void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001208 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001210 if (DEBUG_APP_SWITCH) {
1211 if (handled) {
1212 ALOGD("App switch has arrived.");
1213 } else {
1214 ALOGD("App switch was abandoned.");
1215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217}
1218
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001220 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221}
1222
Prabir Pradhancef936d2021-07-21 16:17:52 +00001223bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001224 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 return false;
1226 }
1227
1228 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001229 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001230 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001231 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1232 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001233 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 return true;
1235}
1236
Prabir Pradhancef936d2021-07-21 16:17:52 +00001237void InputDispatcher::postCommandLocked(Command&& command) {
1238 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239}
1240
1241void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001242 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001243 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001244 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 releaseInboundEventLocked(entry);
1246 }
1247 traceInboundQueueLengthLocked();
1248}
1249
1250void InputDispatcher::releasePendingEventLocked() {
1251 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001253 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 }
1255}
1256
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001257void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001259 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001260 if (DEBUG_DISPATCH_CYCLE) {
1261 ALOGD("Injected inbound event was dropped.");
1262 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001263 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 }
1265 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001266 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 }
1268 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269}
1270
1271void InputDispatcher::resetKeyRepeatLocked() {
1272 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001273 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 }
1275}
1276
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001277std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1278 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279
Michael Wright2e732952014-09-24 13:26:59 -07001280 uint32_t policyFlags = entry->policyFlags &
1281 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001282
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001283 std::shared_ptr<KeyEntry> newEntry =
1284 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1285 entry->source, entry->displayId, policyFlags, entry->action,
1286 entry->flags, entry->keyCode, entry->scanCode,
1287 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001289 newEntry->syntheticRepeat = true;
1290 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001292 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293}
1294
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001295bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001296 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001297 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1298 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1299 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300
1301 // Reset key repeating in case a keyboard device was added or removed or something.
1302 resetKeyRepeatLocked();
1303
1304 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001305 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1306 scoped_unlock unlock(mLock);
1307 mPolicy->notifyConfigurationChanged(eventTime);
1308 };
1309 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 return true;
1311}
1312
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001313bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1314 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001315 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1316 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1317 entry.deviceId);
1318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319
liushenxiang42232912021-05-21 20:24:09 +08001320 // Reset key repeating in case a keyboard device was disabled or enabled.
1321 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1322 resetKeyRepeatLocked();
1323 }
1324
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001325 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001326 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 synthesizeCancelationEventsForAllConnectionsLocked(options);
1328 return true;
1329}
1330
Vishnu Nairad321cd2020-08-20 16:40:21 -07001331void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001332 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001333 if (mPendingEvent != nullptr) {
1334 // Move the pending event to the front of the queue. This will give the chance
1335 // for the pending event to get dispatched to the newly focused window
1336 mInboundQueue.push_front(mPendingEvent);
1337 mPendingEvent = nullptr;
1338 }
1339
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001340 std::unique_ptr<FocusEntry> focusEntry =
1341 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1342 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001343
1344 // This event should go to the front of the queue, but behind all other focus events
1345 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001346 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001347 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001348 [](const std::shared_ptr<EventEntry>& event) {
1349 return event->type == EventEntry::Type::FOCUS;
1350 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001351
1352 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001353 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001354}
1355
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001356void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001357 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001358 if (channel == nullptr) {
1359 return; // Window has gone away
1360 }
1361 InputTarget target;
1362 target.inputChannel = channel;
1363 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1364 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001365 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1366 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001367 std::string reason = std::string("reason=").append(entry->reason);
1368 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001369 dispatchEventLocked(currentTime, entry, {target});
1370}
1371
Prabir Pradhan99987712020-11-10 18:43:05 -08001372void InputDispatcher::dispatchPointerCaptureChangedLocked(
1373 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1374 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001375 dropReason = DropReason::NOT_DROPPED;
1376
Prabir Pradhan99987712020-11-10 18:43:05 -08001377 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001378 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001379
1380 if (entry->pointerCaptureRequest.enable) {
1381 // Enable Pointer Capture.
1382 if (haveWindowWithPointerCapture &&
1383 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001384 // This can happen if pointer capture is disabled and re-enabled before we notify the
1385 // app of the state change, so there is no need to notify the app.
1386 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1387 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001388 }
1389 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001390 // This can happen if a window requests capture and immediately releases capture.
1391 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001392 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001393 return;
1394 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001395 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1396 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1397 return;
1398 }
1399
Vishnu Nairc519ff72021-01-21 08:23:08 -08001400 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001401 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1402 mWindowTokenWithPointerCapture = token;
1403 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001404 // Disable Pointer Capture.
1405 // We do not check if the sequence number matches for requests to disable Pointer Capture
1406 // for two reasons:
1407 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1408 // to disable capture with the same sequence number: one generated by
1409 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1410 // Capture being disabled in InputReader.
1411 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1412 // actual Pointer Capture state that affects events being generated by input devices is
1413 // in InputReader.
1414 if (!haveWindowWithPointerCapture) {
1415 // Pointer capture was already forcefully disabled because of focus change.
1416 dropReason = DropReason::NOT_DROPPED;
1417 return;
1418 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001419 token = mWindowTokenWithPointerCapture;
1420 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001421 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001422 setPointerCaptureLocked(false);
1423 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001424 }
1425
1426 auto channel = getInputChannelLocked(token);
1427 if (channel == nullptr) {
1428 // Window has gone away, clean up Pointer Capture state.
1429 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001430 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001431 setPointerCaptureLocked(false);
1432 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001433 return;
1434 }
1435 InputTarget target;
1436 target.inputChannel = channel;
1437 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1438 entry->dispatchInProgress = true;
1439 dispatchEventLocked(currentTime, entry, {target});
1440
1441 dropReason = DropReason::NOT_DROPPED;
1442}
1443
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001444void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1445 const std::shared_ptr<TouchModeEntry>& entry) {
1446 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001447 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001448 if (windowHandles.empty()) {
1449 return;
1450 }
1451 const std::vector<InputTarget> inputTargets =
1452 getInputTargetsFromWindowHandlesLocked(windowHandles);
1453 if (inputTargets.empty()) {
1454 return;
1455 }
1456 entry->dispatchInProgress = true;
1457 dispatchEventLocked(currentTime, entry, inputTargets);
1458}
1459
1460std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1461 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1462 std::vector<InputTarget> inputTargets;
1463 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001464 const sp<IBinder>& token = handle->getToken();
1465 if (token == nullptr) {
1466 continue;
1467 }
1468 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1469 if (channel == nullptr) {
1470 continue; // Window has gone away
1471 }
1472 InputTarget target;
1473 target.inputChannel = channel;
1474 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1475 inputTargets.push_back(target);
1476 }
1477 return inputTargets;
1478}
1479
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001480bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001481 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001483 if (!entry->dispatchInProgress) {
1484 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1485 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1486 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1487 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001488 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 // We have seen two identical key downs in a row which indicates that the device
1490 // driver is automatically generating key repeats itself. We take note of the
1491 // repeat here, but we disable our own next key repeat timer since it is clear that
1492 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001493 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1494 // Make sure we don't get key down from a different device. If a different
1495 // device Id has same key pressed down, the new device Id will replace the
1496 // current one to hold the key repeat with repeat count reset.
1497 // In the future when got a KEY_UP on the device id, drop it and do not
1498 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1500 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001501 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 } else {
1503 // Not a repeat. Save key down state in case we do see a repeat later.
1504 resetKeyRepeatLocked();
1505 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1506 }
1507 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001508 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1509 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001510 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001511 if (DEBUG_INBOUND_EVENT_DETAILS) {
1512 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1513 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001514 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 resetKeyRepeatLocked();
1516 }
1517
1518 if (entry->repeatCount == 1) {
1519 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1520 } else {
1521 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1522 }
1523
1524 entry->dispatchInProgress = true;
1525
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001526 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 }
1528
1529 // Handle case where the policy asked us to try again later last time.
1530 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1531 if (currentTime < entry->interceptKeyWakeupTime) {
1532 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1533 *nextWakeupTime = entry->interceptKeyWakeupTime;
1534 }
1535 return false; // wait until next wakeup
1536 }
1537 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1538 entry->interceptKeyWakeupTime = 0;
1539 }
1540
1541 // Give the policy a chance to intercept the key.
1542 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1543 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001544 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001545 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001546
1547 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1548 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1549 };
1550 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 return false; // wait for the command to run
1552 } else {
1553 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1554 }
1555 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001556 if (*dropReason == DropReason::NOT_DROPPED) {
1557 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 }
1559 }
1560
1561 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001562 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001563 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001564 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1565 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001566 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 return true;
1568 }
1569
1570 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001571 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001572 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001573 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001574 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 return false;
1576 }
1577
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001578 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001579 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 return true;
1581 }
1582
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001583 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001584 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585
1586 // Dispatch the key.
1587 dispatchEventLocked(currentTime, entry, inputTargets);
1588 return true;
1589}
1590
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001591void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001592 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1593 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1594 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1595 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1596 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1597 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1598 entry.metaState, entry.repeatCount, entry.downTime);
1599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600}
1601
Prabir Pradhancef936d2021-07-21 16:17:52 +00001602void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1603 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001604 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001605 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1606 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1607 "source=0x%x, sensorType=%s",
1608 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001609 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001610 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001611 auto command = [this, entry]() REQUIRES(mLock) {
1612 scoped_unlock unlock(mLock);
1613
1614 if (entry->accuracyChanged) {
1615 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1616 }
1617 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1618 entry->hwTimestamp, entry->values);
1619 };
1620 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001621}
1622
1623bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001624 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1625 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001626 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001627 }
Chris Yef59a2f42020-10-16 12:55:26 -07001628 { // acquire lock
1629 std::scoped_lock _l(mLock);
1630
1631 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1632 std::shared_ptr<EventEntry> entry = *it;
1633 if (entry->type == EventEntry::Type::SENSOR) {
1634 it = mInboundQueue.erase(it);
1635 releaseInboundEventLocked(entry);
1636 }
1637 }
1638 }
1639 return true;
1640}
1641
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001642bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001643 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001644 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001646 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 entry->dispatchInProgress = true;
1648
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001649 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 }
1651
1652 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001653 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001654 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001655 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1656 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 return true;
1658 }
1659
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001660 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001661
1662 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001663 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664
1665 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001666 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 if (isPointerEvent) {
1668 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001669
1670 if (mDragState &&
1671 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1672 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1673 pilferPointersLocked(mDragState->dragWindow->getToken());
1674 }
1675
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001676 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001677 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001678 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 } else {
1680 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001681 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001682 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001684 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 return false;
1686 }
1687
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001688 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001689 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001690 return true;
1691 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001692 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001693 CancelationOptions::Mode mode(isPointerEvent
1694 ? CancelationOptions::CANCEL_POINTER_EVENTS
1695 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1696 CancelationOptions options(mode, "input event injection failed");
1697 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001698 return true;
1699 }
1700
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001701 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001702 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703
1704 // Dispatch the motion.
1705 if (conflictingPointerActions) {
1706 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001707 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 synthesizeCancelationEventsForAllConnectionsLocked(options);
1709 }
1710 dispatchEventLocked(currentTime, entry, inputTargets);
1711 return true;
1712}
1713
chaviw98318de2021-05-19 16:45:23 -05001714void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001715 bool isExiting, const int32_t rawX,
1716 const int32_t rawY) {
1717 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001718 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001719 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1720 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001721
1722 enqueueInboundEventLocked(std::move(dragEntry));
1723}
1724
1725void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1726 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1727 if (channel == nullptr) {
1728 return; // Window has gone away
1729 }
1730 InputTarget target;
1731 target.inputChannel = channel;
1732 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1733 entry->dispatchInProgress = true;
1734 dispatchEventLocked(currentTime, entry, {target});
1735}
1736
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001737void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001738 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1739 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1740 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001741 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001742 "metaState=0x%x, buttonState=0x%x,"
1743 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1744 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001745 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1746 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1747 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001749 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1750 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1751 "x=%f, y=%f, pressure=%f, size=%f, "
1752 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1753 "orientation=%f",
1754 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1755 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1756 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1757 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1758 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1759 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1760 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1761 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1762 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1763 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766}
1767
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001768void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1769 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001770 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001771 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001772 if (DEBUG_DISPATCH_CYCLE) {
1773 ALOGD("dispatchEventToCurrentInputTargets");
1774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001776 updateInteractionTokensLocked(*eventEntry, inputTargets);
1777
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1779
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001780 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001782 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001783 sp<Connection> connection =
1784 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001785 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001786 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001788 if (DEBUG_FOCUS) {
1789 ALOGD("Dropping event delivery to target with channel '%s' because it "
1790 "is no longer registered with the input dispatcher.",
1791 inputTarget.inputChannel->getName().c_str());
1792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 }
1794 }
1795}
1796
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001797void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1798 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1799 // If the policy decides to close the app, we will get a channel removal event via
1800 // unregisterInputChannel, and will clean up the connection that way. We are already not
1801 // sending new pointers to the connection when it blocked, but focused events will continue to
1802 // pile up.
1803 ALOGW("Canceling events for %s because it is unresponsive",
1804 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001805 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001806 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1807 "application not responding");
1808 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 }
1810}
1811
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001812void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001813 if (DEBUG_FOCUS) {
1814 ALOGD("Resetting ANR timeouts.");
1815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816
1817 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001818 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001819 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820}
1821
Tiger Huang721e26f2018-07-24 22:26:19 +08001822/**
1823 * Get the display id that the given event should go to. If this event specifies a valid display id,
1824 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1825 * Focused display is the display that the user most recently interacted with.
1826 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001827int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001828 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001829 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001830 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001831 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1832 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001833 break;
1834 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001835 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001836 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1837 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001838 break;
1839 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001840 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001841 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001842 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001843 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001844 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001845 case EventEntry::Type::SENSOR:
1846 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001847 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001848 return ADISPLAY_ID_NONE;
1849 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001850 }
1851 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1852}
1853
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001854bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1855 const char* focusedWindowName) {
1856 if (mAnrTracker.empty()) {
1857 // already processed all events that we waited for
1858 mKeyIsWaitingForEventsTimeout = std::nullopt;
1859 return false;
1860 }
1861
1862 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1863 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001864 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001865 mKeyIsWaitingForEventsTimeout = currentTime +
1866 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1867 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001868 return true;
1869 }
1870
1871 // We still have pending events, and already started the timer
1872 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1873 return true; // Still waiting
1874 }
1875
1876 // Waited too long, and some connection still hasn't processed all motions
1877 // Just send the key to the focused window
1878 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1879 focusedWindowName);
1880 mKeyIsWaitingForEventsTimeout = std::nullopt;
1881 return false;
1882}
1883
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001884static std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
1885 if (eventEntry.type == EventEntry::Type::KEY) {
1886 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
1887 return keyEntry.downTime;
1888 } else if (eventEntry.type == EventEntry::Type::MOTION) {
1889 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
1890 return motionEntry.downTime;
1891 }
1892 return std::nullopt;
1893}
1894
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001895InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1896 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1897 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001898 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899
Tiger Huang721e26f2018-07-24 22:26:19 +08001900 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001901 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001902 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001903 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1904
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 // If there is no currently focused window and no focused application
1906 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001907 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1908 ALOGI("Dropping %s event because there is no focused window or focused application in "
1909 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001910 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001911 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001912 }
1913
Vishnu Nair062a8672021-09-03 16:07:44 -07001914 // Drop key events if requested by input feature
1915 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1916 return InputEventInjectionResult::FAILED;
1917 }
1918
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001919 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1920 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1921 // start interacting with another application via touch (app switch). This code can be removed
1922 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1923 // an app is expected to have a focused window.
1924 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1925 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1926 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001927 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1928 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1929 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001930 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001931 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001932 ALOGW("Waiting because no window has focus but %s may eventually add a "
1933 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001934 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001935 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001936 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001937 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1938 // Already raised ANR. Drop the event
1939 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001940 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001941 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001942 } else {
1943 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001944 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001945 }
1946 }
1947
1948 // we have a valid, non-null focused window
1949 resetNoFocusedWindowTimeoutLocked();
1950
Prabir Pradhan5735a322022-04-11 17:23:34 +00001951 // Verify targeted injection.
1952 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1953 ALOGW("Dropping injected event: %s", (*err).c_str());
1954 return InputEventInjectionResult::TARGET_MISMATCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 }
1956
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001957 if (focusedWindowHandle->getInfo()->inputConfig.test(
1958 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001959 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001960 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001961 }
1962
1963 // If the event is a key event, then we must wait for all previous events to
1964 // complete before delivering it because previous events may have the
1965 // side-effect of transferring focus to a different window and we want to
1966 // ensure that the following keys are sent to the new window.
1967 //
1968 // Suppose the user touches a button in a window then immediately presses "A".
1969 // If the button causes a pop-up window to appear then we want to ensure that
1970 // the "A" key is delivered to the new pop-up window. This is because users
1971 // often anticipate pending UI changes when typing on a keyboard.
1972 // To obtain this behavior, we must serialize key events with respect to all
1973 // prior input events.
1974 if (entry.type == EventEntry::Type::KEY) {
1975 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1976 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001977 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001978 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 }
1980
1981 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001982 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001983 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001984 BitSet32(0), getDownTime(entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985
1986 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001987 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988}
1989
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001990/**
1991 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1992 * that are currently unresponsive.
1993 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001994std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1995 const std::vector<Monitor>& monitors) const {
1996 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001997 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001998 [this](const Monitor& monitor) REQUIRES(mLock) {
1999 sp<Connection> connection =
2000 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002001 if (connection == nullptr) {
2002 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002003 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002004 return false;
2005 }
2006 if (!connection->responsive) {
2007 ALOGW("Unresponsive monitor %s will not get the new gesture",
2008 connection->inputChannel->getName().c_str());
2009 return false;
2010 }
2011 return true;
2012 });
2013 return responsiveMonitors;
2014}
2015
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002016InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
2017 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
2018 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002019 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021 // For security reasons, we defer updating the touch state until we are sure that
2022 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002023 const int32_t displayId = entry.displayId;
2024 const int32_t action = entry.action;
2025 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026
2027 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002028 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002029 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2030 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002032 // Copy current touch state into tempTouchState.
2033 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2034 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002035 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002036 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002037 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2038 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002039 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002040 }
2041
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002042 bool isSplit = tempTouchState.split;
2043 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2044 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2045 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002046
2047 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2048 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2049 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2050 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2051 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002052 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 bool wrongDevice = false;
2054 if (newGesture) {
2055 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002056 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002057 ALOGI("Dropping event because a pointer for a different device is already down "
2058 "in display %" PRId32,
2059 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002060 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002061 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 switchedDevice = false;
2063 wrongDevice = true;
2064 goto Failed;
2065 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002066 tempTouchState.reset();
2067 tempTouchState.down = down;
2068 tempTouchState.deviceId = entry.deviceId;
2069 tempTouchState.source = entry.source;
2070 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002072 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002073 ALOGI("Dropping move event because a pointer for a different device is already active "
2074 "in display %" PRId32,
2075 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002076 // TODO: test multiple simultaneous input streams.
Prabir Pradhan5735a322022-04-11 17:23:34 +00002077 injectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002078 switchedDevice = false;
2079 wrongDevice = true;
2080 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081 }
2082
2083 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2084 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002085 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002086 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002087 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002088 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002089 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002090 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002091
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002093 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002094 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2095 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002097 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002098 }
2099
Prabir Pradhan5735a322022-04-11 17:23:34 +00002100 // Verify targeted injection.
2101 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2102 ALOGW("Dropping injected touch event: %s", (*err).c_str());
2103 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2104 newTouchedWindowHandle = nullptr;
2105 goto Failed;
2106 }
2107
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002108 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002109 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002110 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2111 // New window supports splitting, but we should never split mouse events.
2112 isSplit = !isFromMouse;
2113 } else if (isSplit) {
2114 // New window does not support splitting but we have already split events.
2115 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002116 newTouchedWindowHandle = nullptr;
2117 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002118 } else {
2119 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002120 // be delivered to a new window which supports split touch. Pointers from a mouse device
2121 // should never be split.
2122 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002123 }
2124
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002125 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002126 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002127 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2128 newHoverWindowHandle = nullptr;
2129 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002130 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002131 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002132 }
2133
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002134 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002135 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002136 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002137 // Process the foreground window first so that it is the first to receive the event.
2138 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002139 }
2140
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002141 if (newTouchedWindows.empty()) {
2142 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2143 x, y, displayId);
2144 injectionResult = InputEventInjectionResult::FAILED;
2145 goto Failed;
2146 }
2147
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002148 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002149 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002150 continue;
2151 }
2152
2153 // Set target flags.
2154 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2155
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002156 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2157 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002158 targetFlags |= InputTarget::FLAG_FOREGROUND;
2159 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002160
2161 if (isSplit) {
2162 targetFlags |= InputTarget::FLAG_SPLIT;
2163 }
2164 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2165 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2166 } else if (isWindowObscuredLocked(windowHandle)) {
2167 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2168 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002169
2170 // Update the temporary touch state.
2171 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002172 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002173
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002174 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2175 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002177
2178 // If any existing window is pilfering pointers from newly added window, remove it
2179 BitSet32 canceledPointers = BitSet32(0);
2180 for (const TouchedWindow& window : tempTouchState.windows) {
2181 if (window.isPilferingPointers) {
2182 canceledPointers |= window.pointerIds;
2183 }
2184 }
2185 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 } else {
2187 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2188
2189 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002190 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002191 if (DEBUG_FOCUS) {
2192 ALOGD("Dropping event because the pointer is not down or we previously "
2193 "dropped the pointer down event in display %" PRId32,
2194 displayId);
2195 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002196 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 goto Failed;
2198 }
2199
arthurhung6d4bed92021-03-17 11:59:33 +08002200 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002201
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002203 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002204 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002205 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002206 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002207 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002208 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002209 newTouchedWindowHandle =
2210 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002211
Prabir Pradhan5735a322022-04-11 17:23:34 +00002212 // Verify targeted injection.
2213 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2214 ALOGW("Dropping injected event: %s", (*err).c_str());
2215 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2216 newTouchedWindowHandle = nullptr;
2217 goto Failed;
2218 }
2219
Vishnu Nair062a8672021-09-03 16:07:44 -07002220 // Drop touch events if requested by input feature
2221 if (newTouchedWindowHandle != nullptr &&
2222 shouldDropInput(entry, newTouchedWindowHandle)) {
2223 newTouchedWindowHandle = nullptr;
2224 }
2225
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002226 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2227 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002228 if (DEBUG_FOCUS) {
2229 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2230 oldTouchedWindowHandle->getName().c_str(),
2231 newTouchedWindowHandle->getName().c_str(), displayId);
2232 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002234 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2235 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2236 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237
2238 // Make a slippery entrance into the new window.
2239 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002240 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241 }
2242
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002243 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2244 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2245 targetFlags |= InputTarget::FLAG_FOREGROUND;
2246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 if (isSplit) {
2248 targetFlags |= InputTarget::FLAG_SPLIT;
2249 }
2250 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2251 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002252 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2253 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 }
2255
2256 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002257 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002258 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2259 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260 }
2261 }
2262 }
2263
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002264 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002266 // Let the previous window know that the hover sequence is over, unless we already did
2267 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002268 if (mLastHoverWindowHandle != nullptr &&
2269 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2270 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002271 if (DEBUG_HOVER) {
2272 ALOGD("Sending hover exit event to window %s.",
2273 mLastHoverWindowHandle->getName().c_str());
2274 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002275 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2276 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 }
2278
Garfield Tandf26e862020-07-01 20:18:19 -07002279 // Let the new window know that the hover sequence is starting, unless we already did it
2280 // when dispatching it as is to newTouchedWindowHandle.
2281 if (newHoverWindowHandle != nullptr &&
2282 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2283 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002284 if (DEBUG_HOVER) {
2285 ALOGD("Sending hover enter event to window %s.",
2286 newHoverWindowHandle->getName().c_str());
2287 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002288 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2289 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2290 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 }
2292 }
2293
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002294 // Ensure that we have at least one foreground window or at least one window that cannot be a
2295 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2296 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2297 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002298 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2299 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002300 return !canReceiveForegroundTouches(
2301 *touchedWindow.windowHandle->getInfo()) ||
2302 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002303 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002304 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2305 displayId, entry.getDescription().c_str());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002306 injectionResult = InputEventInjectionResult::FAILED;
2307 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 }
2309
Prabir Pradhan5735a322022-04-11 17:23:34 +00002310 // Ensure that all touched windows are valid for injection.
2311 if (entry.injectionState != nullptr) {
2312 std::string errs;
2313 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2314 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2315 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2316 // dispatched to any uid, since the coords will be zeroed out later.
2317 continue;
2318 }
2319 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2320 if (err) errs += "\n - " + *err;
2321 }
2322 if (!errs.empty()) {
2323 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2324 "%d:%s",
2325 *entry.injectionState->targetUid, errs.c_str());
2326 injectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2327 goto Failed;
2328 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002329 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002330
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 // Check whether windows listening for outside touches are owned by the same UID. If it is
2332 // set the policy flag that we will not reveal coordinate information to this window.
2333 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002334 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002335 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002336 if (foregroundWindowHandle) {
2337 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002338 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002339 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002340 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2341 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2342 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002343 InputTarget::FLAG_ZERO_COORDS,
2344 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 }
2347 }
2348 }
2349 }
2350
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 // If this is the first pointer going down and the touched window has a wallpaper
2352 // then also add the touched wallpaper windows so they are locked in for the duration
2353 // of the touch gesture.
2354 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2355 // engine only supports touch events. We would need to add a mechanism similar
2356 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2357 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002358 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002359 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002360 if (foregroundWindowHandle &&
2361 foregroundWindowHandle->getInfo()->inputConfig.test(
2362 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002363 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002364 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002365 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2366 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002367 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002368 windowHandle->getInfo()->inputConfig.test(
2369 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002370 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002371 .addOrUpdateWindow(windowHandle,
2372 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2373 InputTarget::
2374 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2375 InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002376 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377 }
2378 }
2379 }
2380 }
2381
2382 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002383 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002385 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002387 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
2388 inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 }
2390
2391 // Drop the outside or hover touch windows since we will not care about them
2392 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002393 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394
2395Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002397 if (!wrongDevice) {
2398 if (switchedDevice) {
2399 if (DEBUG_FOCUS) {
2400 ALOGD("Conflicting pointer actions: Switched to a different device.");
2401 }
2402 *outConflictingPointerActions = true;
2403 }
2404
2405 if (isHoverAction) {
2406 // Started hovering, therefore no longer down.
2407 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002408 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002409 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2410 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412 *outConflictingPointerActions = true;
2413 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002414 tempTouchState.reset();
2415 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2416 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2417 tempTouchState.deviceId = entry.deviceId;
2418 tempTouchState.source = entry.source;
2419 tempTouchState.displayId = displayId;
2420 }
2421 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2422 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2423 // All pointers up or canceled.
2424 tempTouchState.reset();
2425 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2426 // First pointer went down.
2427 if (oldState && oldState->down) {
2428 if (DEBUG_FOCUS) {
2429 ALOGD("Conflicting pointer actions: Down received while already down.");
2430 }
2431 *outConflictingPointerActions = true;
2432 }
2433 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2434 // One pointer went up.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002435 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2436 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002438 for (size_t i = 0; i < tempTouchState.windows.size();) {
2439 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2440 touchedWindow.pointerIds.clearBit(pointerId);
2441 if (touchedWindow.pointerIds.isEmpty()) {
2442 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2443 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002444 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002445 i += 1;
2446 }
2447 } else if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2448 // If no split, we suppose all touched windows should receive pointer down.
2449 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2450 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2451 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2452 // Ignore drag window for it should just track one pointer.
2453 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2454 continue;
2455 }
2456 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Jeff Brownf086ddb2014-02-11 14:28:48 -08002457 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002458 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002459
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002460 // Save changes unless the action was scroll in which case the temporary touch
2461 // state was only valid for this one action.
2462 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2463 if (tempTouchState.displayId >= 0) {
2464 mTouchStatesByDisplay[displayId] = tempTouchState;
2465 } else {
2466 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002468 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002470 // Update hover state.
2471 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 }
2473
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474 return injectionResult;
2475}
2476
arthurhung6d4bed92021-03-17 11:59:33 +08002477void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002478 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2479 // have an explicit reason to support it.
2480 constexpr bool isStylus = false;
2481
chaviw98318de2021-05-19 16:45:23 -05002482 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002483 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002484 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002485 if (dropWindow) {
2486 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002487 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002488 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002489 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002490 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002491 }
2492 mDragState.reset();
2493}
2494
2495void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002496 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002497 return;
2498 }
2499
arthurhung6d4bed92021-03-17 11:59:33 +08002500 if (!mDragState->isStartDrag) {
2501 mDragState->isStartDrag = true;
2502 mDragState->isStylusButtonDownAtStart =
2503 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2504 }
2505
Arthur Hung54745652022-04-20 07:17:41 +00002506 // Find the pointer index by id.
2507 int32_t pointerIndex = 0;
2508 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2509 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2510 if (pointerProperties.id == mDragState->pointerId) {
2511 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002512 }
Arthur Hung54745652022-04-20 07:17:41 +00002513 }
arthurhung6d4bed92021-03-17 11:59:33 +08002514
Arthur Hung54745652022-04-20 07:17:41 +00002515 if (uint32_t(pointerIndex) == entry.pointerCount) {
2516 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002517 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002518 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002519 return;
2520 }
2521
2522 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2523 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2524 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2525
2526 switch (maskedAction) {
2527 case AMOTION_EVENT_ACTION_MOVE: {
2528 // Handle the special case : stylus button no longer pressed.
2529 bool isStylusButtonDown =
2530 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2531 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2532 finishDragAndDrop(entry.displayId, x, y);
2533 return;
2534 }
2535
2536 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2537 // until we have an explicit reason to support it.
2538 constexpr bool isStylus = false;
2539
2540 const sp<WindowInfoHandle> hoverWindowHandle =
2541 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2542 isStylus, false /*addOutsideTargets*/,
2543 true /*ignoreDragWindow*/);
2544 // enqueue drag exit if needed.
2545 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2546 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2547 if (mDragState->dragHoverWindowHandle != nullptr) {
2548 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2549 y);
2550 }
2551 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2552 }
2553 // enqueue drag location if needed.
2554 if (hoverWindowHandle != nullptr) {
2555 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2556 }
2557 break;
2558 }
2559
2560 case AMOTION_EVENT_ACTION_POINTER_UP:
2561 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2562 break;
2563 }
2564 // The drag pointer is up.
2565 [[fallthrough]];
2566 case AMOTION_EVENT_ACTION_UP:
2567 finishDragAndDrop(entry.displayId, x, y);
2568 break;
2569 case AMOTION_EVENT_ACTION_CANCEL: {
2570 ALOGD("Receiving cancel when drag and drop.");
2571 sendDropWindowCommandLocked(nullptr, 0, 0);
2572 mDragState.reset();
2573 break;
2574 }
arthurhungb89ccb02020-12-30 16:19:01 +08002575 }
2576}
2577
chaviw98318de2021-05-19 16:45:23 -05002578void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002579 int32_t targetFlags, BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002580 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002581 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002582 std::vector<InputTarget>::iterator it =
2583 std::find_if(inputTargets.begin(), inputTargets.end(),
2584 [&windowHandle](const InputTarget& inputTarget) {
2585 return inputTarget.inputChannel->getConnectionToken() ==
2586 windowHandle->getToken();
2587 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002588
chaviw98318de2021-05-19 16:45:23 -05002589 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002590
2591 if (it == inputTargets.end()) {
2592 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002593 std::shared_ptr<InputChannel> inputChannel =
2594 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002595 if (inputChannel == nullptr) {
2596 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2597 return;
2598 }
2599 inputTarget.inputChannel = inputChannel;
2600 inputTarget.flags = targetFlags;
2601 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002602 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002603 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2604 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002605 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002606 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002607 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002608 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002609 inputTargets.push_back(inputTarget);
2610 it = inputTargets.end() - 1;
2611 }
2612
2613 ALOG_ASSERT(it->flags == targetFlags);
2614 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2615
chaviw1ff3d1e2020-07-01 15:53:47 -07002616 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617}
2618
Michael Wright3dd60e22019-03-27 22:06:44 +00002619void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002620 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002621 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2622 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002623
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002624 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2625 InputTarget target;
2626 target.inputChannel = monitor.inputChannel;
2627 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002628 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2629 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002630 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2631 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002632 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002633 target.setDefaultPointerTransform(target.displayTransform);
2634 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002635 }
2636}
2637
Robert Carrc9bf1d32020-04-13 17:21:08 -07002638/**
2639 * Indicate whether one window handle should be considered as obscuring
2640 * another window handle. We only check a few preconditions. Actually
2641 * checking the bounds is left to the caller.
2642 */
chaviw98318de2021-05-19 16:45:23 -05002643static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2644 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002645 // Compare by token so cloned layers aren't counted
2646 if (haveSameToken(windowHandle, otherHandle)) {
2647 return false;
2648 }
2649 auto info = windowHandle->getInfo();
2650 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002651 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002652 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002653 } else if (otherInfo->alpha == 0 &&
2654 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002655 // Those act as if they were invisible, so we don't need to flag them.
2656 // We do want to potentially flag touchable windows even if they have 0
2657 // opacity, since they can consume touches and alter the effects of the
2658 // user interaction (eg. apps that rely on
2659 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2660 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2661 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002662 } else if (info->ownerUid == otherInfo->ownerUid) {
2663 // If ownerUid is the same we don't generate occlusion events as there
2664 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002665 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002666 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002667 return false;
2668 } else if (otherInfo->displayId != info->displayId) {
2669 return false;
2670 }
2671 return true;
2672}
2673
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002674/**
2675 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2676 * untrusted, one should check:
2677 *
2678 * 1. If result.hasBlockingOcclusion is true.
2679 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2680 * BLOCK_UNTRUSTED.
2681 *
2682 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2683 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2684 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2685 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2686 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2687 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2688 *
2689 * If neither of those is true, then it means the touch can be allowed.
2690 */
2691InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002692 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2693 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002694 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002695 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002696 TouchOcclusionInfo info;
2697 info.hasBlockingOcclusion = false;
2698 info.obscuringOpacity = 0;
2699 info.obscuringUid = -1;
2700 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002701 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002702 if (windowHandle == otherHandle) {
2703 break; // All future windows are below us. Exit early.
2704 }
chaviw98318de2021-05-19 16:45:23 -05002705 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002706 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2707 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002708 if (DEBUG_TOUCH_OCCLUSION) {
2709 info.debugInfo.push_back(
2710 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2711 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002712 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2713 // we perform the checks below to see if the touch can be propagated or not based on the
2714 // window's touch occlusion mode
2715 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2716 info.hasBlockingOcclusion = true;
2717 info.obscuringUid = otherInfo->ownerUid;
2718 info.obscuringPackage = otherInfo->packageName;
2719 break;
2720 }
2721 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2722 uint32_t uid = otherInfo->ownerUid;
2723 float opacity =
2724 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2725 // Given windows A and B:
2726 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2727 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2728 opacityByUid[uid] = opacity;
2729 if (opacity > info.obscuringOpacity) {
2730 info.obscuringOpacity = opacity;
2731 info.obscuringUid = uid;
2732 info.obscuringPackage = otherInfo->packageName;
2733 }
2734 }
2735 }
2736 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002737 if (DEBUG_TOUCH_OCCLUSION) {
2738 info.debugInfo.push_back(
2739 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2740 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002741 return info;
2742}
2743
chaviw98318de2021-05-19 16:45:23 -05002744std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002745 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002746 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2747 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2748 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2749 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002750 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2751 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2752 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2753 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2754 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002755 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002756 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002757}
2758
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002759bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2760 if (occlusionInfo.hasBlockingOcclusion) {
2761 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2762 occlusionInfo.obscuringUid);
2763 return false;
2764 }
2765 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2766 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2767 "%.2f, maximum allowed = %.2f)",
2768 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2769 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2770 return false;
2771 }
2772 return true;
2773}
2774
chaviw98318de2021-05-19 16:45:23 -05002775bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002776 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002778 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2779 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002780 if (windowHandle == otherHandle) {
2781 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 }
chaviw98318de2021-05-19 16:45:23 -05002783 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002784 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002785 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786 return true;
2787 }
2788 }
2789 return false;
2790}
2791
chaviw98318de2021-05-19 16:45:23 -05002792bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002793 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002794 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2795 const WindowInfo* windowInfo = windowHandle->getInfo();
2796 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002797 if (windowHandle == otherHandle) {
2798 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002799 }
chaviw98318de2021-05-19 16:45:23 -05002800 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002801 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002802 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002803 return true;
2804 }
2805 }
2806 return false;
2807}
2808
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002809std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002810 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002811 if (applicationHandle != nullptr) {
2812 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002813 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814 } else {
2815 return applicationHandle->getName();
2816 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002817 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002818 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002820 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 }
2822}
2823
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002824void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002825 if (!isUserActivityEvent(eventEntry)) {
2826 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002827 return;
2828 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002829 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002830 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002831 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002832 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002833 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002834 if (DEBUG_DISPATCH_CYCLE) {
2835 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 return;
2838 }
2839 }
2840
2841 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002842 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002843 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002844 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2845 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002846 return;
2847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002849 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002850 eventType = USER_ACTIVITY_EVENT_TOUCH;
2851 }
2852 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002854 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002855 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2856 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002857 return;
2858 }
2859 eventType = USER_ACTIVITY_EVENT_BUTTON;
2860 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002862 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002863 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002864 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002865 break;
2866 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 }
2868
Prabir Pradhancef936d2021-07-21 16:17:52 +00002869 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2870 REQUIRES(mLock) {
2871 scoped_unlock unlock(mLock);
2872 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2873 };
2874 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875}
2876
2877void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002878 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002879 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002880 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002881 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002882 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002883 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002884 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002885 ATRACE_NAME(message.c_str());
2886 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002887 if (DEBUG_DISPATCH_CYCLE) {
2888 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2889 "globalScaleFactor=%f, pointerIds=0x%x %s",
2890 connection->getInputChannelName().c_str(), inputTarget.flags,
2891 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2892 inputTarget.getPointerInfoString().c_str());
2893 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894
2895 // Skip this event if the connection status is not normal.
2896 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002897 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002898 if (DEBUG_DISPATCH_CYCLE) {
2899 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002900 connection->getInputChannelName().c_str(),
2901 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002902 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903 return;
2904 }
2905
2906 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002907 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2908 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2909 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002910 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002912 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002913 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002914 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2915 "Splitting motion events requires a down time to be set for the "
2916 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002917 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002918 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2919 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 if (!splitMotionEntry) {
2921 return; // split event was dropped
2922 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002923 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2924 std::string reason = std::string("reason=pointer cancel on split window");
2925 android_log_event_list(LOGTAG_INPUT_CANCEL)
2926 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2927 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002928 if (DEBUG_FOCUS) {
2929 ALOGD("channel '%s' ~ Split motion event.",
2930 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002931 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002932 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002933 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2934 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935 return;
2936 }
2937 }
2938
2939 // Not splitting. Enqueue dispatch entries for the event as is.
2940 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2941}
2942
2943void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002944 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002945 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002946 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002947 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002948 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002949 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002950 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002951 ATRACE_NAME(message.c_str());
2952 }
2953
hongzuo liu95785e22022-09-06 02:51:35 +00002954 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955
2956 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002957 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002958 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002959 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002960 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002961 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002962 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002963 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002964 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002965 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002966 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002967 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002968 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969
2970 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002971 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 startDispatchCycleLocked(currentTime, connection);
2973 }
2974}
2975
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002976void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002977 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002978 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002979 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002980 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002981 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2982 connection->getInputChannelName().c_str(),
2983 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002984 ATRACE_NAME(message.c_str());
2985 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002986 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002987 if (!(inputTargetFlags & dispatchMode)) {
2988 return;
2989 }
2990 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2991
2992 // This is a new event.
2993 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002994 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002995 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002996
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002997 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2998 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002999 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003001 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003002 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003003 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003004 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003005 dispatchEntry->resolvedAction = keyEntry.action;
3006 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003008 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3009 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003010 if (DEBUG_DISPATCH_CYCLE) {
3011 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3012 "event",
3013 connection->getInputChannelName().c_str());
3014 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003015 return; // skip the inconsistent event
3016 }
3017 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003018 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003020 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003021 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003022 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3023 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3024 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3025 static_cast<int32_t>(IdGenerator::Source::OTHER);
3026 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003027 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3028 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3029 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3030 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3031 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3032 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3033 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3034 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3035 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3036 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3037 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003038 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003039 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003040 }
3041 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003042 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3043 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003044 if (DEBUG_DISPATCH_CYCLE) {
3045 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3046 "enter event",
3047 connection->getInputChannelName().c_str());
3048 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003049 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3050 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003051 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003054 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003055 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3056 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3057 }
3058 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3059 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3060 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003061
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003062 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3063 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003064 if (DEBUG_DISPATCH_CYCLE) {
3065 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3066 "event",
3067 connection->getInputChannelName().c_str());
3068 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003069 return; // skip the inconsistent event
3070 }
3071
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003072 dispatchEntry->resolvedEventId =
3073 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3074 ? mIdGenerator.nextId()
3075 : motionEntry.id;
3076 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3077 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3078 ") to MotionEvent(id=0x%" PRIx32 ").",
3079 motionEntry.id, dispatchEntry->resolvedEventId);
3080 ATRACE_NAME(message.c_str());
3081 }
3082
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003083 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3084 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3085 // Skip reporting pointer down outside focus to the policy.
3086 break;
3087 }
3088
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003089 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003090 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003091
3092 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003094 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003095 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003096 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3097 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003098 break;
3099 }
Chris Yef59a2f42020-10-16 12:55:26 -07003100 case EventEntry::Type::SENSOR: {
3101 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3102 break;
3103 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003104 case EventEntry::Type::CONFIGURATION_CHANGED:
3105 case EventEntry::Type::DEVICE_RESET: {
3106 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003107 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003108 break;
3109 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110 }
3111
3112 // Remember that we are waiting for this dispatch to complete.
3113 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003114 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 }
3116
3117 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003118 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003119 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003120}
3121
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003122/**
3123 * This function is purely for debugging. It helps us understand where the user interaction
3124 * was taking place. For example, if user is touching launcher, we will see a log that user
3125 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3126 * We will see both launcher and wallpaper in that list.
3127 * Once the interaction with a particular set of connections starts, no new logs will be printed
3128 * until the set of interacted connections changes.
3129 *
3130 * The following items are skipped, to reduce the logspam:
3131 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3132 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3133 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3134 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3135 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003136 */
3137void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3138 const std::vector<InputTarget>& targets) {
3139 // Skip ACTION_UP events, and all events other than keys and motions
3140 if (entry.type == EventEntry::Type::KEY) {
3141 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3142 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3143 return;
3144 }
3145 } else if (entry.type == EventEntry::Type::MOTION) {
3146 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3147 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3148 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3149 return;
3150 }
3151 } else {
3152 return; // Not a key or a motion
3153 }
3154
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003155 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003156 std::vector<sp<Connection>> newConnections;
3157 for (const InputTarget& target : targets) {
3158 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3159 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3160 continue; // Skip windows that receive ACTION_OUTSIDE
3161 }
3162
3163 sp<IBinder> token = target.inputChannel->getConnectionToken();
3164 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003165 if (connection == nullptr) {
3166 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003167 }
3168 newConnectionTokens.insert(std::move(token));
3169 newConnections.emplace_back(connection);
3170 }
3171 if (newConnectionTokens == mInteractionConnectionTokens) {
3172 return; // no change
3173 }
3174 mInteractionConnectionTokens = newConnectionTokens;
3175
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003176 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003177 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003178 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003179 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003180 std::string message = "Interaction with: " + targetList;
3181 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003182 message += "<none>";
3183 }
3184 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3185}
3186
chaviwfd6d3512019-03-25 13:23:49 -07003187void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003188 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003189 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003190 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3191 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003192 return;
3193 }
3194
Vishnu Nairc519ff72021-01-21 08:23:08 -08003195 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003196 if (focusedToken == token) {
3197 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003198 return;
3199 }
3200
Prabir Pradhancef936d2021-07-21 16:17:52 +00003201 auto command = [this, token]() REQUIRES(mLock) {
3202 scoped_unlock unlock(mLock);
3203 mPolicy->onPointerDownOutsideFocus(token);
3204 };
3205 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206}
3207
3208void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003210 if (ATRACE_ENABLED()) {
3211 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003212 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003213 ATRACE_NAME(message.c_str());
3214 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003215 if (DEBUG_DISPATCH_CYCLE) {
3216 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003219 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003220 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003222 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003223 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224
3225 // Publish the event.
3226 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003227 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3228 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003229 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003230 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3231 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003233 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003234 status = connection->inputPublisher
3235 .publishKeyEvent(dispatchEntry->seq,
3236 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3237 keyEntry.source, keyEntry.displayId,
3238 std::move(hmac), dispatchEntry->resolvedAction,
3239 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3240 keyEntry.scanCode, keyEntry.metaState,
3241 keyEntry.repeatCount, keyEntry.downTime,
3242 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003243 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 }
3245
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003246 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003247 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003249 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003250 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003251
chaviw82357092020-01-28 13:13:06 -08003252 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003253 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003254 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3255 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003256 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003257 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3258 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003259 // Don't apply window scale here since we don't want scale to affect raw
3260 // coordinates. The scale will be sent back to the client and applied
3261 // later when requesting relative coordinates.
3262 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3263 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003264 }
3265 usingCoords = scaledCoords;
3266 }
3267 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003268 // We don't want the dispatch target to know.
3269 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003270 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003271 scaledCoords[i].clear();
3272 }
3273 usingCoords = scaledCoords;
3274 }
3275 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003276
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003277 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003278
3279 // Publish the motion event.
3280 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003281 .publishMotionEvent(dispatchEntry->seq,
3282 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003283 motionEntry.deviceId, motionEntry.source,
3284 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003285 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003286 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003287 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003288 motionEntry.edgeFlags, motionEntry.metaState,
3289 motionEntry.buttonState,
3290 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003291 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003292 motionEntry.xPrecision, motionEntry.yPrecision,
3293 motionEntry.xCursorPosition,
3294 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003295 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003296 motionEntry.downTime, motionEntry.eventTime,
3297 motionEntry.pointerCount,
3298 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003299 break;
3300 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003301
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003302 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003303 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003304 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003305 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003306 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003307 break;
3308 }
3309
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003310 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3311 const TouchModeEntry& touchModeEntry =
3312 static_cast<const TouchModeEntry&>(eventEntry);
3313 status = connection->inputPublisher
3314 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3315 touchModeEntry.inTouchMode);
3316
3317 break;
3318 }
3319
Prabir Pradhan99987712020-11-10 18:43:05 -08003320 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3321 const auto& captureEntry =
3322 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3323 status = connection->inputPublisher
3324 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003325 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003326 break;
3327 }
3328
arthurhungb89ccb02020-12-30 16:19:01 +08003329 case EventEntry::Type::DRAG: {
3330 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3331 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3332 dragEntry.id, dragEntry.x,
3333 dragEntry.y,
3334 dragEntry.isExiting);
3335 break;
3336 }
3337
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003338 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003339 case EventEntry::Type::DEVICE_RESET:
3340 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003341 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003342 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345 }
3346
3347 // Check the result.
3348 if (status) {
3349 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003350 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003352 "This is unexpected because the wait queue is empty, so the pipe "
3353 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003354 "event to it, status=%s(%d)",
3355 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3356 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3358 } else {
3359 // Pipe is full and we are waiting for the app to finish process some events
3360 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003361 if (DEBUG_DISPATCH_CYCLE) {
3362 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3363 "waiting for the application to catch up",
3364 connection->getInputChannelName().c_str());
3365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 }
3367 } else {
3368 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003369 "status=%s(%d)",
3370 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3371 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3373 }
3374 return;
3375 }
3376
3377 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003378 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3379 connection->outboundQueue.end(),
3380 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003381 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003382 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003383 if (connection->responsive) {
3384 mAnrTracker.insert(dispatchEntry->timeoutTime,
3385 connection->inputChannel->getConnectionToken());
3386 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003387 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 }
3389}
3390
chaviw09c8d2d2020-08-24 15:48:26 -07003391std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3392 size_t size;
3393 switch (event.type) {
3394 case VerifiedInputEvent::Type::KEY: {
3395 size = sizeof(VerifiedKeyEvent);
3396 break;
3397 }
3398 case VerifiedInputEvent::Type::MOTION: {
3399 size = sizeof(VerifiedMotionEvent);
3400 break;
3401 }
3402 }
3403 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3404 return mHmacKeyManager.sign(start, size);
3405}
3406
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003407const std::array<uint8_t, 32> InputDispatcher::getSignature(
3408 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003409 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3410 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003411 // Only sign events up and down events as the purely move events
3412 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003413 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003414 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003415
3416 VerifiedMotionEvent verifiedEvent =
3417 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3418 verifiedEvent.actionMasked = actionMasked;
3419 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3420 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003421}
3422
3423const std::array<uint8_t, 32> InputDispatcher::getSignature(
3424 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3425 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3426 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3427 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003428 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003429}
3430
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003432 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003433 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003434 if (DEBUG_DISPATCH_CYCLE) {
3435 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3436 connection->getInputChannelName().c_str(), seq, toString(handled));
3437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003439 if (connection->status == Connection::Status::BROKEN ||
3440 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441 return;
3442 }
3443
3444 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003445 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3446 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3447 };
3448 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449}
3450
3451void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003452 const sp<Connection>& connection,
3453 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003454 if (DEBUG_DISPATCH_CYCLE) {
3455 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3456 connection->getInputChannelName().c_str(), toString(notify));
3457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458
3459 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003460 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003461 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003462 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003463 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003464
3465 // The connection appears to be unrecoverably broken.
3466 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003467 if (connection->status == Connection::Status::NORMAL) {
3468 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469
3470 if (notify) {
3471 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003472 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3473 connection->getInputChannelName().c_str());
3474
3475 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003476 scoped_unlock unlock(mLock);
3477 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3478 };
3479 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480 }
3481 }
3482}
3483
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003484void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3485 while (!queue.empty()) {
3486 DispatchEntry* dispatchEntry = queue.front();
3487 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003488 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489 }
3490}
3491
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003492void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003494 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495 }
3496 delete dispatchEntry;
3497}
3498
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003499int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3500 std::scoped_lock _l(mLock);
3501 sp<Connection> connection = getConnectionLocked(connectionToken);
3502 if (connection == nullptr) {
3503 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3504 connectionToken.get(), events);
3505 return 0; // remove the callback
3506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003508 bool notify;
3509 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3510 if (!(events & ALOOPER_EVENT_INPUT)) {
3511 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3512 "events=0x%x",
3513 connection->getInputChannelName().c_str(), events);
3514 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515 }
3516
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003517 nsecs_t currentTime = now();
3518 bool gotOne = false;
3519 status_t status = OK;
3520 for (;;) {
3521 Result<InputPublisher::ConsumerResponse> result =
3522 connection->inputPublisher.receiveConsumerResponse();
3523 if (!result.ok()) {
3524 status = result.error().code();
3525 break;
3526 }
3527
3528 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3529 const InputPublisher::Finished& finish =
3530 std::get<InputPublisher::Finished>(*result);
3531 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3532 finish.consumeTime);
3533 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003534 if (shouldReportMetricsForConnection(*connection)) {
3535 const InputPublisher::Timeline& timeline =
3536 std::get<InputPublisher::Timeline>(*result);
3537 mLatencyTracker
3538 .trackGraphicsLatency(timeline.inputEventId,
3539 connection->inputChannel->getConnectionToken(),
3540 std::move(timeline.graphicsTimeline));
3541 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003542 }
3543 gotOne = true;
3544 }
3545 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003546 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003547 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548 return 1;
3549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550 }
3551
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003552 notify = status != DEAD_OBJECT || !connection->monitor;
3553 if (notify) {
3554 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3555 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3556 status);
3557 }
3558 } else {
3559 // Monitor channels are never explicitly unregistered.
3560 // We do it automatically when the remote endpoint is closed so don't warn about them.
3561 const bool stillHaveWindowHandle =
3562 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3563 notify = !connection->monitor && stillHaveWindowHandle;
3564 if (notify) {
3565 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3566 connection->getInputChannelName().c_str(), events);
3567 }
3568 }
3569
3570 // Remove the channel.
3571 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3572 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573}
3574
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003575void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003577 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003578 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579 }
3580}
3581
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003582void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003583 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003584 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003585 for (const Monitor& monitor : monitors) {
3586 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003587 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003588 }
3589}
3590
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003592 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003593 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003594 if (connection == nullptr) {
3595 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003597
3598 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599}
3600
3601void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3602 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003603 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 return;
3605 }
3606
3607 nsecs_t currentTime = now();
3608
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003609 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003610 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003612 if (cancelationEvents.empty()) {
3613 return;
3614 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003615 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3616 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3617 "with reality: %s, mode=%d.",
3618 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3619 options.mode);
3620 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003621
Arthur Hungb3307ee2021-10-14 10:57:37 +00003622 std::string reason = std::string("reason=").append(options.reason);
3623 android_log_event_list(LOGTAG_INPUT_CANCEL)
3624 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3625
Svet Ganov5d3bc372020-01-26 23:11:07 -08003626 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003627 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003628 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3629 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003630 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003631 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003632 target.globalScaleFactor = windowInfo->globalScaleFactor;
3633 }
3634 target.inputChannel = connection->inputChannel;
3635 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3636
hongzuo liu95785e22022-09-06 02:51:35 +00003637 const bool wasEmpty = connection->outboundQueue.empty();
3638
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003639 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003640 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003641 switch (cancelationEventEntry->type) {
3642 case EventEntry::Type::KEY: {
3643 logOutboundKeyDetails("cancel - ",
3644 static_cast<const KeyEntry&>(*cancelationEventEntry));
3645 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003647 case EventEntry::Type::MOTION: {
3648 logOutboundMotionDetails("cancel - ",
3649 static_cast<const MotionEntry&>(*cancelationEventEntry));
3650 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003652 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003653 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003654 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3655 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003656 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003657 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003658 break;
3659 }
3660 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003661 case EventEntry::Type::DEVICE_RESET:
3662 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003663 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003664 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003665 break;
3666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667 }
3668
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003669 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3670 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003671 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003672
hongzuo liu95785e22022-09-06 02:51:35 +00003673 // If the outbound queue was previously empty, start the dispatch cycle going.
3674 if (wasEmpty && !connection->outboundQueue.empty()) {
3675 startDispatchCycleLocked(currentTime, connection);
3676 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677}
3678
Svet Ganov5d3bc372020-01-26 23:11:07 -08003679void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003680 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003681 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003682 return;
3683 }
3684
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003685 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003686 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003687
3688 if (downEvents.empty()) {
3689 return;
3690 }
3691
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003692 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003693 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3694 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003695 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003696
3697 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003698 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003699 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3700 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003701 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003702 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003703 target.globalScaleFactor = windowInfo->globalScaleFactor;
3704 }
3705 target.inputChannel = connection->inputChannel;
3706 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3707
hongzuo liu95785e22022-09-06 02:51:35 +00003708 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003709 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003710 switch (downEventEntry->type) {
3711 case EventEntry::Type::MOTION: {
3712 logOutboundMotionDetails("down - ",
3713 static_cast<const MotionEntry&>(*downEventEntry));
3714 break;
3715 }
3716
3717 case EventEntry::Type::KEY:
3718 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003719 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003720 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003721 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003722 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003723 case EventEntry::Type::SENSOR:
3724 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003725 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003726 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003727 break;
3728 }
3729 }
3730
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003731 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3732 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003733 }
3734
hongzuo liu95785e22022-09-06 02:51:35 +00003735 // If the outbound queue was previously empty, start the dispatch cycle going.
3736 if (wasEmpty && !connection->outboundQueue.empty()) {
3737 startDispatchCycleLocked(downTime, connection);
3738 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003739}
3740
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003741std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003742 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 ALOG_ASSERT(pointerIds.value != 0);
3744
3745 uint32_t splitPointerIndexMap[MAX_POINTERS];
3746 PointerProperties splitPointerProperties[MAX_POINTERS];
3747 PointerCoords splitPointerCoords[MAX_POINTERS];
3748
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003749 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003750 uint32_t splitPointerCount = 0;
3751
3752 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003753 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003755 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 uint32_t pointerId = uint32_t(pointerProperties.id);
3757 if (pointerIds.hasBit(pointerId)) {
3758 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3759 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3760 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003761 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 splitPointerCount += 1;
3763 }
3764 }
3765
3766 if (splitPointerCount != pointerIds.count()) {
3767 // This is bad. We are missing some of the pointers that we expected to deliver.
3768 // Most likely this indicates that we received an ACTION_MOVE events that has
3769 // different pointer ids than we expected based on the previous ACTION_DOWN
3770 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3771 // in this way.
3772 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003773 "we expected there to be %d pointers. This probably means we received "
3774 "a broken sequence of pointer ids from the input device.",
3775 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003776 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777 }
3778
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003779 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003781 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3782 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3784 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003785 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 uint32_t pointerId = uint32_t(pointerProperties.id);
3787 if (pointerIds.hasBit(pointerId)) {
3788 if (pointerIds.count() == 1) {
3789 // The first/last pointer went down/up.
3790 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003791 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003792 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3793 ? AMOTION_EVENT_ACTION_CANCEL
3794 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 } else {
3796 // A secondary pointer went down/up.
3797 uint32_t splitPointerIndex = 0;
3798 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3799 splitPointerIndex += 1;
3800 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003801 action = maskedAction |
3802 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 }
3804 } else {
3805 // An unrelated pointer changed.
3806 action = AMOTION_EVENT_ACTION_MOVE;
3807 }
3808 }
3809
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003810 if (action == AMOTION_EVENT_ACTION_DOWN) {
3811 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3812 "Split motion event has mismatching downTime and eventTime for "
3813 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3814 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3815 }
3816
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003817 int32_t newId = mIdGenerator.nextId();
3818 if (ATRACE_ENABLED()) {
3819 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3820 ") to MotionEvent(id=0x%" PRIx32 ").",
3821 originalMotionEntry.id, newId);
3822 ATRACE_NAME(message.c_str());
3823 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003824 std::unique_ptr<MotionEntry> splitMotionEntry =
3825 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3826 originalMotionEntry.deviceId, originalMotionEntry.source,
3827 originalMotionEntry.displayId,
3828 originalMotionEntry.policyFlags, action,
3829 originalMotionEntry.actionButton,
3830 originalMotionEntry.flags, originalMotionEntry.metaState,
3831 originalMotionEntry.buttonState,
3832 originalMotionEntry.classification,
3833 originalMotionEntry.edgeFlags,
3834 originalMotionEntry.xPrecision,
3835 originalMotionEntry.yPrecision,
3836 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003837 originalMotionEntry.yCursorPosition, splitDownTime,
3838 splitPointerCount, splitPointerProperties,
3839 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003841 if (originalMotionEntry.injectionState) {
3842 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843 splitMotionEntry->injectionState->refCount += 1;
3844 }
3845
3846 return splitMotionEntry;
3847}
3848
3849void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003850 if (DEBUG_INBOUND_EVENT_DETAILS) {
3851 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853
Antonio Kantekf16f2832021-09-28 04:39:20 +00003854 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003856 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003858 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3859 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3860 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861 } // release lock
3862
3863 if (needWake) {
3864 mLooper->wake();
3865 }
3866}
3867
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003868/**
3869 * If one of the meta shortcuts is detected, process them here:
3870 * Meta + Backspace -> generate BACK
3871 * Meta + Enter -> generate HOME
3872 * This will potentially overwrite keyCode and metaState.
3873 */
3874void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003875 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003876 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3877 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3878 if (keyCode == AKEYCODE_DEL) {
3879 newKeyCode = AKEYCODE_BACK;
3880 } else if (keyCode == AKEYCODE_ENTER) {
3881 newKeyCode = AKEYCODE_HOME;
3882 }
3883 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003884 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003885 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003886 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003887 keyCode = newKeyCode;
3888 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3889 }
3890 } else if (action == AKEY_EVENT_ACTION_UP) {
3891 // In order to maintain a consistent stream of up and down events, check to see if the key
3892 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3893 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003894 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003895 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003896 auto replacementIt = mReplacedKeys.find(replacement);
3897 if (replacementIt != mReplacedKeys.end()) {
3898 keyCode = replacementIt->second;
3899 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003900 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3901 }
3902 }
3903}
3904
Michael Wrightd02c5b62014-02-10 15:10:22 -08003905void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003906 if (DEBUG_INBOUND_EVENT_DETAILS) {
3907 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3908 "policyFlags=0x%x, action=0x%x, "
3909 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3910 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3911 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3912 args->downTime);
3913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914 if (!validateKeyEvent(args->action)) {
3915 return;
3916 }
3917
3918 uint32_t policyFlags = args->policyFlags;
3919 int32_t flags = args->flags;
3920 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003921 // InputDispatcher tracks and generates key repeats on behalf of
3922 // whatever notifies it, so repeatCount should always be set to 0
3923 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3925 policyFlags |= POLICY_FLAG_VIRTUAL;
3926 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3927 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 if (policyFlags & POLICY_FLAG_FUNCTION) {
3929 metaState |= AMETA_FUNCTION_ON;
3930 }
3931
3932 policyFlags |= POLICY_FLAG_TRUSTED;
3933
Michael Wright78f24442014-08-06 15:55:28 -07003934 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003935 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003936
Michael Wrightd02c5b62014-02-10 15:10:22 -08003937 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003938 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003939 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3940 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941
Michael Wright2b3c3302018-03-02 17:19:13 +00003942 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003944 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3945 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003946 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948
Antonio Kantekf16f2832021-09-28 04:39:20 +00003949 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 { // acquire lock
3951 mLock.lock();
3952
3953 if (shouldSendKeyToInputFilterLocked(args)) {
3954 mLock.unlock();
3955
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003956 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3958 return; // event was consumed by the filter
3959 }
3960
3961 mLock.lock();
3962 }
3963
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003964 std::unique_ptr<KeyEntry> newEntry =
3965 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3966 args->displayId, policyFlags, args->action, flags,
3967 keyCode, args->scanCode, metaState, repeatCount,
3968 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003970 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 mLock.unlock();
3972 } // release lock
3973
3974 if (needWake) {
3975 mLooper->wake();
3976 }
3977}
3978
3979bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3980 return mInputFilterEnabled;
3981}
3982
3983void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003984 if (DEBUG_INBOUND_EVENT_DETAILS) {
3985 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3986 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07003987 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003988 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
3989 "yCursorPosition=%f, downTime=%" PRId64,
3990 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07003991 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
3992 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
3993 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3994 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003995 for (uint32_t i = 0; i < args->pointerCount; i++) {
3996 ALOGD(" Pointer %d: id=%d, toolType=%d, "
3997 "x=%f, y=%f, pressure=%f, size=%f, "
3998 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3999 "orientation=%f",
4000 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4001 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4002 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4003 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4004 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4005 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4006 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4007 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4008 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4009 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004012 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4013 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014 return;
4015 }
4016
4017 uint32_t policyFlags = args->policyFlags;
4018 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004019
4020 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004021 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004022 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4023 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004024 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026
Antonio Kantekf16f2832021-09-28 04:39:20 +00004027 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028 { // acquire lock
4029 mLock.lock();
4030
4031 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004032 ui::Transform displayTransform;
4033 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4034 displayTransform = it->second.transform;
4035 }
4036
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037 mLock.unlock();
4038
4039 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004040 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4041 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004042 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004043 displayTransform, args->xPrecision, args->yPrecision,
4044 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004045 args->downTime, args->eventTime, args->pointerCount,
4046 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047
4048 policyFlags |= POLICY_FLAG_FILTERED;
4049 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4050 return; // event was consumed by the filter
4051 }
4052
4053 mLock.lock();
4054 }
4055
4056 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004057 std::unique_ptr<MotionEntry> newEntry =
4058 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4059 args->source, args->displayId, policyFlags,
4060 args->action, args->actionButton, args->flags,
4061 args->metaState, args->buttonState,
4062 args->classification, args->edgeFlags,
4063 args->xPrecision, args->yPrecision,
4064 args->xCursorPosition, args->yCursorPosition,
4065 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004066 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004068 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4069 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4070 !mInputFilterEnabled) {
4071 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4072 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4073 }
4074
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004075 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 mLock.unlock();
4077 } // release lock
4078
4079 if (needWake) {
4080 mLooper->wake();
4081 }
4082}
4083
Chris Yef59a2f42020-10-16 12:55:26 -07004084void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004085 if (DEBUG_INBOUND_EVENT_DETAILS) {
4086 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4087 " sensorType=%s",
4088 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004089 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004090 }
Chris Yef59a2f42020-10-16 12:55:26 -07004091
Antonio Kantekf16f2832021-09-28 04:39:20 +00004092 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004093 { // acquire lock
4094 mLock.lock();
4095
4096 // Just enqueue a new sensor event.
4097 std::unique_ptr<SensorEntry> newEntry =
4098 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4099 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4100 args->sensorType, args->accuracy,
4101 args->accuracyChanged, args->values);
4102
4103 needWake = enqueueInboundEventLocked(std::move(newEntry));
4104 mLock.unlock();
4105 } // release lock
4106
4107 if (needWake) {
4108 mLooper->wake();
4109 }
4110}
4111
Chris Yefb552902021-02-03 17:18:37 -08004112void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004113 if (DEBUG_INBOUND_EVENT_DETAILS) {
4114 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4115 args->deviceId, args->isOn);
4116 }
Chris Yefb552902021-02-03 17:18:37 -08004117 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4118}
4119
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004121 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122}
4123
4124void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004125 if (DEBUG_INBOUND_EVENT_DETAILS) {
4126 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4127 "switchMask=0x%08x",
4128 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4129 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130
4131 uint32_t policyFlags = args->policyFlags;
4132 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004133 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134}
4135
4136void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004137 if (DEBUG_INBOUND_EVENT_DETAILS) {
4138 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4139 args->deviceId);
4140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141
Antonio Kantekf16f2832021-09-28 04:39:20 +00004142 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004144 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004146 std::unique_ptr<DeviceResetEntry> newEntry =
4147 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4148 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 } // release lock
4150
4151 if (needWake) {
4152 mLooper->wake();
4153 }
4154}
4155
Prabir Pradhan7e186182020-11-10 13:56:45 -08004156void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004157 if (DEBUG_INBOUND_EVENT_DETAILS) {
4158 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004159 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004160 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004161
Antonio Kantekf16f2832021-09-28 04:39:20 +00004162 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004163 { // acquire lock
4164 std::scoped_lock _l(mLock);
4165 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004166 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004167 needWake = enqueueInboundEventLocked(std::move(entry));
4168 } // release lock
4169
4170 if (needWake) {
4171 mLooper->wake();
4172 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004173}
4174
Prabir Pradhan5735a322022-04-11 17:23:34 +00004175InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4176 std::optional<int32_t> targetUid,
4177 InputEventInjectionSync syncMode,
4178 std::chrono::milliseconds timeout,
4179 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004180 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004181 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4182 "policyFlags=0x%08x",
4183 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4184 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004185 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004186 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187
Prabir Pradhan5735a322022-04-11 17:23:34 +00004188 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004190 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004191 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4192 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4193 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4194 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4195 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004196 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004197 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004198 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004199 }
4200
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004201 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004203 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004204 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4205 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004206 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004207 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004208 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004210 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004211 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4212 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4213 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004214 int32_t keyCode = incomingKey.getKeyCode();
4215 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004216 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004217 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004218 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004219 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004220 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4221 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4222 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004224 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4225 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004226 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004227
4228 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4229 android::base::Timer t;
4230 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4231 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4232 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4233 std::to_string(t.duration().count()).c_str());
4234 }
4235 }
4236
4237 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004238 std::unique_ptr<KeyEntry> injectedEntry =
4239 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004240 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004241 incomingKey.getDisplayId(), policyFlags, action,
4242 flags, keyCode, incomingKey.getScanCode(), metaState,
4243 incomingKey.getRepeatCount(),
4244 incomingKey.getDownTime());
4245 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 }
4248
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004249 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004250 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004251 const int32_t action = motionEvent.getAction();
4252 const bool isPointerEvent =
4253 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4254 // If a pointer event has no displayId specified, inject it to the default display.
4255 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4256 ? ADISPLAY_ID_DEFAULT
4257 : event->getDisplayId();
4258 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004259 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004260 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004261 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004262 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004263 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004264 }
4265
4266 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004267 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 android::base::Timer t;
4269 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4270 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4271 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4272 std::to_string(t.duration().count()).c_str());
4273 }
4274 }
4275
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004276 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4277 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4278 }
4279
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004280 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004281 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4282 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004283 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004284 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4285 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004286 displayId, policyFlags, action, actionButton,
4287 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004288 motionEvent.getButtonState(),
4289 motionEvent.getClassification(),
4290 motionEvent.getEdgeFlags(),
4291 motionEvent.getXPrecision(),
4292 motionEvent.getYPrecision(),
4293 motionEvent.getRawXCursorPosition(),
4294 motionEvent.getRawYCursorPosition(),
4295 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004296 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004297 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004298 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004299 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004300 sampleEventTimes += 1;
4301 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004302 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004303 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4304 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004305 displayId, policyFlags, action, actionButton,
4306 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004307 motionEvent.getButtonState(),
4308 motionEvent.getClassification(),
4309 motionEvent.getEdgeFlags(),
4310 motionEvent.getXPrecision(),
4311 motionEvent.getYPrecision(),
4312 motionEvent.getRawXCursorPosition(),
4313 motionEvent.getRawYCursorPosition(),
4314 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004315 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004316 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004317 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4318 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004319 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004320 }
4321 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004324 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004325 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004326 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
4328
Prabir Pradhan5735a322022-04-11 17:23:34 +00004329 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004330 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 injectionState->injectionIsAsync = true;
4332 }
4333
4334 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004335 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336
4337 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004338 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004339 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004340 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 }
4342
4343 mLock.unlock();
4344
4345 if (needWake) {
4346 mLooper->wake();
4347 }
4348
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004349 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004351 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004353 if (syncMode == InputEventInjectionSync::NONE) {
4354 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 } else {
4356 for (;;) {
4357 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004358 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 break;
4360 }
4361
4362 nsecs_t remainingTimeout = endTime - now();
4363 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004364 if (DEBUG_INJECTION) {
4365 ALOGD("injectInputEvent - Timed out waiting for injection result "
4366 "to become available.");
4367 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004368 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 break;
4370 }
4371
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004372 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
4374
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004375 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4376 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004378 if (DEBUG_INJECTION) {
4379 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4380 injectionState->pendingForegroundDispatches);
4381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 nsecs_t remainingTimeout = endTime - now();
4383 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004384 if (DEBUG_INJECTION) {
4385 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4386 "dispatches to finish.");
4387 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004388 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 break;
4390 }
4391
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004392 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 }
4394 }
4395 }
4396
4397 injectionState->release();
4398 } // release lock
4399
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004400 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004401 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403
4404 return injectionResult;
4405}
4406
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004407std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004408 std::array<uint8_t, 32> calculatedHmac;
4409 std::unique_ptr<VerifiedInputEvent> result;
4410 switch (event.getType()) {
4411 case AINPUT_EVENT_TYPE_KEY: {
4412 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4413 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4414 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004415 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004416 break;
4417 }
4418 case AINPUT_EVENT_TYPE_MOTION: {
4419 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4420 VerifiedMotionEvent verifiedMotionEvent =
4421 verifiedMotionEventFromMotionEvent(motionEvent);
4422 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004423 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004424 break;
4425 }
4426 default: {
4427 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4428 return nullptr;
4429 }
4430 }
4431 if (calculatedHmac == INVALID_HMAC) {
4432 return nullptr;
4433 }
4434 if (calculatedHmac != event.getHmac()) {
4435 return nullptr;
4436 }
4437 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004438}
4439
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004440void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004441 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004442 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004444 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004445 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004448 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 // Log the outcome since the injector did not wait for the injection result.
4450 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004452 ALOGV("Asynchronous input event injection succeeded.");
4453 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004454 case InputEventInjectionResult::TARGET_MISMATCH:
4455 ALOGV("Asynchronous input event injection target mismatch.");
4456 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004457 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004458 ALOGW("Asynchronous input event injection failed.");
4459 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004460 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004461 ALOGW("Asynchronous input event injection timed out.");
4462 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004463 case InputEventInjectionResult::PENDING:
4464 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4465 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466 }
4467 }
4468
4469 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004470 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 }
4472}
4473
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004474void InputDispatcher::transformMotionEntryForInjectionLocked(
4475 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004476 // Input injection works in the logical display coordinate space, but the input pipeline works
4477 // display space, so we need to transform the injected events accordingly.
4478 const auto it = mDisplayInfos.find(entry.displayId);
4479 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004480 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004481
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004482 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4483 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4484 const vec2 cursor =
4485 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4486 {entry.xCursorPosition, entry.yCursorPosition});
4487 entry.xCursorPosition = cursor.x;
4488 entry.yCursorPosition = cursor.y;
4489 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004490 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004491 entry.pointerCoords[i] =
4492 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4493 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004494 }
4495}
4496
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004497void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4498 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 if (injectionState) {
4500 injectionState->pendingForegroundDispatches += 1;
4501 }
4502}
4503
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004504void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4505 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506 if (injectionState) {
4507 injectionState->pendingForegroundDispatches -= 1;
4508
4509 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004510 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511 }
4512 }
4513}
4514
chaviw98318de2021-05-19 16:45:23 -05004515const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004516 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004517 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004518 auto it = mWindowHandlesByDisplay.find(displayId);
4519 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004520}
4521
chaviw98318de2021-05-19 16:45:23 -05004522sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004523 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004524 if (windowHandleToken == nullptr) {
4525 return nullptr;
4526 }
4527
Arthur Hungb92218b2018-08-14 12:00:21 +08004528 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004529 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4530 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004531 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004532 return windowHandle;
4533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534 }
4535 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004536 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004537}
4538
chaviw98318de2021-05-19 16:45:23 -05004539sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4540 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004541 if (windowHandleToken == nullptr) {
4542 return nullptr;
4543 }
4544
chaviw98318de2021-05-19 16:45:23 -05004545 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004546 if (windowHandle->getToken() == windowHandleToken) {
4547 return windowHandle;
4548 }
4549 }
4550 return nullptr;
4551}
4552
chaviw98318de2021-05-19 16:45:23 -05004553sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4554 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004555 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004556 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4557 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004558 if (handle->getId() == windowHandle->getId() &&
4559 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004560 if (windowHandle->getInfo()->displayId != it.first) {
4561 ALOGE("Found window %s in display %" PRId32
4562 ", but it should belong to display %" PRId32,
4563 windowHandle->getName().c_str(), it.first,
4564 windowHandle->getInfo()->displayId);
4565 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004566 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004567 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 }
4569 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004570 return nullptr;
4571}
4572
chaviw98318de2021-05-19 16:45:23 -05004573sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004574 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4575 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576}
4577
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004578bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4579 const MotionEntry& motionEntry) const {
4580 const WindowInfo& info = *window->getInfo();
4581
4582 // Skip spy window targets that are not valid for targeted injection.
4583 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004584 return false;
4585 }
4586
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004587 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4588 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4589 return false;
4590 }
4591
4592 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4593 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4594 window->getName().c_str());
4595 return false;
4596 }
4597
4598 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004599 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004600 ALOGW("Not sending touch to %s because there's no corresponding connection",
4601 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004602 return false;
4603 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004604
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004605 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004606 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004607 return false;
4608 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004609
4610 // Drop events that can't be trusted due to occlusion
4611 const auto [x, y] = resolveTouchedPosition(motionEntry);
4612 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4613 if (!isTouchTrustedLocked(occlusionInfo)) {
4614 if (DEBUG_TOUCH_OCCLUSION) {
4615 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4616 for (const auto& log : occlusionInfo.debugInfo) {
4617 ALOGD("%s", log.c_str());
4618 }
4619 }
4620 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4621 occlusionInfo.obscuringUid);
4622 return false;
4623 }
4624
4625 // Drop touch events if requested by input feature
4626 if (shouldDropInput(motionEntry, window)) {
4627 return false;
4628 }
4629
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004630 return true;
4631}
4632
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004633std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4634 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004635 auto connectionIt = mConnectionsByToken.find(token);
4636 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004637 return nullptr;
4638 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004639 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004640}
4641
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004642void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004643 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4644 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004645 // Remove all handles on a display if there are no windows left.
4646 mWindowHandlesByDisplay.erase(displayId);
4647 return;
4648 }
4649
4650 // Since we compare the pointer of input window handles across window updates, we need
4651 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004652 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4653 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4654 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004655 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004656 }
4657
chaviw98318de2021-05-19 16:45:23 -05004658 std::vector<sp<WindowInfoHandle>> newHandles;
4659 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004660 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004661 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004662 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004663 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004664 const bool canReceiveInput =
4665 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4666 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004667 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004668 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004669 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004670 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004671 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004672 }
4673
4674 if (info->displayId != displayId) {
4675 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4676 handle->getName().c_str(), displayId, info->displayId);
4677 continue;
4678 }
4679
Robert Carredd13602020-04-13 17:24:34 -07004680 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4681 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004682 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004683 oldHandle->updateFrom(handle);
4684 newHandles.push_back(oldHandle);
4685 } else {
4686 newHandles.push_back(handle);
4687 }
4688 }
4689
4690 // Insert or replace
4691 mWindowHandlesByDisplay[displayId] = newHandles;
4692}
4693
Arthur Hung72d8dc32020-03-28 00:48:39 +00004694void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004695 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004696 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004697 { // acquire lock
4698 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004699 for (const auto& [displayId, handles] : handlesPerDisplay) {
4700 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004701 }
4702 }
4703 // Wake up poll loop since it may need to make new input dispatching choices.
4704 mLooper->wake();
4705}
4706
Arthur Hungb92218b2018-08-14 12:00:21 +08004707/**
4708 * Called from InputManagerService, update window handle list by displayId that can receive input.
4709 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4710 * If set an empty list, remove all handles from the specific display.
4711 * For focused handle, check if need to change and send a cancel event to previous one.
4712 * For removed handle, check if need to send a cancel event if already in touch.
4713 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004714void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004715 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004716 if (DEBUG_FOCUS) {
4717 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004718 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004719 windowList += iwh->getName() + " ";
4720 }
4721 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4722 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723
Prabir Pradhand65552b2021-10-07 11:23:50 -07004724 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004725 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004726 const WindowInfo& info = *window->getInfo();
4727
4728 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004729 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004730 if (noInputWindow && window->getToken() != nullptr) {
4731 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4732 window->getName().c_str());
4733 window->releaseChannel();
4734 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004735
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004736 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004737 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4738 !info.inputConfig.test(
4739 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004740 "%s has feature SPY, but is not a trusted overlay.",
4741 window->getName().c_str());
4742
Prabir Pradhand65552b2021-10-07 11:23:50 -07004743 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004744 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4745 !info.inputConfig.test(
4746 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004747 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4748 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004749 }
4750
Arthur Hung72d8dc32020-03-28 00:48:39 +00004751 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004752 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004754 // Save the old windows' orientation by ID before it gets updated.
4755 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004756 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004757 oldWindowOrientations.emplace(handle->getId(),
4758 handle->getInfo()->transform.getOrientation());
4759 }
4760
chaviw98318de2021-05-19 16:45:23 -05004761 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004762
chaviw98318de2021-05-19 16:45:23 -05004763 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004764 if (mLastHoverWindowHandle &&
4765 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4766 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004767 mLastHoverWindowHandle = nullptr;
4768 }
4769
Vishnu Nairc519ff72021-01-21 08:23:08 -08004770 std::optional<FocusResolver::FocusChanges> changes =
4771 mFocusResolver.setInputWindows(displayId, windowHandles);
4772 if (changes) {
4773 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004776 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4777 mTouchStatesByDisplay.find(displayId);
4778 if (stateIt != mTouchStatesByDisplay.end()) {
4779 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004780 for (size_t i = 0; i < state.windows.size();) {
4781 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004782 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004783 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004784 ALOGD("Touched window was removed: %s in display %" PRId32,
4785 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004786 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004787 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004788 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4789 if (touchedInputChannel != nullptr) {
4790 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4791 "touched window was removed");
4792 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004793 // Since we are about to drop the touch, cancel the events for the wallpaper as
4794 // well.
4795 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004796 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4797 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004798 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4799 if (wallpaper != nullptr) {
4800 sp<Connection> wallpaperConnection =
4801 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004802 if (wallpaperConnection != nullptr) {
4803 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4804 options);
4805 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004806 }
4807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004809 state.windows.erase(state.windows.begin() + i);
4810 } else {
4811 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 }
4813 }
arthurhungb89ccb02020-12-30 16:19:01 +08004814
arthurhung6d4bed92021-03-17 11:59:33 +08004815 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004816 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004817 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004818 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004819 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004820 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4821 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004822 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004823 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004824 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004825
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004826 // Determine if the orientation of any of the input windows have changed, and cancel all
4827 // pointer events if necessary.
4828 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4829 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4830 if (newWindowHandle != nullptr &&
4831 newWindowHandle->getInfo()->transform.getOrientation() !=
4832 oldWindowOrientations[oldWindowHandle->getId()]) {
4833 std::shared_ptr<InputChannel> inputChannel =
4834 getInputChannelLocked(newWindowHandle->getToken());
4835 if (inputChannel != nullptr) {
4836 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4837 "touched window's orientation changed");
4838 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004839 }
4840 }
4841 }
4842
Arthur Hung72d8dc32020-03-28 00:48:39 +00004843 // Release information for windows that are no longer present.
4844 // This ensures that unused input channels are released promptly.
4845 // Otherwise, they might stick around until the window handle is destroyed
4846 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004847 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004848 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004849 if (DEBUG_FOCUS) {
4850 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004851 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004852 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004853 }
chaviw291d88a2019-02-14 10:33:58 -08004854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855}
4856
4857void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004858 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004859 if (DEBUG_FOCUS) {
4860 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4861 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4862 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004863 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004864 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004865 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 } // release lock
4867
4868 // Wake up poll loop since it may need to make new input dispatching choices.
4869 mLooper->wake();
4870}
4871
Vishnu Nair599f1412021-06-21 10:39:58 -07004872void InputDispatcher::setFocusedApplicationLocked(
4873 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4874 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4875 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4876
4877 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4878 return; // This application is already focused. No need to wake up or change anything.
4879 }
4880
4881 // Set the new application handle.
4882 if (inputApplicationHandle != nullptr) {
4883 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4884 } else {
4885 mFocusedApplicationHandlesByDisplay.erase(displayId);
4886 }
4887
4888 // No matter what the old focused application was, stop waiting on it because it is
4889 // no longer focused.
4890 resetNoFocusedWindowTimeoutLocked();
4891}
4892
Tiger Huang721e26f2018-07-24 22:26:19 +08004893/**
4894 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4895 * the display not specified.
4896 *
4897 * We track any unreleased events for each window. If a window loses the ability to receive the
4898 * released event, we will send a cancel event to it. So when the focused display is changed, we
4899 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4900 * display. The display-specified events won't be affected.
4901 */
4902void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004903 if (DEBUG_FOCUS) {
4904 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4905 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004906 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004907 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004908
4909 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004910 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004911 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004912 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004913 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004914 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004915 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004916 CancelationOptions
4917 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4918 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004919 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004920 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4921 }
4922 }
4923 mFocusedDisplayId = displayId;
4924
Chris Ye3c2d6f52020-08-09 10:39:48 -07004925 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004926 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004927 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004928
Vishnu Nairad321cd2020-08-20 16:40:21 -07004929 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004930 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004931 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004932 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004933 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004934 }
4935 }
4936 }
4937
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004938 if (DEBUG_FOCUS) {
4939 logDispatchStateLocked();
4940 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004941 } // release lock
4942
4943 // Wake up poll loop since it may need to make new input dispatching choices.
4944 mLooper->wake();
4945}
4946
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004948 if (DEBUG_FOCUS) {
4949 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951
4952 bool changed;
4953 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004954 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955
4956 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4957 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004958 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 }
4960
4961 if (mDispatchEnabled && !enabled) {
4962 resetAndDropEverythingLocked("dispatcher is being disabled");
4963 }
4964
4965 mDispatchEnabled = enabled;
4966 mDispatchFrozen = frozen;
4967 changed = true;
4968 } else {
4969 changed = false;
4970 }
4971
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004972 if (DEBUG_FOCUS) {
4973 logDispatchStateLocked();
4974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004975 } // release lock
4976
4977 if (changed) {
4978 // Wake up poll loop since it may need to make new input dispatching choices.
4979 mLooper->wake();
4980 }
4981}
4982
4983void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004984 if (DEBUG_FOCUS) {
4985 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4986 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987
4988 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004989 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990
4991 if (mInputFilterEnabled == enabled) {
4992 return;
4993 }
4994
4995 mInputFilterEnabled = enabled;
4996 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4997 } // release lock
4998
4999 // Wake up poll loop since there might be work to do to drop everything.
5000 mLooper->wake();
5001}
5002
Antonio Kanteka042c022022-07-06 16:51:07 -07005003bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5004 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005005 bool needWake = false;
5006 {
5007 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005008 ALOGD_IF(DEBUG_TOUCH_MODE,
5009 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5010 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5011 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5012 mTouchModePerDisplay.count(displayId) == 0
5013 ? "not set"
5014 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5015
Antonio Kantek15beb512022-06-13 22:35:41 +00005016 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5017 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005018 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005019 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005020 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005021 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5022 !recentWindowsAreOwnedByLocked(pid, uid)) {
5023 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5024 "window nor none of the previously interacted window",
5025 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005026 return false;
5027 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005028 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005029 mTouchModePerDisplay[displayId] = inTouchMode;
5030 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5031 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005032 needWake = enqueueInboundEventLocked(std::move(entry));
5033 } // release lock
5034
5035 if (needWake) {
5036 mLooper->wake();
5037 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005038 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005039}
5040
Antonio Kantek48710e42022-03-24 14:19:30 -07005041bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5042 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5043 if (focusedToken == nullptr) {
5044 return false;
5045 }
5046 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5047 return isWindowOwnedBy(windowHandle, pid, uid);
5048}
5049
5050bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5051 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5052 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5053 const sp<WindowInfoHandle> windowHandle =
5054 getWindowHandleLocked(connectionToken);
5055 return isWindowOwnedBy(windowHandle, pid, uid);
5056 }) != mInteractionConnectionTokens.end();
5057}
5058
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005059void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5060 if (opacity < 0 || opacity > 1) {
5061 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5062 return;
5063 }
5064
5065 std::scoped_lock lock(mLock);
5066 mMaximumObscuringOpacityForTouch = opacity;
5067}
5068
Arthur Hungabbb9d82021-09-01 14:52:30 +00005069std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5070 const sp<IBinder>& token) {
5071 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5072 for (TouchedWindow& w : state.windows) {
5073 if (w.windowHandle->getToken() == token) {
5074 return std::make_pair(&state, &w);
5075 }
5076 }
5077 }
5078 return std::make_pair(nullptr, nullptr);
5079}
5080
arthurhungb89ccb02020-12-30 16:19:01 +08005081bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5082 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005083 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005084 if (DEBUG_FOCUS) {
5085 ALOGD("Trivial transfer to same window.");
5086 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005087 return true;
5088 }
5089
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005091 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092
Arthur Hungabbb9d82021-09-01 14:52:30 +00005093 // Find the target touch state and touched window by fromToken.
5094 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5095 if (state == nullptr || touchedWindow == nullptr) {
5096 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005097 return false;
5098 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005099
5100 const int32_t displayId = state->displayId;
5101 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5102 if (toWindowHandle == nullptr) {
5103 ALOGW("Cannot transfer focus because to window not found.");
5104 return false;
5105 }
5106
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005107 if (DEBUG_FOCUS) {
5108 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005109 touchedWindow->windowHandle->getName().c_str(),
5110 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111 }
5112
Arthur Hungabbb9d82021-09-01 14:52:30 +00005113 // Erase old window.
5114 int32_t oldTargetFlags = touchedWindow->targetFlags;
5115 BitSet32 pointerIds = touchedWindow->pointerIds;
5116 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117
Arthur Hungabbb9d82021-09-01 14:52:30 +00005118 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005119 nsecs_t downTimeInTarget = now();
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005120 int32_t newTargetFlags =
5121 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5122 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5123 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5124 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005125 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126
Arthur Hungabbb9d82021-09-01 14:52:30 +00005127 // Store the dragging window.
5128 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005129 if (pointerIds.count() != 1) {
5130 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5131 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005132 return false;
5133 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005134 // Track the pointer id for drag window and generate the drag state.
5135 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005136 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137 }
5138
Arthur Hungabbb9d82021-09-01 14:52:30 +00005139 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005140 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5141 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005142 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005143 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005144 CancelationOptions
5145 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5146 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005147 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005148 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149 }
5150
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005151 if (DEBUG_FOCUS) {
5152 logDispatchStateLocked();
5153 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 } // release lock
5155
5156 // Wake up poll loop since it may need to make new input dispatching choices.
5157 mLooper->wake();
5158 return true;
5159}
5160
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005161/**
5162 * Get the touched foreground window on the given display.
5163 * Return null if there are no windows touched on that display, or if more than one foreground
5164 * window is being touched.
5165 */
5166sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5167 auto stateIt = mTouchStatesByDisplay.find(displayId);
5168 if (stateIt == mTouchStatesByDisplay.end()) {
5169 ALOGI("No touch state on display %" PRId32, displayId);
5170 return nullptr;
5171 }
5172
5173 const TouchState& state = stateIt->second;
5174 sp<WindowInfoHandle> touchedForegroundWindow;
5175 // If multiple foreground windows are touched, return nullptr
5176 for (const TouchedWindow& window : state.windows) {
5177 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5178 if (touchedForegroundWindow != nullptr) {
5179 ALOGI("Two or more foreground windows: %s and %s",
5180 touchedForegroundWindow->getName().c_str(),
5181 window.windowHandle->getName().c_str());
5182 return nullptr;
5183 }
5184 touchedForegroundWindow = window.windowHandle;
5185 }
5186 }
5187 return touchedForegroundWindow;
5188}
5189
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005190// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005191bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005192 sp<IBinder> fromToken;
5193 { // acquire lock
5194 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005195 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005196 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005197 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5198 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005199 return false;
5200 }
5201
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005202 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5203 if (from == nullptr) {
5204 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5205 return false;
5206 }
5207
5208 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005209 } // release lock
5210
5211 return transferTouchFocus(fromToken, destChannelToken);
5212}
5213
Michael Wrightd02c5b62014-02-10 15:10:22 -08005214void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005215 if (DEBUG_FOCUS) {
5216 ALOGD("Resetting and dropping all events (%s).", reason);
5217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005218
5219 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5220 synthesizeCancelationEventsForAllConnectionsLocked(options);
5221
5222 resetKeyRepeatLocked();
5223 releasePendingEventLocked();
5224 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005225 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005226
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005227 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005228 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005230 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231}
5232
5233void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005234 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235 dumpDispatchStateLocked(dump);
5236
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005237 std::istringstream stream(dump);
5238 std::string line;
5239
5240 while (std::getline(stream, line, '\n')) {
5241 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005242 }
5243}
5244
Prabir Pradhan99987712020-11-10 18:43:05 -08005245std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5246 std::string dump;
5247
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005248 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5249 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005250
5251 std::string windowName = "None";
5252 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005253 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005254 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5255 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5256 : "token has capture without window";
5257 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005258 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005259
5260 return dump;
5261}
5262
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005263void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005264 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5265 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5266 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005267 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268
Tiger Huang721e26f2018-07-24 22:26:19 +08005269 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5270 dump += StringPrintf(INDENT "FocusedApplications:\n");
5271 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5272 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005273 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005274 const std::chrono::duration timeout =
5275 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005276 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005277 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005278 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005279 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005281 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005283
Vishnu Nairc519ff72021-01-21 08:23:08 -08005284 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005285 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005287 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005288 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005289 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5290 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005291 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005292 state.displayId, toString(state.down), toString(state.split),
5293 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005294 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005295 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005296 for (size_t i = 0; i < state.windows.size(); i++) {
5297 const TouchedWindow& touchedWindow = state.windows[i];
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005298 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, "
5299 "targetFlags=0x%x, firstDownTimeInTarget=%" PRId64
5300 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005301 i, touchedWindow.windowHandle->getName().c_str(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005302 touchedWindow.pointerIds.value, touchedWindow.targetFlags,
5303 ns2ms(touchedWindow.firstDownTimeInTarget.value_or(0)));
Jeff Brownf086ddb2014-02-11 14:28:48 -08005304 }
5305 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005306 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308 }
5309 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005310 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311 }
5312
arthurhung6d4bed92021-03-17 11:59:33 +08005313 if (mDragState) {
5314 dump += StringPrintf(INDENT "DragState:\n");
5315 mDragState->dump(dump, INDENT2);
5316 }
5317
Arthur Hungb92218b2018-08-14 12:00:21 +08005318 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005319 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5320 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5321 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5322 const auto& displayInfo = it->second;
5323 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5324 displayInfo.logicalHeight);
5325 displayInfo.transform.dump(dump, "transform", INDENT4);
5326 } else {
5327 dump += INDENT2 "No DisplayInfo found!\n";
5328 }
5329
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005330 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005331 dump += INDENT2 "Windows:\n";
5332 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005333 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5334 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005335
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005336 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005337 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005338 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005339 "applicationInfo.name=%s, "
5340 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005341 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005342 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005343 windowInfo->displayId,
5344 windowInfo->inputConfig.string().c_str(),
5345 windowInfo->alpha, windowInfo->frameLeft,
5346 windowInfo->frameTop, windowInfo->frameRight,
5347 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005348 windowInfo->applicationInfo.name.c_str(),
5349 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005350 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005351 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005352 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005353 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005354 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005355 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005356 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005357 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005358 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005359 }
5360 } else {
5361 dump += INDENT2 "Windows: <none>\n";
5362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363 }
5364 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005365 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005366 }
5367
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005368 if (!mGlobalMonitorsByDisplay.empty()) {
5369 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5370 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005371 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005373 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005374 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375 }
5376
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005377 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378
5379 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005380 if (!mRecentQueue.empty()) {
5381 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005382 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005383 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005384 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005385 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005386 }
5387 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005388 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389 }
5390
5391 // Dump event currently being dispatched.
5392 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005393 dump += INDENT "PendingEvent:\n";
5394 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005395 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005396 dump += StringPrintf(", age=%" PRId64 "ms\n",
5397 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005398 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005399 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005400 }
5401
5402 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005403 if (!mInboundQueue.empty()) {
5404 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005405 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005406 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005407 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005408 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005409 }
5410 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005411 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412 }
5413
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005414 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005415 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005416 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5417 const KeyReplacement& replacement = pair.first;
5418 int32_t newKeyCode = pair.second;
5419 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005420 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005421 }
5422 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005423 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005424 }
5425
Prabir Pradhancef936d2021-07-21 16:17:52 +00005426 if (!mCommandQueue.empty()) {
5427 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5428 } else {
5429 dump += INDENT "CommandQueue: <empty>\n";
5430 }
5431
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005432 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005433 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005434 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005435 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005436 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005437 connection->inputChannel->getFd().get(),
5438 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005439 connection->getWindowName().c_str(),
5440 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005441 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005443 if (!connection->outboundQueue.empty()) {
5444 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5445 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005446 dump += dumpQueue(connection->outboundQueue, currentTime);
5447
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005449 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005450 }
5451
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005452 if (!connection->waitQueue.empty()) {
5453 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5454 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005455 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005457 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 }
5459 }
5460 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005461 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005462 }
5463
5464 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005465 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5466 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005468 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 }
5470
Antonio Kantek15beb512022-06-13 22:35:41 +00005471 if (!mTouchModePerDisplay.empty()) {
5472 dump += INDENT "TouchModePerDisplay:\n";
5473 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5474 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5475 std::to_string(touchMode).c_str());
5476 }
5477 } else {
5478 dump += INDENT "TouchModePerDisplay: <none>\n";
5479 }
5480
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005481 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005482 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5483 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5484 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005485 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005486 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005487}
5488
Michael Wright3dd60e22019-03-27 22:06:44 +00005489void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5490 const size_t numMonitors = monitors.size();
5491 for (size_t i = 0; i < numMonitors; i++) {
5492 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005493 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005494 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5495 dump += "\n";
5496 }
5497}
5498
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005499class LooperEventCallback : public LooperCallback {
5500public:
5501 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5502 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5503
5504private:
5505 std::function<int(int events)> mCallback;
5506};
5507
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005508Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005509 if (DEBUG_CHANNEL_CREATION) {
5510 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005513 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005514 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005515 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005516
5517 if (result) {
5518 return base::Error(result) << "Failed to open input channel pair with name " << name;
5519 }
5520
Michael Wrightd02c5b62014-02-10 15:10:22 -08005521 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005522 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005523 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005524 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005525 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005526 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005527
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005528 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5529 ALOGE("Created a new connection, but the token %p is already known", token.get());
5530 }
5531 mConnectionsByToken.emplace(token, connection);
5532
5533 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5534 this, std::placeholders::_1, token);
5535
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005536 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5537 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005538 } // release lock
5539
5540 // Wake the looper because some connections have changed.
5541 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005542 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543}
5544
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005545Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005546 const std::string& name,
5547 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005548 std::shared_ptr<InputChannel> serverChannel;
5549 std::unique_ptr<InputChannel> clientChannel;
5550 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5551 if (result) {
5552 return base::Error(result) << "Failed to open input channel pair with name " << name;
5553 }
5554
Michael Wright3dd60e22019-03-27 22:06:44 +00005555 { // acquire lock
5556 std::scoped_lock _l(mLock);
5557
5558 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005559 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5560 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005561 }
5562
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005563 sp<Connection> connection =
5564 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005565 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005566 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005567
5568 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5569 ALOGE("Created a new connection, but the token %p is already known", token.get());
5570 }
5571 mConnectionsByToken.emplace(token, connection);
5572 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5573 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005574
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005575 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005576
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005577 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5578 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005579 }
Garfield Tan15601662020-09-22 15:32:38 -07005580
Michael Wright3dd60e22019-03-27 22:06:44 +00005581 // Wake the looper because some connections have changed.
5582 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005583 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005584}
5585
Garfield Tan15601662020-09-22 15:32:38 -07005586status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005587 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005588 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589
Garfield Tan15601662020-09-22 15:32:38 -07005590 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005591 if (status) {
5592 return status;
5593 }
5594 } // release lock
5595
5596 // Wake the poll loop because removing the connection may have changed the current
5597 // synchronization state.
5598 mLooper->wake();
5599 return OK;
5600}
5601
Garfield Tan15601662020-09-22 15:32:38 -07005602status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5603 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005604 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005605 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005606 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607 return BAD_VALUE;
5608 }
5609
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005610 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005611
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005613 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614 }
5615
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005616 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617
5618 nsecs_t currentTime = now();
5619 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5620
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005621 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005622 return OK;
5623}
5624
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005625void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005626 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5627 auto& [displayId, monitors] = *it;
5628 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5629 return monitor.inputChannel->getConnectionToken() == connectionToken;
5630 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005631
Michael Wright3dd60e22019-03-27 22:06:44 +00005632 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005633 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005634 } else {
5635 ++it;
5636 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 }
5638}
5639
Michael Wright3dd60e22019-03-27 22:06:44 +00005640status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005641 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005642 return pilferPointersLocked(token);
5643}
Michael Wright3dd60e22019-03-27 22:06:44 +00005644
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005645status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005646 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5647 if (!requestingChannel) {
5648 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5649 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005650 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005651
5652 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5653 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5654 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5655 " Ignoring.");
5656 return BAD_VALUE;
5657 }
5658
5659 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005660 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005661 // Send cancel events to all the input channels we're stealing from.
5662 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5663 "input channel stole pointer stream");
5664 options.deviceId = state.deviceId;
5665 options.displayId = state.displayId;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005666 if (state.split) {
5667 // If split pointers then selectively cancel pointers otherwise cancel all pointers
5668 options.pointerIds = window.pointerIds;
5669 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005670 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005671 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005672 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005673 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005674 if (channel != nullptr && channel->getConnectionToken() != token) {
5675 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5676 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5677 canceledWindows += channel->getName();
5678 }
5679 }
5680 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5681 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5682 canceledWindows.c_str());
5683
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005684 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005685 // This only blocks relevant pointers to be sent to other windows
5686 window.isPilferingPointers = true;
5687
5688 if (state.split) {
5689 state.cancelPointersForWindowsExcept(window.pointerIds, token);
5690 } else {
5691 state.filterWindowsExcept(token);
5692 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005693 return OK;
5694}
5695
Prabir Pradhan99987712020-11-10 18:43:05 -08005696void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5697 { // acquire lock
5698 std::scoped_lock _l(mLock);
5699 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005700 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005701 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5702 windowHandle != nullptr ? windowHandle->getName().c_str()
5703 : "token without window");
5704 }
5705
Vishnu Nairc519ff72021-01-21 08:23:08 -08005706 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005707 if (focusedToken != windowToken) {
5708 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5709 enabled ? "enable" : "disable");
5710 return;
5711 }
5712
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005713 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005714 ALOGW("Ignoring request to %s Pointer Capture: "
5715 "window has %s requested pointer capture.",
5716 enabled ? "enable" : "disable", enabled ? "already" : "not");
5717 return;
5718 }
5719
Christine Franksb768bb42021-11-29 12:11:31 -08005720 if (enabled) {
5721 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5722 mIneligibleDisplaysForPointerCapture.end(),
5723 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5724 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5725 return;
5726 }
5727 }
5728
Prabir Pradhan99987712020-11-10 18:43:05 -08005729 setPointerCaptureLocked(enabled);
5730 } // release lock
5731
5732 // Wake the thread to process command entries.
5733 mLooper->wake();
5734}
5735
Christine Franksb768bb42021-11-29 12:11:31 -08005736void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5737 { // acquire lock
5738 std::scoped_lock _l(mLock);
5739 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5740 if (!isEligible) {
5741 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5742 }
5743 } // release lock
5744}
5745
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005746std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5747 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005748 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005749 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005750 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005751 }
5752 }
5753 }
5754 return std::nullopt;
5755}
5756
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005757sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005758 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005759 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005760 }
5761
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005762 for (const auto& [token, connection] : mConnectionsByToken) {
5763 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005764 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005765 }
5766 }
Robert Carr4e670e52018-08-15 13:26:12 -07005767
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005768 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769}
5770
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005771std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5772 sp<Connection> connection = getConnectionLocked(connectionToken);
5773 if (connection == nullptr) {
5774 return "<nullptr>";
5775 }
5776 return connection->getInputChannelName();
5777}
5778
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005779void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005780 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005781 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005782}
5783
Prabir Pradhancef936d2021-07-21 16:17:52 +00005784void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5785 const sp<Connection>& connection, uint32_t seq,
5786 bool handled, nsecs_t consumeTime) {
5787 // Handle post-event policy actions.
5788 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5789 if (dispatchEntryIt == connection->waitQueue.end()) {
5790 return;
5791 }
5792 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5793 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5794 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5795 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5796 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5797 }
5798 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5799 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5800 connection->inputChannel->getConnectionToken(),
5801 dispatchEntry->deliveryTime, consumeTime, finishTime);
5802 }
5803
5804 bool restartEvent;
5805 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5806 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5807 restartEvent =
5808 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5809 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5810 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5811 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5812 handled);
5813 } else {
5814 restartEvent = false;
5815 }
5816
5817 // Dequeue the event and start the next cycle.
5818 // Because the lock might have been released, it is possible that the
5819 // contents of the wait queue to have been drained, so we need to double-check
5820 // a few things.
5821 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5822 if (dispatchEntryIt != connection->waitQueue.end()) {
5823 dispatchEntry = *dispatchEntryIt;
5824 connection->waitQueue.erase(dispatchEntryIt);
5825 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5826 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5827 if (!connection->responsive) {
5828 connection->responsive = isConnectionResponsive(*connection);
5829 if (connection->responsive) {
5830 // The connection was unresponsive, and now it's responsive.
5831 processConnectionResponsiveLocked(*connection);
5832 }
5833 }
5834 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005835 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005836 connection->outboundQueue.push_front(dispatchEntry);
5837 traceOutboundQueueLength(*connection);
5838 } else {
5839 releaseDispatchEntry(dispatchEntry);
5840 }
5841 }
5842
5843 // Start the next dispatch cycle for this connection.
5844 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005845}
5846
Prabir Pradhancef936d2021-07-21 16:17:52 +00005847void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5848 const sp<IBinder>& newToken) {
5849 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5850 scoped_unlock unlock(mLock);
5851 mPolicy->notifyFocusChanged(oldToken, newToken);
5852 };
5853 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005854}
5855
Prabir Pradhancef936d2021-07-21 16:17:52 +00005856void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5857 auto command = [this, token, x, y]() REQUIRES(mLock) {
5858 scoped_unlock unlock(mLock);
5859 mPolicy->notifyDropWindow(token, x, y);
5860 };
5861 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005862}
5863
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005864void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5865 if (connection == nullptr) {
5866 LOG_ALWAYS_FATAL("Caller must check for nullness");
5867 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005868 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5869 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005870 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005871 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005872 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005873 return;
5874 }
5875 /**
5876 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5877 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5878 * has changed. This could cause newer entries to time out before the already dispatched
5879 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5880 * processes the events linearly. So providing information about the oldest entry seems to be
5881 * most useful.
5882 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005883 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005884 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5885 std::string reason =
5886 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005887 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005888 ns2ms(currentWait),
5889 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005890 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005891 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005892
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005893 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5894
5895 // Stop waking up for events on this connection, it is already unresponsive
5896 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005897}
5898
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005899void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5900 std::string reason =
5901 StringPrintf("%s does not have a focused window", application->getName().c_str());
5902 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005903
Prabir Pradhancef936d2021-07-21 16:17:52 +00005904 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5905 scoped_unlock unlock(mLock);
5906 mPolicy->notifyNoFocusedWindowAnr(application);
5907 };
5908 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005909}
5910
chaviw98318de2021-05-19 16:45:23 -05005911void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005912 const std::string& reason) {
5913 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5914 updateLastAnrStateLocked(windowLabel, reason);
5915}
5916
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005917void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5918 const std::string& reason) {
5919 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005920 updateLastAnrStateLocked(windowLabel, reason);
5921}
5922
5923void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5924 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005926 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005927 struct tm tm;
5928 localtime_r(&t, &tm);
5929 char timestr[64];
5930 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005931 mLastAnrState.clear();
5932 mLastAnrState += INDENT "ANR:\n";
5933 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005934 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5935 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005936 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937}
5938
Prabir Pradhancef936d2021-07-21 16:17:52 +00005939void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5940 KeyEntry& entry) {
5941 const KeyEvent event = createKeyEvent(entry);
5942 nsecs_t delay = 0;
5943 { // release lock
5944 scoped_unlock unlock(mLock);
5945 android::base::Timer t;
5946 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5947 entry.policyFlags);
5948 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5949 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5950 std::to_string(t.duration().count()).c_str());
5951 }
5952 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005953
5954 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005955 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005956 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005957 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005959 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5960 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005962}
5963
Prabir Pradhancef936d2021-07-21 16:17:52 +00005964void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005965 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005966 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005967 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005968 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005969 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005970 };
5971 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005972}
5973
Prabir Pradhanedd96402022-02-15 01:46:16 -08005974void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5975 std::optional<int32_t> pid) {
5976 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005977 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005978 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005979 };
5980 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005981}
5982
5983/**
5984 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5985 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5986 * command entry to the command queue.
5987 */
5988void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5989 std::string reason) {
5990 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005991 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005992 if (connection.monitor) {
5993 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5994 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005995 pid = findMonitorPidByTokenLocked(connectionToken);
5996 } else {
5997 // The connection is a window
5998 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5999 reason.c_str());
6000 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6001 if (handle != nullptr) {
6002 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006003 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006004 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006005 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006006}
6007
6008/**
6009 * Tell the policy that a connection has become responsive so that it can stop ANR.
6010 */
6011void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6012 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006013 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006014 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006015 pid = findMonitorPidByTokenLocked(connectionToken);
6016 } else {
6017 // The connection is a window
6018 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6019 if (handle != nullptr) {
6020 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006021 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006022 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006023 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006024}
6025
Prabir Pradhancef936d2021-07-21 16:17:52 +00006026bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006027 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006028 KeyEntry& keyEntry, bool handled) {
6029 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006030 if (!handled) {
6031 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006032 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006033 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006034 return false;
6035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006036
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006037 // Get the fallback key state.
6038 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006039 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006040 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006041 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006042 connection->inputState.removeFallbackKey(originalKeyCode);
6043 }
6044
6045 if (handled || !dispatchEntry->hasForegroundTarget()) {
6046 // If the application handles the original key for which we previously
6047 // generated a fallback or if the window is not a foreground window,
6048 // then cancel the associated fallback key, if any.
6049 if (fallbackKeyCode != -1) {
6050 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006051 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6052 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6053 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6054 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6055 keyEntry.policyFlags);
6056 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006057 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006058 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006059
6060 mLock.unlock();
6061
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006062 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006063 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006064
6065 mLock.lock();
6066
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006067 // Cancel the fallback key.
6068 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006069 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006070 "application handled the original non-fallback key "
6071 "or is no longer a foreground target, "
6072 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006073 options.keyCode = fallbackKeyCode;
6074 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006075 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006076 connection->inputState.removeFallbackKey(originalKeyCode);
6077 }
6078 } else {
6079 // If the application did not handle a non-fallback key, first check
6080 // that we are in a good state to perform unhandled key event processing
6081 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006082 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006083 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006084 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6085 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6086 "since this is not an initial down. "
6087 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6088 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6089 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006090 return false;
6091 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006093 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006094 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6095 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6096 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6097 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6098 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006099 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006100
6101 mLock.unlock();
6102
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006103 bool fallback =
6104 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006105 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006106
6107 mLock.lock();
6108
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006109 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006110 connection->inputState.removeFallbackKey(originalKeyCode);
6111 return false;
6112 }
6113
6114 // Latch the fallback keycode for this key on an initial down.
6115 // The fallback keycode cannot change at any other point in the lifecycle.
6116 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006117 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006118 fallbackKeyCode = event.getKeyCode();
6119 } else {
6120 fallbackKeyCode = AKEYCODE_UNKNOWN;
6121 }
6122 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6123 }
6124
6125 ALOG_ASSERT(fallbackKeyCode != -1);
6126
6127 // Cancel the fallback key if the policy decides not to send it anymore.
6128 // We will continue to dispatch the key to the policy but we will no
6129 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006130 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6131 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006132 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6133 if (fallback) {
6134 ALOGD("Unhandled key event: Policy requested to send key %d"
6135 "as a fallback for %d, but on the DOWN it had requested "
6136 "to send %d instead. Fallback canceled.",
6137 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6138 } else {
6139 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6140 "but on the DOWN it had requested to send %d. "
6141 "Fallback canceled.",
6142 originalKeyCode, fallbackKeyCode);
6143 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006144 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006145
6146 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6147 "canceling fallback, policy no longer desires it");
6148 options.keyCode = fallbackKeyCode;
6149 synthesizeCancelationEventsForConnectionLocked(connection, options);
6150
6151 fallback = false;
6152 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006153 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006154 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006155 }
6156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006157
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006158 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6159 {
6160 std::string msg;
6161 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6162 connection->inputState.getFallbackKeys();
6163 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6164 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6165 }
6166 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6167 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006168 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006169 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006170
6171 if (fallback) {
6172 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006173 keyEntry.eventTime = event.getEventTime();
6174 keyEntry.deviceId = event.getDeviceId();
6175 keyEntry.source = event.getSource();
6176 keyEntry.displayId = event.getDisplayId();
6177 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6178 keyEntry.keyCode = fallbackKeyCode;
6179 keyEntry.scanCode = event.getScanCode();
6180 keyEntry.metaState = event.getMetaState();
6181 keyEntry.repeatCount = event.getRepeatCount();
6182 keyEntry.downTime = event.getDownTime();
6183 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006184
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006185 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6186 ALOGD("Unhandled key event: Dispatching fallback key. "
6187 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6188 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6189 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006190 return true; // restart the event
6191 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006192 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6193 ALOGD("Unhandled key event: No fallback key.");
6194 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006195
6196 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006197 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006198 }
6199 }
6200 return false;
6201}
6202
Prabir Pradhancef936d2021-07-21 16:17:52 +00006203bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006204 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006205 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006206 return false;
6207}
6208
Michael Wrightd02c5b62014-02-10 15:10:22 -08006209void InputDispatcher::traceInboundQueueLengthLocked() {
6210 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006211 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006212 }
6213}
6214
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006215void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006216 if (ATRACE_ENABLED()) {
6217 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006218 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6219 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220 }
6221}
6222
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006223void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006224 if (ATRACE_ENABLED()) {
6225 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006226 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6227 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006228 }
6229}
6230
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006231void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006232 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006234 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006235 dumpDispatchStateLocked(dump);
6236
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006237 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006238 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006239 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006240 }
6241}
6242
6243void InputDispatcher::monitor() {
6244 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006245 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006246 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006247 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248}
6249
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006250/**
6251 * Wake up the dispatcher and wait until it processes all events and commands.
6252 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6253 * this method can be safely called from any thread, as long as you've ensured that
6254 * the work you are interested in completing has already been queued.
6255 */
6256bool InputDispatcher::waitForIdle() {
6257 /**
6258 * Timeout should represent the longest possible time that a device might spend processing
6259 * events and commands.
6260 */
6261 constexpr std::chrono::duration TIMEOUT = 100ms;
6262 std::unique_lock lock(mLock);
6263 mLooper->wake();
6264 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6265 return result == std::cv_status::no_timeout;
6266}
6267
Vishnu Naire798b472020-07-23 13:52:21 -07006268/**
6269 * Sets focus to the window identified by the token. This must be called
6270 * after updating any input window handles.
6271 *
6272 * Params:
6273 * request.token - input channel token used to identify the window that should gain focus.
6274 * request.focusedToken - the token that the caller expects currently to be focused. If the
6275 * specified token does not match the currently focused window, this request will be dropped.
6276 * If the specified focused token matches the currently focused window, the call will succeed.
6277 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6278 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6279 * when requesting the focus change. This determines which request gets
6280 * precedence if there is a focus change request from another source such as pointer down.
6281 */
Vishnu Nair958da932020-08-21 17:12:37 -07006282void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6283 { // acquire lock
6284 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006285 std::optional<FocusResolver::FocusChanges> changes =
6286 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6287 if (changes) {
6288 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006289 }
6290 } // release lock
6291 // Wake up poll loop since it may need to make new input dispatching choices.
6292 mLooper->wake();
6293}
6294
Vishnu Nairc519ff72021-01-21 08:23:08 -08006295void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6296 if (changes.oldFocus) {
6297 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006298 if (focusedInputChannel) {
6299 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6300 "focus left window");
6301 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006302 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006303 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006304 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006305 if (changes.newFocus) {
6306 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006307 }
6308
Prabir Pradhan99987712020-11-10 18:43:05 -08006309 // If a window has pointer capture, then it must have focus. We need to ensure that this
6310 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6311 // If the window loses focus before it loses pointer capture, then the window can be in a state
6312 // where it has pointer capture but not focus, violating the contract. Therefore we must
6313 // dispatch the pointer capture event before the focus event. Since focus events are added to
6314 // the front of the queue (above), we add the pointer capture event to the front of the queue
6315 // after the focus events are added. This ensures the pointer capture event ends up at the
6316 // front.
6317 disablePointerCaptureForcedLocked();
6318
Vishnu Nairc519ff72021-01-21 08:23:08 -08006319 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006320 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006321 }
6322}
Vishnu Nair958da932020-08-21 17:12:37 -07006323
Prabir Pradhan99987712020-11-10 18:43:05 -08006324void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006325 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006326 return;
6327 }
6328
6329 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6330
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006331 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006332 setPointerCaptureLocked(false);
6333 }
6334
6335 if (!mWindowTokenWithPointerCapture) {
6336 // No need to send capture changes because no window has capture.
6337 return;
6338 }
6339
6340 if (mPendingEvent != nullptr) {
6341 // Move the pending event to the front of the queue. This will give the chance
6342 // for the pending event to be dropped if it is a captured event.
6343 mInboundQueue.push_front(mPendingEvent);
6344 mPendingEvent = nullptr;
6345 }
6346
6347 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006348 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006349 mInboundQueue.push_front(std::move(entry));
6350}
6351
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006352void InputDispatcher::setPointerCaptureLocked(bool enable) {
6353 mCurrentPointerCaptureRequest.enable = enable;
6354 mCurrentPointerCaptureRequest.seq++;
6355 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006356 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006357 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006358 };
6359 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006360}
6361
Vishnu Nair599f1412021-06-21 10:39:58 -07006362void InputDispatcher::displayRemoved(int32_t displayId) {
6363 { // acquire lock
6364 std::scoped_lock _l(mLock);
6365 // Set an empty list to remove all handles from the specific display.
6366 setInputWindowsLocked(/* window handles */ {}, displayId);
6367 setFocusedApplicationLocked(displayId, nullptr);
6368 // Call focus resolver to clean up stale requests. This must be called after input windows
6369 // have been removed for the removed display.
6370 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006371 // Reset pointer capture eligibility, regardless of previous state.
6372 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006373 // Remove the associated touch mode state.
6374 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006375 } // release lock
6376
6377 // Wake up poll loop since it may need to make new input dispatching choices.
6378 mLooper->wake();
6379}
6380
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006381void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6382 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006383 // The listener sends the windows as a flattened array. Separate the windows by display for
6384 // more convenient parsing.
6385 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006386 for (const auto& info : windowInfos) {
6387 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006388 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006389 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006390
6391 { // acquire lock
6392 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006393
6394 // Ensure that we have an entry created for all existing displays so that if a displayId has
6395 // no windows, we can tell that the windows were removed from the display.
6396 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6397 handlesPerDisplay[displayId];
6398 }
6399
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006400 mDisplayInfos.clear();
6401 for (const auto& displayInfo : displayInfos) {
6402 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6403 }
6404
6405 for (const auto& [displayId, handles] : handlesPerDisplay) {
6406 setInputWindowsLocked(handles, displayId);
6407 }
6408 }
6409 // Wake up poll loop since it may need to make new input dispatching choices.
6410 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006411}
6412
Vishnu Nair062a8672021-09-03 16:07:44 -07006413bool InputDispatcher::shouldDropInput(
6414 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006415 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6416 (windowHandle->getInfo()->inputConfig.test(
6417 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006418 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006419 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6420 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006421 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006422 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006423 windowHandle->getInfo()->displayId);
6424 return true;
6425 }
6426 return false;
6427}
6428
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006429void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6430 const std::vector<gui::WindowInfo>& windowInfos,
6431 const std::vector<DisplayInfo>& displayInfos) {
6432 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6433}
6434
Arthur Hungdfd528e2021-12-08 13:23:04 +00006435void InputDispatcher::cancelCurrentTouch() {
6436 {
6437 std::scoped_lock _l(mLock);
6438 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6439 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6440 "cancel current touch");
6441 synthesizeCancelationEventsForAllConnectionsLocked(options);
6442
6443 mTouchStatesByDisplay.clear();
6444 mLastHoverWindowHandle.clear();
6445 }
6446 // Wake up poll loop since there might be work to do.
6447 mLooper->wake();
6448}
6449
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006450void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6451 std::scoped_lock _l(mLock);
6452 mMonitorDispatchingTimeout = timeout;
6453}
6454
Garfield Tane84e6f92019-08-29 17:28:41 -07006455} // namespace android::inputdispatcher