blob: 694c127e40389e990ddc3911c2a7aed515ded7db [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
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700544std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
545 if (eventEntry.type == EventEntry::Type::KEY) {
546 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
547 return keyEntry.downTime;
548 } else if (eventEntry.type == EventEntry::Type::MOTION) {
549 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
550 return motionEntry.downTime;
551 }
552 return std::nullopt;
553}
554
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000555} // namespace
556
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557// --- InputDispatcher ---
558
Garfield Tan00f511d2019-06-12 16:55:40 -0700559InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800560 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
561
562InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
563 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700564 : mPolicy(policy),
565 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700566 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800567 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700568 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700569 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700570 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800571 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700572 mDispatchEnabled(false),
573 mDispatchFrozen(false),
574 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100575 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000576 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800577 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800578 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000579 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000580 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700581 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800582 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700584 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700585#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700586 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700587#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700588 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 policy->getDispatcherConfiguration(&mConfig);
590}
591
592InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000593 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800594
Prabir Pradhancef936d2021-07-21 16:17:52 +0000595 resetKeyRepeatLocked();
596 releasePendingEventLocked();
597 drainInboundQueueLocked();
598 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000600 while (!mConnectionsByToken.empty()) {
601 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000602 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
603 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800604 }
605}
606
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700607status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700608 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700609 return ALREADY_EXISTS;
610 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700611 mThread = std::make_unique<InputThread>(
612 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
613 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700614}
615
616status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700617 if (mThread && mThread->isCallingThread()) {
618 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700619 return INVALID_OPERATION;
620 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700621 mThread.reset();
622 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700623}
624
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700626 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800628 std::scoped_lock _l(mLock);
629 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630
631 // Run a dispatch loop if there are no pending commands.
632 // The dispatch loop might enqueue commands to run afterwards.
633 if (!haveCommandsLocked()) {
634 dispatchOnceInnerLocked(&nextWakeupTime);
635 }
636
637 // Run all pending commands if there are any.
638 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000639 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700640 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800641 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800642
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700643 // If we are still waiting for ack on some events,
644 // we might have to wake up earlier to check if an app is anr'ing.
645 const nsecs_t nextAnrCheck = processAnrsLocked();
646 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
647
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800648 // We are about to enter an infinitely long sleep, because we have no commands or
649 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700650 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800651 mDispatcherEnteredIdle.notify_all();
652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653 } // release lock
654
655 // Wait for callback or timeout or wake. (make sure we round up, not down)
656 nsecs_t currentTime = now();
657 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
658 mLooper->pollOnce(timeoutMillis);
659}
660
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700661/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500662 * Raise ANR if there is no focused window.
663 * Before the ANR is raised, do a final state check:
664 * 1. The currently focused application must be the same one we are waiting for.
665 * 2. Ensure we still don't have a focused window.
666 */
667void InputDispatcher::processNoFocusedWindowAnrLocked() {
668 // Check if the application that we are waiting for is still focused.
669 std::shared_ptr<InputApplicationHandle> focusedApplication =
670 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
671 if (focusedApplication == nullptr ||
672 focusedApplication->getApplicationToken() !=
673 mAwaitedFocusedApplication->getApplicationToken()) {
674 // Unexpected because we should have reset the ANR timer when focused application changed
675 ALOGE("Waited for a focused window, but focused application has already changed to %s",
676 focusedApplication->getName().c_str());
677 return; // The focused application has changed.
678 }
679
chaviw98318de2021-05-19 16:45:23 -0500680 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500681 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
682 if (focusedWindowHandle != nullptr) {
683 return; // We now have a focused window. No need for ANR.
684 }
685 onAnrLocked(mAwaitedFocusedApplication);
686}
687
688/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700689 * Check if any of the connections' wait queues have events that are too old.
690 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
691 * Return the time at which we should wake up next.
692 */
693nsecs_t InputDispatcher::processAnrsLocked() {
694 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700695 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700696 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
697 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
698 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500699 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700700 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500701 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700702 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700703 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500704 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700705 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
706 }
707 }
708
709 // Check if any connection ANRs are due
710 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
711 if (currentTime < nextAnrCheck) { // most likely scenario
712 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
713 }
714
715 // If we reached here, we have an unresponsive connection.
716 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
717 if (connection == nullptr) {
718 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
719 return nextAnrCheck;
720 }
721 connection->responsive = false;
722 // Stop waking up for this unresponsive connection
723 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000724 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700725 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700726}
727
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800728std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
729 const sp<Connection>& connection) {
730 if (connection->monitor) {
731 return mMonitorDispatchingTimeout;
732 }
733 const sp<WindowInfoHandle> window =
734 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700735 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500736 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700737 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500738 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700739}
740
Michael Wrightd02c5b62014-02-10 15:10:22 -0800741void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
742 nsecs_t currentTime = now();
743
Jeff Browndc5992e2014-04-11 01:27:26 -0700744 // Reset the key repeat timer whenever normal dispatch is suspended while the
745 // device is in a non-interactive state. This is to ensure that we abort a key
746 // repeat if the device is just coming out of sleep.
747 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 resetKeyRepeatLocked();
749 }
750
751 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
752 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100753 if (DEBUG_FOCUS) {
754 ALOGD("Dispatch frozen. Waiting some more.");
755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 return;
757 }
758
759 // Optimize latency of app switches.
760 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
761 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
762 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
763 if (mAppSwitchDueTime < *nextWakeupTime) {
764 *nextWakeupTime = mAppSwitchDueTime;
765 }
766
767 // Ready to start a new event.
768 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700769 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700770 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771 if (isAppSwitchDue) {
772 // The inbound queue is empty so the app switch key we were waiting
773 // for will never arrive. Stop waiting for it.
774 resetPendingAppSwitchLocked(false);
775 isAppSwitchDue = false;
776 }
777
778 // Synthesize a key repeat if appropriate.
779 if (mKeyRepeatState.lastKeyEntry) {
780 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
781 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
782 } else {
783 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
784 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
785 }
786 }
787 }
788
789 // Nothing to do if there is no pending event.
790 if (!mPendingEvent) {
791 return;
792 }
793 } else {
794 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700795 mPendingEvent = mInboundQueue.front();
796 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797 traceInboundQueueLengthLocked();
798 }
799
800 // Poke user activity for this event.
801 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700802 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 }
805
806 // Now we have an event to dispatch.
807 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700808 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700810 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700812 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700814 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815 }
816
817 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700818 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 }
820
821 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700822 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700823 const ConfigurationChangedEntry& typedEntry =
824 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700825 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700826 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700827 break;
828 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700830 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700831 const DeviceResetEntry& typedEntry =
832 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700833 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700834 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 break;
836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100838 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700839 std::shared_ptr<FocusEntry> typedEntry =
840 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100841 dispatchFocusLocked(currentTime, typedEntry);
842 done = true;
843 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
844 break;
845 }
846
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700847 case EventEntry::Type::TOUCH_MODE_CHANGED: {
848 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
849 dispatchTouchModeChangeLocked(currentTime, typedEntry);
850 done = true;
851 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
852 break;
853 }
854
Prabir Pradhan99987712020-11-10 18:43:05 -0800855 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
856 const auto typedEntry =
857 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
858 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
859 done = true;
860 break;
861 }
862
arthurhungb89ccb02020-12-30 16:19:01 +0800863 case EventEntry::Type::DRAG: {
864 std::shared_ptr<DragEntry> typedEntry =
865 std::static_pointer_cast<DragEntry>(mPendingEvent);
866 dispatchDragLocked(currentTime, typedEntry);
867 done = true;
868 break;
869 }
870
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700871 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700872 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700873 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700874 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 resetPendingAppSwitchLocked(true);
876 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700877 } else if (dropReason == DropReason::NOT_DROPPED) {
878 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700879 }
880 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700881 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700882 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700883 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700884 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
885 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700886 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700887 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 break;
889 }
890
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700891 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700892 std::shared_ptr<MotionEntry> motionEntry =
893 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700894 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
895 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700897 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700898 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700899 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700900 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
901 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700902 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700903 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700904 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 }
Chris Yef59a2f42020-10-16 12:55:26 -0700906
907 case EventEntry::Type::SENSOR: {
908 std::shared_ptr<SensorEntry> sensorEntry =
909 std::static_pointer_cast<SensorEntry>(mPendingEvent);
910 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
911 dropReason = DropReason::APP_SWITCH;
912 }
913 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
914 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
915 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
916 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
917 dropReason = DropReason::STALE;
918 }
919 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
920 done = true;
921 break;
922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 }
924
925 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700926 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700927 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 }
Michael Wright3a981722015-06-10 15:26:13 +0100929 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930
931 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -0700932 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 }
934}
935
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800936bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
937 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
938}
939
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700940/**
941 * Return true if the events preceding this incoming motion event should be dropped
942 * Return false otherwise (the default behaviour)
943 */
944bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700945 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700946 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700947
948 // Optimize case where the current application is unresponsive and the user
949 // decides to touch a window in a different application.
950 // If the application takes too long to catch up then we drop all events preceding
951 // the touch into the other window.
952 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700953 const int32_t displayId = motionEntry.displayId;
954 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700955 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700956
chaviw98318de2021-05-19 16:45:23 -0500957 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700958 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700959 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700960 touchedWindowHandle->getApplicationToken() !=
961 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700962 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700963 ALOGI("Pruning input queue because user touched a different application while waiting "
964 "for %s",
965 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700966 return true;
967 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700968
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800969 // Alternatively, maybe there's a spy window that could handle this event.
970 const std::vector<sp<WindowInfoHandle>> touchedSpies =
971 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
972 for (const auto& windowHandle : touchedSpies) {
973 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000974 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800975 // This spy window could take more input. Drop all events preceding this
976 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700977 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800978 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700979 mAwaitedFocusedApplication->getName().c_str());
980 return true;
981 }
982 }
983 }
984
985 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
986 // yet been processed by some connections, the dispatcher will wait for these motion
987 // events to be processed before dispatching the key event. This is because these motion events
988 // may cause a new window to be launched, which the user might expect to receive focus.
989 // To prevent waiting forever for such events, just send the key to the currently focused window
990 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
991 ALOGD("Received a new pointer down event, stop waiting for events to process and "
992 "just send the pending key event to the focused window.");
993 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700994 }
995 return false;
996}
997
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700998bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700999 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001000 mInboundQueue.push_back(std::move(newEntry));
1001 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 traceInboundQueueLengthLocked();
1003
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001004 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001005 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001006 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1007 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001008 // Optimize app switch latency.
1009 // If the application takes too long to catch up then we drop all events preceding
1010 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001011 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001012 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001013 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001014 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001015 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001016 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001017 if (DEBUG_APP_SWITCH) {
1018 ALOGD("App switch is pending!");
1019 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001020 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001021 mAppSwitchSawKeyDown = false;
1022 needWake = true;
1023 }
1024 }
1025 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001026
1027 // If a new up event comes in, and the pending event with same key code has been asked
1028 // to try again later because of the policy. We have to reset the intercept key wake up
1029 // time for it may have been handled in the policy and could be dropped.
1030 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1031 mPendingEvent->type == EventEntry::Type::KEY) {
1032 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1033 if (pendingKey.keyCode == keyEntry.keyCode &&
1034 pendingKey.interceptKeyResult ==
1035 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1036 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1037 pendingKey.interceptKeyWakeupTime = 0;
1038 needWake = true;
1039 }
1040 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001041 break;
1042 }
1043
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001044 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001045 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1046 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001047 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1048 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001049 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001051 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001053 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001054 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1055 break;
1056 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001057 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001058 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001059 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001060 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001061 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1062 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001063 // nothing to do
1064 break;
1065 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066 }
1067
1068 return needWake;
1069}
1070
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001071void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001072 // Do not store sensor event in recent queue to avoid flooding the queue.
1073 if (entry->type != EventEntry::Type::SENSOR) {
1074 mRecentQueue.push_back(entry);
1075 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001076 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001077 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 }
1079}
1080
chaviw98318de2021-05-19 16:45:23 -05001081sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1082 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001083 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001084 bool addOutsideTargets,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07001085 bool ignoreDragWindow) const {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001086 if (addOutsideTargets && touchState == nullptr) {
1087 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001090 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001091 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001092 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001093 continue;
1094 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001096 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001097 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001098 return windowHandle;
1099 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001100
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001101 if (addOutsideTargets &&
1102 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001103 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1104 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105 }
1106 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001107 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108}
1109
Prabir Pradhand65552b2021-10-07 11:23:50 -07001110std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1111 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001112 // Traverse windows from front to back and gather the touched spy windows.
1113 std::vector<sp<WindowInfoHandle>> spyWindows;
1114 const auto& windowHandles = getWindowHandlesLocked(displayId);
1115 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1116 const WindowInfo& info = *windowHandle->getInfo();
1117
Prabir Pradhand65552b2021-10-07 11:23:50 -07001118 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001119 continue;
1120 }
1121 if (!info.isSpy()) {
1122 // The first touched non-spy window was found, so return the spy windows touched so far.
1123 return spyWindows;
1124 }
1125 spyWindows.push_back(windowHandle);
1126 }
1127 return spyWindows;
1128}
1129
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001130void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 const char* reason;
1132 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001133 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001134 if (DEBUG_INBOUND_EVENT_DETAILS) {
1135 ALOGD("Dropped event because policy consumed it.");
1136 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001137 reason = "inbound event was dropped because the policy consumed it";
1138 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001139 case DropReason::DISABLED:
1140 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001141 ALOGI("Dropped event because input dispatch is disabled.");
1142 }
1143 reason = "inbound event was dropped because input dispatch is disabled";
1144 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001145 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001146 ALOGI("Dropped event because of pending overdue app switch.");
1147 reason = "inbound event was dropped because of pending overdue app switch";
1148 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001149 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001150 ALOGI("Dropped event because the current application is not responding and the user "
1151 "has started interacting with a different application.");
1152 reason = "inbound event was dropped because the current application is not responding "
1153 "and the user has started interacting with a different application";
1154 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001155 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001156 ALOGI("Dropped event because it is stale.");
1157 reason = "inbound event was dropped because it is stale";
1158 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001159 case DropReason::NO_POINTER_CAPTURE:
1160 ALOGI("Dropped event because there is no window with Pointer Capture.");
1161 reason = "inbound event was dropped because there is no window with Pointer Capture";
1162 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001163 case DropReason::NOT_DROPPED: {
1164 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001165 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001166 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 }
1168
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001169 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001170 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1172 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001173 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001175 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001176 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1177 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001178 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1179 synthesizeCancelationEventsForAllConnectionsLocked(options);
1180 } else {
1181 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1182 synthesizeCancelationEventsForAllConnectionsLocked(options);
1183 }
1184 break;
1185 }
Chris Yef59a2f42020-10-16 12:55:26 -07001186 case EventEntry::Type::SENSOR: {
1187 break;
1188 }
arthurhungb89ccb02020-12-30 16:19:01 +08001189 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1190 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001191 break;
1192 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001193 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001194 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001195 case EventEntry::Type::CONFIGURATION_CHANGED:
1196 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001197 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001198 break;
1199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 }
1201}
1202
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001203static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001204 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1205 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206}
1207
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001208bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1209 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1210 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1211 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212}
1213
1214bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001215 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216}
1217
1218void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001219 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001221 if (DEBUG_APP_SWITCH) {
1222 if (handled) {
1223 ALOGD("App switch has arrived.");
1224 } else {
1225 ALOGD("App switch was abandoned.");
1226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228}
1229
Michael Wrightd02c5b62014-02-10 15:10:22 -08001230bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001231 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232}
1233
Prabir Pradhancef936d2021-07-21 16:17:52 +00001234bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001235 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 return false;
1237 }
1238
1239 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001240 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001241 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001242 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1243 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001244 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 return true;
1246}
1247
Prabir Pradhancef936d2021-07-21 16:17:52 +00001248void InputDispatcher::postCommandLocked(Command&& command) {
1249 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250}
1251
1252void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001253 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001254 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001255 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 releaseInboundEventLocked(entry);
1257 }
1258 traceInboundQueueLengthLocked();
1259}
1260
1261void InputDispatcher::releasePendingEventLocked() {
1262 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001264 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 }
1266}
1267
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001268void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001270 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001271 if (DEBUG_DISPATCH_CYCLE) {
1272 ALOGD("Injected inbound event was dropped.");
1273 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001274 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 }
1276 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001277 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 }
1279 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280}
1281
1282void InputDispatcher::resetKeyRepeatLocked() {
1283 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001284 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285 }
1286}
1287
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001288std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1289 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290
Michael Wright2e732952014-09-24 13:26:59 -07001291 uint32_t policyFlags = entry->policyFlags &
1292 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001294 std::shared_ptr<KeyEntry> newEntry =
1295 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1296 entry->source, entry->displayId, policyFlags, entry->action,
1297 entry->flags, entry->keyCode, entry->scanCode,
1298 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001300 newEntry->syntheticRepeat = true;
1301 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001303 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304}
1305
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001306bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001307 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001308 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1309 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311
1312 // Reset key repeating in case a keyboard device was added or removed or something.
1313 resetKeyRepeatLocked();
1314
1315 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001316 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1317 scoped_unlock unlock(mLock);
1318 mPolicy->notifyConfigurationChanged(eventTime);
1319 };
1320 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 return true;
1322}
1323
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001324bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1325 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001326 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1327 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1328 entry.deviceId);
1329 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330
liushenxiang42232912021-05-21 20:24:09 +08001331 // Reset key repeating in case a keyboard device was disabled or enabled.
1332 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1333 resetKeyRepeatLocked();
1334 }
1335
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001336 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001337 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 synthesizeCancelationEventsForAllConnectionsLocked(options);
1339 return true;
1340}
1341
Vishnu Nairad321cd2020-08-20 16:40:21 -07001342void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001343 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001344 if (mPendingEvent != nullptr) {
1345 // Move the pending event to the front of the queue. This will give the chance
1346 // for the pending event to get dispatched to the newly focused window
1347 mInboundQueue.push_front(mPendingEvent);
1348 mPendingEvent = nullptr;
1349 }
1350
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001351 std::unique_ptr<FocusEntry> focusEntry =
1352 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1353 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001354
1355 // This event should go to the front of the queue, but behind all other focus events
1356 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001357 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001358 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001359 [](const std::shared_ptr<EventEntry>& event) {
1360 return event->type == EventEntry::Type::FOCUS;
1361 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001362
1363 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001364 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001365}
1366
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001367void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001368 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001369 if (channel == nullptr) {
1370 return; // Window has gone away
1371 }
1372 InputTarget target;
1373 target.inputChannel = channel;
1374 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1375 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001376 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1377 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001378 std::string reason = std::string("reason=").append(entry->reason);
1379 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001380 dispatchEventLocked(currentTime, entry, {target});
1381}
1382
Prabir Pradhan99987712020-11-10 18:43:05 -08001383void InputDispatcher::dispatchPointerCaptureChangedLocked(
1384 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1385 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001386 dropReason = DropReason::NOT_DROPPED;
1387
Prabir Pradhan99987712020-11-10 18:43:05 -08001388 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001389 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001390
1391 if (entry->pointerCaptureRequest.enable) {
1392 // Enable Pointer Capture.
1393 if (haveWindowWithPointerCapture &&
1394 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001395 // This can happen if pointer capture is disabled and re-enabled before we notify the
1396 // app of the state change, so there is no need to notify the app.
1397 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1398 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001399 }
1400 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001401 // This can happen if a window requests capture and immediately releases capture.
1402 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001403 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001404 return;
1405 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001406 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1407 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1408 return;
1409 }
1410
Vishnu Nairc519ff72021-01-21 08:23:08 -08001411 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001412 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1413 mWindowTokenWithPointerCapture = token;
1414 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001415 // Disable Pointer Capture.
1416 // We do not check if the sequence number matches for requests to disable Pointer Capture
1417 // for two reasons:
1418 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1419 // to disable capture with the same sequence number: one generated by
1420 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1421 // Capture being disabled in InputReader.
1422 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1423 // actual Pointer Capture state that affects events being generated by input devices is
1424 // in InputReader.
1425 if (!haveWindowWithPointerCapture) {
1426 // Pointer capture was already forcefully disabled because of focus change.
1427 dropReason = DropReason::NOT_DROPPED;
1428 return;
1429 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001430 token = mWindowTokenWithPointerCapture;
1431 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001432 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001433 setPointerCaptureLocked(false);
1434 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001435 }
1436
1437 auto channel = getInputChannelLocked(token);
1438 if (channel == nullptr) {
1439 // Window has gone away, clean up Pointer Capture state.
1440 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001441 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001442 setPointerCaptureLocked(false);
1443 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001444 return;
1445 }
1446 InputTarget target;
1447 target.inputChannel = channel;
1448 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1449 entry->dispatchInProgress = true;
1450 dispatchEventLocked(currentTime, entry, {target});
1451
1452 dropReason = DropReason::NOT_DROPPED;
1453}
1454
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001455void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1456 const std::shared_ptr<TouchModeEntry>& entry) {
1457 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001458 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001459 if (windowHandles.empty()) {
1460 return;
1461 }
1462 const std::vector<InputTarget> inputTargets =
1463 getInputTargetsFromWindowHandlesLocked(windowHandles);
1464 if (inputTargets.empty()) {
1465 return;
1466 }
1467 entry->dispatchInProgress = true;
1468 dispatchEventLocked(currentTime, entry, inputTargets);
1469}
1470
1471std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1472 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1473 std::vector<InputTarget> inputTargets;
1474 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001475 const sp<IBinder>& token = handle->getToken();
1476 if (token == nullptr) {
1477 continue;
1478 }
1479 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1480 if (channel == nullptr) {
1481 continue; // Window has gone away
1482 }
1483 InputTarget target;
1484 target.inputChannel = channel;
1485 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1486 inputTargets.push_back(target);
1487 }
1488 return inputTargets;
1489}
1490
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001491bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001492 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001494 if (!entry->dispatchInProgress) {
1495 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1496 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1497 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1498 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001499 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 // We have seen two identical key downs in a row which indicates that the device
1501 // driver is automatically generating key repeats itself. We take note of the
1502 // repeat here, but we disable our own next key repeat timer since it is clear that
1503 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001504 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1505 // Make sure we don't get key down from a different device. If a different
1506 // device Id has same key pressed down, the new device Id will replace the
1507 // current one to hold the key repeat with repeat count reset.
1508 // In the future when got a KEY_UP on the device id, drop it and do not
1509 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1511 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001512 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 } else {
1514 // Not a repeat. Save key down state in case we do see a repeat later.
1515 resetKeyRepeatLocked();
1516 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1517 }
1518 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001519 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1520 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001521 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001522 if (DEBUG_INBOUND_EVENT_DETAILS) {
1523 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1524 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001525 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 resetKeyRepeatLocked();
1527 }
1528
1529 if (entry->repeatCount == 1) {
1530 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1531 } else {
1532 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1533 }
1534
1535 entry->dispatchInProgress = true;
1536
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001537 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 }
1539
1540 // Handle case where the policy asked us to try again later last time.
1541 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1542 if (currentTime < entry->interceptKeyWakeupTime) {
1543 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1544 *nextWakeupTime = entry->interceptKeyWakeupTime;
1545 }
1546 return false; // wait until next wakeup
1547 }
1548 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1549 entry->interceptKeyWakeupTime = 0;
1550 }
1551
1552 // Give the policy a chance to intercept the key.
1553 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1554 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001555 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001556 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001557
1558 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1559 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1560 };
1561 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 return false; // wait for the command to run
1563 } else {
1564 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1565 }
1566 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001567 if (*dropReason == DropReason::NOT_DROPPED) {
1568 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569 }
1570 }
1571
1572 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001573 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001574 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001575 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1576 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001577 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 return true;
1579 }
1580
1581 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001582 InputEventInjectionResult injectionResult;
1583 sp<WindowInfoHandle> focusedWindow =
1584 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1585 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001586 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 return false;
1588 }
1589
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001590 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001591 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 return true;
1593 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001594 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1595
1596 std::vector<InputTarget> inputTargets;
1597 addWindowTargetLocked(focusedWindow,
1598 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1599 BitSet32(0), getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001601 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001602 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603
1604 // Dispatch the key.
1605 dispatchEventLocked(currentTime, entry, inputTargets);
1606 return true;
1607}
1608
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001609void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001610 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1611 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1612 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1613 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1614 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1615 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1616 entry.metaState, entry.repeatCount, entry.downTime);
1617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618}
1619
Prabir Pradhancef936d2021-07-21 16:17:52 +00001620void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1621 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001622 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001623 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1624 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1625 "source=0x%x, sensorType=%s",
1626 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001627 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001628 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001629 auto command = [this, entry]() REQUIRES(mLock) {
1630 scoped_unlock unlock(mLock);
1631
1632 if (entry->accuracyChanged) {
1633 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1634 }
1635 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1636 entry->hwTimestamp, entry->values);
1637 };
1638 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001639}
1640
1641bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001642 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1643 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001644 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001645 }
Chris Yef59a2f42020-10-16 12:55:26 -07001646 { // acquire lock
1647 std::scoped_lock _l(mLock);
1648
1649 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1650 std::shared_ptr<EventEntry> entry = *it;
1651 if (entry->type == EventEntry::Type::SENSOR) {
1652 it = mInboundQueue.erase(it);
1653 releaseInboundEventLocked(entry);
1654 }
1655 }
1656 }
1657 return true;
1658}
1659
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001660bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001661 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001662 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001663 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001664 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 entry->dispatchInProgress = true;
1666
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001667 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 }
1669
1670 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001671 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001672 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001673 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1674 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 return true;
1676 }
1677
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001678 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679
1680 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001681 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682
1683 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001684 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685 if (isPointerEvent) {
1686 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001687
1688 if (mDragState &&
1689 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1690 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1691 pilferPointersLocked(mDragState->dragWindow->getToken());
1692 }
1693
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001694 std::vector<TouchedWindow> touchedWindows =
1695 findTouchedWindowTargetsLocked(currentTime, *entry, nextWakeupTime,
1696 &conflictingPointerActions,
1697 /*byref*/ injectionResult);
1698 for (const TouchedWindow& touchedWindow : touchedWindows) {
1699 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED,
1700 "Shouldn't be adding window if the injection didn't succeed.");
1701 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1702 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
1703 inputTargets);
1704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 } else {
1706 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001707 sp<WindowInfoHandle> focusedWindow =
1708 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1709 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1710 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1711 addWindowTargetLocked(focusedWindow,
1712 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1713 BitSet32(0), getDownTime(*entry), inputTargets);
1714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001716 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 return false;
1718 }
1719
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001720 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001721 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001722 return true;
1723 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001724 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001725 CancelationOptions::Mode mode(isPointerEvent
1726 ? CancelationOptions::CANCEL_POINTER_EVENTS
1727 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1728 CancelationOptions options(mode, "input event injection failed");
1729 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 return true;
1731 }
1732
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001733 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001734 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735
1736 // Dispatch the motion.
1737 if (conflictingPointerActions) {
1738 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001739 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 synthesizeCancelationEventsForAllConnectionsLocked(options);
1741 }
1742 dispatchEventLocked(currentTime, entry, inputTargets);
1743 return true;
1744}
1745
chaviw98318de2021-05-19 16:45:23 -05001746void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001747 bool isExiting, const int32_t rawX,
1748 const int32_t rawY) {
1749 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001750 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001751 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1752 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001753
1754 enqueueInboundEventLocked(std::move(dragEntry));
1755}
1756
1757void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1758 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1759 if (channel == nullptr) {
1760 return; // Window has gone away
1761 }
1762 InputTarget target;
1763 target.inputChannel = channel;
1764 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1765 entry->dispatchInProgress = true;
1766 dispatchEventLocked(currentTime, entry, {target});
1767}
1768
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001769void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001770 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1771 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1772 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001773 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001774 "metaState=0x%x, buttonState=0x%x,"
1775 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1776 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001777 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1778 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1779 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001781 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1782 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1783 "x=%f, y=%f, pressure=%f, size=%f, "
1784 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1785 "orientation=%f",
1786 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1787 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1788 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1789 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1790 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1791 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1792 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1793 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1794 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1795 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798}
1799
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001800void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1801 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001802 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001803 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001804 if (DEBUG_DISPATCH_CYCLE) {
1805 ALOGD("dispatchEventToCurrentInputTargets");
1806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001808 updateInteractionTokensLocked(*eventEntry, inputTargets);
1809
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1811
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001812 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001814 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001815 sp<Connection> connection =
1816 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001817 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001818 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001820 if (DEBUG_FOCUS) {
1821 ALOGD("Dropping event delivery to target with channel '%s' because it "
1822 "is no longer registered with the input dispatcher.",
1823 inputTarget.inputChannel->getName().c_str());
1824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 }
1826 }
1827}
1828
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001829void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1830 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1831 // If the policy decides to close the app, we will get a channel removal event via
1832 // unregisterInputChannel, and will clean up the connection that way. We are already not
1833 // sending new pointers to the connection when it blocked, but focused events will continue to
1834 // pile up.
1835 ALOGW("Canceling events for %s because it is unresponsive",
1836 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001837 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001838 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1839 "application not responding");
1840 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 }
1842}
1843
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001844void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001845 if (DEBUG_FOCUS) {
1846 ALOGD("Resetting ANR timeouts.");
1847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848
1849 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001850 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001851 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852}
1853
Tiger Huang721e26f2018-07-24 22:26:19 +08001854/**
1855 * Get the display id that the given event should go to. If this event specifies a valid display id,
1856 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1857 * Focused display is the display that the user most recently interacted with.
1858 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001859int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001860 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001861 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001862 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001863 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1864 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001865 break;
1866 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001867 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001868 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1869 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001870 break;
1871 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001872 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001873 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001874 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001875 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001876 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001877 case EventEntry::Type::SENSOR:
1878 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001879 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001880 return ADISPLAY_ID_NONE;
1881 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001882 }
1883 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1884}
1885
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001886bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1887 const char* focusedWindowName) {
1888 if (mAnrTracker.empty()) {
1889 // already processed all events that we waited for
1890 mKeyIsWaitingForEventsTimeout = std::nullopt;
1891 return false;
1892 }
1893
1894 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1895 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001896 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001897 mKeyIsWaitingForEventsTimeout = currentTime +
1898 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1899 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001900 return true;
1901 }
1902
1903 // We still have pending events, and already started the timer
1904 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1905 return true; // Still waiting
1906 }
1907
1908 // Waited too long, and some connection still hasn't processed all motions
1909 // Just send the key to the focused window
1910 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1911 focusedWindowName);
1912 mKeyIsWaitingForEventsTimeout = std::nullopt;
1913 return false;
1914}
1915
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001916sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1917 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1918 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001919 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001920 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921
Tiger Huang721e26f2018-07-24 22:26:19 +08001922 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001923 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001924 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001925 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1926
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 // If there is no currently focused window and no focused application
1928 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001929 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1930 ALOGI("Dropping %s event because there is no focused window or focused application in "
1931 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001932 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001933 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 }
1935
Vishnu Nair062a8672021-09-03 16:07:44 -07001936 // Drop key events if requested by input feature
1937 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001938 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07001939 }
1940
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001941 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1942 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1943 // start interacting with another application via touch (app switch). This code can be removed
1944 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1945 // an app is expected to have a focused window.
1946 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1947 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1948 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001949 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1950 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1951 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001952 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001953 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001954 ALOGW("Waiting because no window has focus but %s may eventually add a "
1955 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001956 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001957 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001958 outInjectionResult = InputEventInjectionResult::PENDING;
1959 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001960 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1961 // Already raised ANR. Drop the event
1962 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001963 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001964 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001965 } else {
1966 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001967 outInjectionResult = InputEventInjectionResult::PENDING;
1968 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001969 }
1970 }
1971
1972 // we have a valid, non-null focused window
1973 resetNoFocusedWindowTimeoutLocked();
1974
Prabir Pradhan5735a322022-04-11 17:23:34 +00001975 // Verify targeted injection.
1976 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1977 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001978 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
1979 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 }
1981
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001982 if (focusedWindowHandle->getInfo()->inputConfig.test(
1983 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001984 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001985 outInjectionResult = InputEventInjectionResult::PENDING;
1986 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001987 }
1988
1989 // If the event is a key event, then we must wait for all previous events to
1990 // complete before delivering it because previous events may have the
1991 // side-effect of transferring focus to a different window and we want to
1992 // ensure that the following keys are sent to the new window.
1993 //
1994 // Suppose the user touches a button in a window then immediately presses "A".
1995 // If the button causes a pop-up window to appear then we want to ensure that
1996 // the "A" key is delivered to the new pop-up window. This is because users
1997 // often anticipate pending UI changes when typing on a keyboard.
1998 // To obtain this behavior, we must serialize key events with respect to all
1999 // prior input events.
2000 if (entry.type == EventEntry::Type::KEY) {
2001 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2002 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002003 outInjectionResult = InputEventInjectionResult::PENDING;
2004 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 }
2007
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002008 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2009 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010}
2011
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002012/**
2013 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2014 * that are currently unresponsive.
2015 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002016std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2017 const std::vector<Monitor>& monitors) const {
2018 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002019 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002020 [this](const Monitor& monitor) REQUIRES(mLock) {
2021 sp<Connection> connection =
2022 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002023 if (connection == nullptr) {
2024 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002025 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002026 return false;
2027 }
2028 if (!connection->responsive) {
2029 ALOGW("Unresponsive monitor %s will not get the new gesture",
2030 connection->inputChannel->getName().c_str());
2031 return false;
2032 }
2033 return true;
2034 });
2035 return responsiveMonitors;
2036}
2037
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002038std::vector<TouchedWindow> InputDispatcher::findTouchedWindowTargetsLocked(
2039 nsecs_t currentTime, const MotionEntry& entry, nsecs_t* nextWakeupTime,
2040 bool* outConflictingPointerActions, InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002041 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002043 std::vector<TouchedWindow> touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 // For security reasons, we defer updating the touch state until we are sure that
2045 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002046 const int32_t displayId = entry.displayId;
2047 const int32_t action = entry.action;
2048 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049
2050 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002051 outInjectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002052 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2053 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002055 // Copy current touch state into tempTouchState.
2056 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2057 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002058 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002059 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002060 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2061 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002062 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002063 }
2064
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002065 bool isSplit = tempTouchState.split;
2066 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2067 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2068 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002069
2070 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2071 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2072 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2073 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2074 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002075 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 bool wrongDevice = false;
2077 if (newGesture) {
2078 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002079 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002080 ALOGI("Dropping event because a pointer for a different device is already down "
2081 "in display %" PRId32,
2082 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002083 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002084 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 switchedDevice = false;
2086 wrongDevice = true;
2087 goto Failed;
2088 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002089 tempTouchState.reset();
2090 tempTouchState.down = down;
2091 tempTouchState.deviceId = entry.deviceId;
2092 tempTouchState.source = entry.source;
2093 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002095 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002096 ALOGI("Dropping move event because a pointer for a different device is already active "
2097 "in display %" PRId32,
2098 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002099 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002100 outInjectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002101 switchedDevice = false;
2102 wrongDevice = true;
2103 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 }
2105
2106 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2107 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002108 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002109 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002110 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002111 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002112 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002113 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002114
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002116 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002117 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2118 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002120 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002121 }
2122
Prabir Pradhan5735a322022-04-11 17:23:34 +00002123 // Verify targeted injection.
2124 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2125 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002126 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002127 newTouchedWindowHandle = nullptr;
2128 goto Failed;
2129 }
2130
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002131 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002132 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002133 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2134 // New window supports splitting, but we should never split mouse events.
2135 isSplit = !isFromMouse;
2136 } else if (isSplit) {
2137 // New window does not support splitting but we have already split events.
2138 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002139 newTouchedWindowHandle = nullptr;
2140 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002141 } else {
2142 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002143 // be delivered to a new window which supports split touch. Pointers from a mouse device
2144 // should never be split.
2145 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002146 }
2147
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002148 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002149 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002150 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2151 newHoverWindowHandle = nullptr;
2152 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002153 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002154 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002155 }
2156
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002157 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002158 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002159 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002160 // Process the foreground window first so that it is the first to receive the event.
2161 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002162 }
2163
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002164 if (newTouchedWindows.empty()) {
2165 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2166 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002167 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002168 goto Failed;
2169 }
2170
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002171 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002172 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002173 continue;
2174 }
2175
2176 // Set target flags.
2177 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2178
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002179 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2180 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002181 targetFlags |= InputTarget::FLAG_FOREGROUND;
2182 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002183
2184 if (isSplit) {
2185 targetFlags |= InputTarget::FLAG_SPLIT;
2186 }
2187 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2188 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2189 } else if (isWindowObscuredLocked(windowHandle)) {
2190 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2191 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002192
2193 // Update the temporary touch state.
2194 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002195 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002196
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002197 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2198 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002200
2201 // If any existing window is pilfering pointers from newly added window, remove it
2202 BitSet32 canceledPointers = BitSet32(0);
2203 for (const TouchedWindow& window : tempTouchState.windows) {
2204 if (window.isPilferingPointers) {
2205 canceledPointers |= window.pointerIds;
2206 }
2207 }
2208 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 } else {
2210 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2211
2212 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002213 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002214 if (DEBUG_FOCUS) {
2215 ALOGD("Dropping event because the pointer is not down or we previously "
2216 "dropped the pointer down event in display %" PRId32,
2217 displayId);
2218 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002219 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 goto Failed;
2221 }
2222
arthurhung6d4bed92021-03-17 11:59:33 +08002223 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002224
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002226 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002227 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002228 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002229 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002230 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002231 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002232 newTouchedWindowHandle =
2233 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002234
Prabir Pradhan5735a322022-04-11 17:23:34 +00002235 // Verify targeted injection.
2236 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2237 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002238 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002239 newTouchedWindowHandle = nullptr;
2240 goto Failed;
2241 }
2242
Vishnu Nair062a8672021-09-03 16:07:44 -07002243 // Drop touch events if requested by input feature
2244 if (newTouchedWindowHandle != nullptr &&
2245 shouldDropInput(entry, newTouchedWindowHandle)) {
2246 newTouchedWindowHandle = nullptr;
2247 }
2248
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002249 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2250 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002251 if (DEBUG_FOCUS) {
2252 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2253 oldTouchedWindowHandle->getName().c_str(),
2254 newTouchedWindowHandle->getName().c_str(), displayId);
2255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002257 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2258 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2259 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260
2261 // Make a slippery entrance into the new window.
2262 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002263 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 }
2265
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002266 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2267 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2268 targetFlags |= InputTarget::FLAG_FOREGROUND;
2269 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 if (isSplit) {
2271 targetFlags |= InputTarget::FLAG_SPLIT;
2272 }
2273 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2274 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002275 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2276 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 }
2278
2279 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002280 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002281 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2282 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284 }
2285 }
2286
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002287 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002289 // Let the previous window know that the hover sequence is over, unless we already did
2290 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002291 if (mLastHoverWindowHandle != nullptr &&
2292 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2293 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002294 if (DEBUG_HOVER) {
2295 ALOGD("Sending hover exit event to window %s.",
2296 mLastHoverWindowHandle->getName().c_str());
2297 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002298 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2299 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 }
2301
Garfield Tandf26e862020-07-01 20:18:19 -07002302 // Let the new window know that the hover sequence is starting, unless we already did it
2303 // when dispatching it as is to newTouchedWindowHandle.
2304 if (newHoverWindowHandle != nullptr &&
2305 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2306 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002307 if (DEBUG_HOVER) {
2308 ALOGD("Sending hover enter event to window %s.",
2309 newHoverWindowHandle->getName().c_str());
2310 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002311 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2312 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2313 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
2315 }
2316
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002317 // Ensure that we have at least one foreground window or at least one window that cannot be a
2318 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2319 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2320 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002321 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2322 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002323 return !canReceiveForegroundTouches(
2324 *touchedWindow.windowHandle->getInfo()) ||
2325 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002326 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002327 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2328 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002329 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002330 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 }
2332
Prabir Pradhan5735a322022-04-11 17:23:34 +00002333 // Ensure that all touched windows are valid for injection.
2334 if (entry.injectionState != nullptr) {
2335 std::string errs;
2336 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2337 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2338 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2339 // dispatched to any uid, since the coords will be zeroed out later.
2340 continue;
2341 }
2342 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2343 if (err) errs += "\n - " + *err;
2344 }
2345 if (!errs.empty()) {
2346 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2347 "%d:%s",
2348 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002349 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002350 goto Failed;
2351 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002352 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002353
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 // Check whether windows listening for outside touches are owned by the same UID. If it is
2355 // set the policy flag that we will not reveal coordinate information to this window.
2356 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002357 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002358 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002359 if (foregroundWindowHandle) {
2360 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002361 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002362 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002363 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2364 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2365 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002366 InputTarget::FLAG_ZERO_COORDS,
2367 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369 }
2370 }
2371 }
2372 }
2373
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 // If this is the first pointer going down and the touched window has a wallpaper
2375 // then also add the touched wallpaper windows so they are locked in for the duration
2376 // of the touch gesture.
2377 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2378 // engine only supports touch events. We would need to add a mechanism similar
2379 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2380 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002381 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002382 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002383 if (foregroundWindowHandle &&
2384 foregroundWindowHandle->getInfo()->inputConfig.test(
2385 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002386 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002387 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002388 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2389 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002390 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002391 windowHandle->getInfo()->inputConfig.test(
2392 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002393 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002394 .addOrUpdateWindow(windowHandle,
2395 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2396 InputTarget::
2397 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2398 InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002399 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400 }
2401 }
2402 }
2403 }
2404
2405 // Success! Output targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002406 touchedWindows = tempTouchState.windows;
2407 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408
2409 // Drop the outside or hover touch windows since we will not care about them
2410 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002411 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412
2413Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002415 if (!wrongDevice) {
2416 if (switchedDevice) {
2417 if (DEBUG_FOCUS) {
2418 ALOGD("Conflicting pointer actions: Switched to a different device.");
2419 }
2420 *outConflictingPointerActions = true;
2421 }
2422
2423 if (isHoverAction) {
2424 // Started hovering, therefore no longer down.
2425 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002426 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002427 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2428 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 *outConflictingPointerActions = true;
2431 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002432 tempTouchState.reset();
2433 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2434 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2435 tempTouchState.deviceId = entry.deviceId;
2436 tempTouchState.source = entry.source;
2437 tempTouchState.displayId = displayId;
2438 }
2439 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2440 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2441 // All pointers up or canceled.
2442 tempTouchState.reset();
2443 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2444 // First pointer went down.
2445 if (oldState && oldState->down) {
2446 if (DEBUG_FOCUS) {
2447 ALOGD("Conflicting pointer actions: Down received while already down.");
2448 }
2449 *outConflictingPointerActions = true;
2450 }
2451 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2452 // One pointer went up.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002453 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2454 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002456 for (size_t i = 0; i < tempTouchState.windows.size();) {
2457 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2458 touchedWindow.pointerIds.clearBit(pointerId);
2459 if (touchedWindow.pointerIds.isEmpty()) {
2460 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2461 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002463 i += 1;
2464 }
2465 } else if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2466 // If no split, we suppose all touched windows should receive pointer down.
2467 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2468 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2469 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2470 // Ignore drag window for it should just track one pointer.
2471 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2472 continue;
2473 }
2474 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Jeff Brownf086ddb2014-02-11 14:28:48 -08002475 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002476 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002477
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002478 // Save changes unless the action was scroll in which case the temporary touch
2479 // state was only valid for this one action.
2480 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2481 if (tempTouchState.displayId >= 0) {
2482 mTouchStatesByDisplay[displayId] = tempTouchState;
2483 } else {
2484 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002488 // Update hover state.
2489 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 }
2491
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002492 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493}
2494
arthurhung6d4bed92021-03-17 11:59:33 +08002495void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002496 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2497 // have an explicit reason to support it.
2498 constexpr bool isStylus = false;
2499
chaviw98318de2021-05-19 16:45:23 -05002500 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002501 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002502 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002503 if (dropWindow) {
2504 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002505 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002506 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002507 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002508 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002509 }
2510 mDragState.reset();
2511}
2512
2513void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002514 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002515 return;
2516 }
2517
arthurhung6d4bed92021-03-17 11:59:33 +08002518 if (!mDragState->isStartDrag) {
2519 mDragState->isStartDrag = true;
2520 mDragState->isStylusButtonDownAtStart =
2521 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2522 }
2523
Arthur Hung54745652022-04-20 07:17:41 +00002524 // Find the pointer index by id.
2525 int32_t pointerIndex = 0;
2526 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2527 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2528 if (pointerProperties.id == mDragState->pointerId) {
2529 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002530 }
Arthur Hung54745652022-04-20 07:17:41 +00002531 }
arthurhung6d4bed92021-03-17 11:59:33 +08002532
Arthur Hung54745652022-04-20 07:17:41 +00002533 if (uint32_t(pointerIndex) == entry.pointerCount) {
2534 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002535 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002536 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002537 return;
2538 }
2539
2540 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2541 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2542 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2543
2544 switch (maskedAction) {
2545 case AMOTION_EVENT_ACTION_MOVE: {
2546 // Handle the special case : stylus button no longer pressed.
2547 bool isStylusButtonDown =
2548 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2549 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2550 finishDragAndDrop(entry.displayId, x, y);
2551 return;
2552 }
2553
2554 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2555 // until we have an explicit reason to support it.
2556 constexpr bool isStylus = false;
2557
2558 const sp<WindowInfoHandle> hoverWindowHandle =
2559 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2560 isStylus, false /*addOutsideTargets*/,
2561 true /*ignoreDragWindow*/);
2562 // enqueue drag exit if needed.
2563 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2564 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2565 if (mDragState->dragHoverWindowHandle != nullptr) {
2566 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2567 y);
2568 }
2569 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2570 }
2571 // enqueue drag location if needed.
2572 if (hoverWindowHandle != nullptr) {
2573 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2574 }
2575 break;
2576 }
2577
2578 case AMOTION_EVENT_ACTION_POINTER_UP:
2579 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2580 break;
2581 }
2582 // The drag pointer is up.
2583 [[fallthrough]];
2584 case AMOTION_EVENT_ACTION_UP:
2585 finishDragAndDrop(entry.displayId, x, y);
2586 break;
2587 case AMOTION_EVENT_ACTION_CANCEL: {
2588 ALOGD("Receiving cancel when drag and drop.");
2589 sendDropWindowCommandLocked(nullptr, 0, 0);
2590 mDragState.reset();
2591 break;
2592 }
arthurhungb89ccb02020-12-30 16:19:01 +08002593 }
2594}
2595
chaviw98318de2021-05-19 16:45:23 -05002596void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002597 int32_t targetFlags, BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002598 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002599 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002600 std::vector<InputTarget>::iterator it =
2601 std::find_if(inputTargets.begin(), inputTargets.end(),
2602 [&windowHandle](const InputTarget& inputTarget) {
2603 return inputTarget.inputChannel->getConnectionToken() ==
2604 windowHandle->getToken();
2605 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002606
chaviw98318de2021-05-19 16:45:23 -05002607 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002608
2609 if (it == inputTargets.end()) {
2610 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002611 std::shared_ptr<InputChannel> inputChannel =
2612 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002613 if (inputChannel == nullptr) {
2614 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2615 return;
2616 }
2617 inputTarget.inputChannel = inputChannel;
2618 inputTarget.flags = targetFlags;
2619 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002620 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002621 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2622 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002623 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002624 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002625 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002626 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002627 inputTargets.push_back(inputTarget);
2628 it = inputTargets.end() - 1;
2629 }
2630
2631 ALOG_ASSERT(it->flags == targetFlags);
2632 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2633
chaviw1ff3d1e2020-07-01 15:53:47 -07002634 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002635}
2636
Michael Wright3dd60e22019-03-27 22:06:44 +00002637void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002638 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002639 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2640 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002641
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002642 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2643 InputTarget target;
2644 target.inputChannel = monitor.inputChannel;
2645 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002646 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2647 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002648 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2649 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002650 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002651 target.setDefaultPointerTransform(target.displayTransform);
2652 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 }
2654}
2655
Robert Carrc9bf1d32020-04-13 17:21:08 -07002656/**
2657 * Indicate whether one window handle should be considered as obscuring
2658 * another window handle. We only check a few preconditions. Actually
2659 * checking the bounds is left to the caller.
2660 */
chaviw98318de2021-05-19 16:45:23 -05002661static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2662 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002663 // Compare by token so cloned layers aren't counted
2664 if (haveSameToken(windowHandle, otherHandle)) {
2665 return false;
2666 }
2667 auto info = windowHandle->getInfo();
2668 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002669 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002670 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002671 } else if (otherInfo->alpha == 0 &&
2672 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002673 // Those act as if they were invisible, so we don't need to flag them.
2674 // We do want to potentially flag touchable windows even if they have 0
2675 // opacity, since they can consume touches and alter the effects of the
2676 // user interaction (eg. apps that rely on
2677 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2678 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2679 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002680 } else if (info->ownerUid == otherInfo->ownerUid) {
2681 // If ownerUid is the same we don't generate occlusion events as there
2682 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002683 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002684 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002685 return false;
2686 } else if (otherInfo->displayId != info->displayId) {
2687 return false;
2688 }
2689 return true;
2690}
2691
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002692/**
2693 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2694 * untrusted, one should check:
2695 *
2696 * 1. If result.hasBlockingOcclusion is true.
2697 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2698 * BLOCK_UNTRUSTED.
2699 *
2700 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2701 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2702 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2703 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2704 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2705 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2706 *
2707 * If neither of those is true, then it means the touch can be allowed.
2708 */
2709InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002710 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2711 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002712 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002713 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002714 TouchOcclusionInfo info;
2715 info.hasBlockingOcclusion = false;
2716 info.obscuringOpacity = 0;
2717 info.obscuringUid = -1;
2718 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002719 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002720 if (windowHandle == otherHandle) {
2721 break; // All future windows are below us. Exit early.
2722 }
chaviw98318de2021-05-19 16:45:23 -05002723 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002724 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2725 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002726 if (DEBUG_TOUCH_OCCLUSION) {
2727 info.debugInfo.push_back(
2728 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2729 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002730 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2731 // we perform the checks below to see if the touch can be propagated or not based on the
2732 // window's touch occlusion mode
2733 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2734 info.hasBlockingOcclusion = true;
2735 info.obscuringUid = otherInfo->ownerUid;
2736 info.obscuringPackage = otherInfo->packageName;
2737 break;
2738 }
2739 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2740 uint32_t uid = otherInfo->ownerUid;
2741 float opacity =
2742 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2743 // Given windows A and B:
2744 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2745 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2746 opacityByUid[uid] = opacity;
2747 if (opacity > info.obscuringOpacity) {
2748 info.obscuringOpacity = opacity;
2749 info.obscuringUid = uid;
2750 info.obscuringPackage = otherInfo->packageName;
2751 }
2752 }
2753 }
2754 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002755 if (DEBUG_TOUCH_OCCLUSION) {
2756 info.debugInfo.push_back(
2757 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2758 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002759 return info;
2760}
2761
chaviw98318de2021-05-19 16:45:23 -05002762std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002763 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002764 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2765 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2766 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2767 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002768 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2769 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2770 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2771 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2772 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002773 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002774 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002775}
2776
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002777bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2778 if (occlusionInfo.hasBlockingOcclusion) {
2779 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2780 occlusionInfo.obscuringUid);
2781 return false;
2782 }
2783 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2784 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2785 "%.2f, maximum allowed = %.2f)",
2786 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2787 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2788 return false;
2789 }
2790 return true;
2791}
2792
chaviw98318de2021-05-19 16:45:23 -05002793bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002794 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002796 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2797 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002798 if (windowHandle == otherHandle) {
2799 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800 }
chaviw98318de2021-05-19 16:45:23 -05002801 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002802 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002803 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002804 return true;
2805 }
2806 }
2807 return false;
2808}
2809
chaviw98318de2021-05-19 16:45:23 -05002810bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002811 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002812 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2813 const WindowInfo* windowInfo = windowHandle->getInfo();
2814 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002815 if (windowHandle == otherHandle) {
2816 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002817 }
chaviw98318de2021-05-19 16:45:23 -05002818 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002819 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002820 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002821 return true;
2822 }
2823 }
2824 return false;
2825}
2826
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002827std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002828 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002829 if (applicationHandle != nullptr) {
2830 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002831 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 } else {
2833 return applicationHandle->getName();
2834 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002835 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002836 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002838 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839 }
2840}
2841
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002842void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002843 if (!isUserActivityEvent(eventEntry)) {
2844 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002845 return;
2846 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002847 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002848 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002849 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002850 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002851 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002852 if (DEBUG_DISPATCH_CYCLE) {
2853 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2854 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855 return;
2856 }
2857 }
2858
2859 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002860 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002861 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002862 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2863 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002864 return;
2865 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002867 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002868 eventType = USER_ACTIVITY_EVENT_TOUCH;
2869 }
2870 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002872 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002873 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2874 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002875 return;
2876 }
2877 eventType = USER_ACTIVITY_EVENT_BUTTON;
2878 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002879 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002880 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002881 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002882 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002883 break;
2884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885 }
2886
Prabir Pradhancef936d2021-07-21 16:17:52 +00002887 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2888 REQUIRES(mLock) {
2889 scoped_unlock unlock(mLock);
2890 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2891 };
2892 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893}
2894
2895void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002896 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002897 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002898 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002899 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002900 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002901 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002902 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002903 ATRACE_NAME(message.c_str());
2904 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002905 if (DEBUG_DISPATCH_CYCLE) {
2906 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2907 "globalScaleFactor=%f, pointerIds=0x%x %s",
2908 connection->getInputChannelName().c_str(), inputTarget.flags,
2909 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2910 inputTarget.getPointerInfoString().c_str());
2911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912
2913 // Skip this event if the connection status is not normal.
2914 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002915 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002916 if (DEBUG_DISPATCH_CYCLE) {
2917 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002918 connection->getInputChannelName().c_str(),
2919 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921 return;
2922 }
2923
2924 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002925 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2926 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2927 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002928 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002930 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002931 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002932 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2933 "Splitting motion events requires a down time to be set for the "
2934 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002935 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002936 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2937 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 if (!splitMotionEntry) {
2939 return; // split event was dropped
2940 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002941 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2942 std::string reason = std::string("reason=pointer cancel on split window");
2943 android_log_event_list(LOGTAG_INPUT_CANCEL)
2944 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2945 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002946 if (DEBUG_FOCUS) {
2947 ALOGD("channel '%s' ~ Split motion event.",
2948 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002949 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002950 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002951 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2952 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953 return;
2954 }
2955 }
2956
2957 // Not splitting. Enqueue dispatch entries for the event as is.
2958 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2959}
2960
2961void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002962 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002963 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002964 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002965 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002966 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002967 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002968 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002969 ATRACE_NAME(message.c_str());
2970 }
2971
hongzuo liu95785e22022-09-06 02:51:35 +00002972 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973
2974 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002975 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002976 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002977 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002978 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002979 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002980 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002981 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002982 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002983 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002984 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002985 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002986 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002987
2988 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002989 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990 startDispatchCycleLocked(currentTime, connection);
2991 }
2992}
2993
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002994void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002995 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002996 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002997 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002998 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002999 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3000 connection->getInputChannelName().c_str(),
3001 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003002 ATRACE_NAME(message.c_str());
3003 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003004 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 if (!(inputTargetFlags & dispatchMode)) {
3006 return;
3007 }
3008 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
3009
3010 // This is a new event.
3011 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003012 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003013 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003015 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3016 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003017 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003018 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003019 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003020 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003021 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003022 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003023 dispatchEntry->resolvedAction = keyEntry.action;
3024 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003026 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3027 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003028 if (DEBUG_DISPATCH_CYCLE) {
3029 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3030 "event",
3031 connection->getInputChannelName().c_str());
3032 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003033 return; // skip the inconsistent event
3034 }
3035 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003038 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003039 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003040 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3041 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3042 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3043 static_cast<int32_t>(IdGenerator::Source::OTHER);
3044 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003045 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3046 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3047 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3048 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3049 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3050 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3051 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3052 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3053 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3054 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3055 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003056 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003057 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003058 }
3059 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003060 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3061 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003062 if (DEBUG_DISPATCH_CYCLE) {
3063 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3064 "enter event",
3065 connection->getInputChannelName().c_str());
3066 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003067 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3068 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003069 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3070 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003072 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003073 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3074 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3075 }
3076 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3077 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003080 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3081 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003082 if (DEBUG_DISPATCH_CYCLE) {
3083 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3084 "event",
3085 connection->getInputChannelName().c_str());
3086 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003087 return; // skip the inconsistent event
3088 }
3089
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003090 dispatchEntry->resolvedEventId =
3091 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3092 ? mIdGenerator.nextId()
3093 : motionEntry.id;
3094 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3095 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3096 ") to MotionEvent(id=0x%" PRIx32 ").",
3097 motionEntry.id, dispatchEntry->resolvedEventId);
3098 ATRACE_NAME(message.c_str());
3099 }
3100
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003101 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3102 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3103 // Skip reporting pointer down outside focus to the policy.
3104 break;
3105 }
3106
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003107 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003108 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003109
3110 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003112 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003113 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003114 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3115 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003116 break;
3117 }
Chris Yef59a2f42020-10-16 12:55:26 -07003118 case EventEntry::Type::SENSOR: {
3119 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3120 break;
3121 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003122 case EventEntry::Type::CONFIGURATION_CHANGED:
3123 case EventEntry::Type::DEVICE_RESET: {
3124 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003125 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003126 break;
3127 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 }
3129
3130 // Remember that we are waiting for this dispatch to complete.
3131 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003132 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003133 }
3134
3135 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003136 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003137 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003138}
3139
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003140/**
3141 * This function is purely for debugging. It helps us understand where the user interaction
3142 * was taking place. For example, if user is touching launcher, we will see a log that user
3143 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3144 * We will see both launcher and wallpaper in that list.
3145 * Once the interaction with a particular set of connections starts, no new logs will be printed
3146 * until the set of interacted connections changes.
3147 *
3148 * The following items are skipped, to reduce the logspam:
3149 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3150 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3151 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3152 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3153 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003154 */
3155void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3156 const std::vector<InputTarget>& targets) {
3157 // Skip ACTION_UP events, and all events other than keys and motions
3158 if (entry.type == EventEntry::Type::KEY) {
3159 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3160 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3161 return;
3162 }
3163 } else if (entry.type == EventEntry::Type::MOTION) {
3164 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3165 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3166 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3167 return;
3168 }
3169 } else {
3170 return; // Not a key or a motion
3171 }
3172
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003173 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003174 std::vector<sp<Connection>> newConnections;
3175 for (const InputTarget& target : targets) {
3176 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3177 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3178 continue; // Skip windows that receive ACTION_OUTSIDE
3179 }
3180
3181 sp<IBinder> token = target.inputChannel->getConnectionToken();
3182 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003183 if (connection == nullptr) {
3184 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003185 }
3186 newConnectionTokens.insert(std::move(token));
3187 newConnections.emplace_back(connection);
3188 }
3189 if (newConnectionTokens == mInteractionConnectionTokens) {
3190 return; // no change
3191 }
3192 mInteractionConnectionTokens = newConnectionTokens;
3193
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003194 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003195 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003196 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003197 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003198 std::string message = "Interaction with: " + targetList;
3199 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003200 message += "<none>";
3201 }
3202 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3203}
3204
chaviwfd6d3512019-03-25 13:23:49 -07003205void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003206 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003207 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003208 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3209 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003210 return;
3211 }
3212
Vishnu Nairc519ff72021-01-21 08:23:08 -08003213 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003214 if (focusedToken == token) {
3215 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003216 return;
3217 }
3218
Prabir Pradhancef936d2021-07-21 16:17:52 +00003219 auto command = [this, token]() REQUIRES(mLock) {
3220 scoped_unlock unlock(mLock);
3221 mPolicy->onPointerDownOutsideFocus(token);
3222 };
3223 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224}
3225
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003226status_t InputDispatcher::publishMotionEvent(Connection& connection,
3227 DispatchEntry& dispatchEntry) const {
3228 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3229 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3230
3231 PointerCoords scaledCoords[MAX_POINTERS];
3232 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3233
3234 // Set the X and Y offset and X and Y scale depending on the input source.
3235 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
3236 !(dispatchEntry.targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3237 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3238 if (globalScaleFactor != 1.0f) {
3239 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3240 scaledCoords[i] = motionEntry.pointerCoords[i];
3241 // Don't apply window scale here since we don't want scale to affect raw
3242 // coordinates. The scale will be sent back to the client and applied
3243 // later when requesting relative coordinates.
3244 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3245 1 /* windowYScale */);
3246 }
3247 usingCoords = scaledCoords;
3248 }
3249 } else if (dispatchEntry.targetFlags & InputTarget::FLAG_ZERO_COORDS) {
3250 // We don't want the dispatch target to know the coordinates
3251 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3252 scaledCoords[i].clear();
3253 }
3254 usingCoords = scaledCoords;
3255 }
3256
3257 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3258
3259 // Publish the motion event.
3260 return connection.inputPublisher
3261 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3262 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3263 std::move(hmac), dispatchEntry.resolvedAction,
3264 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3265 motionEntry.edgeFlags, motionEntry.metaState,
3266 motionEntry.buttonState, motionEntry.classification,
3267 dispatchEntry.transform, motionEntry.xPrecision,
3268 motionEntry.yPrecision, motionEntry.xCursorPosition,
3269 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3270 motionEntry.downTime, motionEntry.eventTime,
3271 motionEntry.pointerCount, motionEntry.pointerProperties,
3272 usingCoords);
3273}
3274
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003276 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003277 if (ATRACE_ENABLED()) {
3278 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003279 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003280 ATRACE_NAME(message.c_str());
3281 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003282 if (DEBUG_DISPATCH_CYCLE) {
3283 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003286 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003287 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003289 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003290 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291
3292 // Publish the event.
3293 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003294 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3295 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003296 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003297 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3298 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003300 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003301 status = connection->inputPublisher
3302 .publishKeyEvent(dispatchEntry->seq,
3303 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3304 keyEntry.source, keyEntry.displayId,
3305 std::move(hmac), dispatchEntry->resolvedAction,
3306 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3307 keyEntry.scanCode, keyEntry.metaState,
3308 keyEntry.repeatCount, keyEntry.downTime,
3309 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003310 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 }
3312
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003313 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003314 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003315 break;
3316 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003317
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003318 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003319 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003320 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003321 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003322 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003323 break;
3324 }
3325
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003326 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3327 const TouchModeEntry& touchModeEntry =
3328 static_cast<const TouchModeEntry&>(eventEntry);
3329 status = connection->inputPublisher
3330 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3331 touchModeEntry.inTouchMode);
3332
3333 break;
3334 }
3335
Prabir Pradhan99987712020-11-10 18:43:05 -08003336 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3337 const auto& captureEntry =
3338 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3339 status = connection->inputPublisher
3340 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003341 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003342 break;
3343 }
3344
arthurhungb89ccb02020-12-30 16:19:01 +08003345 case EventEntry::Type::DRAG: {
3346 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3347 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3348 dragEntry.id, dragEntry.x,
3349 dragEntry.y,
3350 dragEntry.isExiting);
3351 break;
3352 }
3353
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003354 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003355 case EventEntry::Type::DEVICE_RESET:
3356 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003357 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003358 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003359 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361 }
3362
3363 // Check the result.
3364 if (status) {
3365 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003366 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003368 "This is unexpected because the wait queue is empty, so the pipe "
3369 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003370 "event to it, status=%s(%d)",
3371 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3372 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3374 } else {
3375 // Pipe is full and we are waiting for the app to finish process some events
3376 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003377 if (DEBUG_DISPATCH_CYCLE) {
3378 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3379 "waiting for the application to catch up",
3380 connection->getInputChannelName().c_str());
3381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 }
3383 } else {
3384 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003385 "status=%s(%d)",
3386 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3387 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3389 }
3390 return;
3391 }
3392
3393 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003394 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3395 connection->outboundQueue.end(),
3396 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003397 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003398 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003399 if (connection->responsive) {
3400 mAnrTracker.insert(dispatchEntry->timeoutTime,
3401 connection->inputChannel->getConnectionToken());
3402 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003403 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 }
3405}
3406
chaviw09c8d2d2020-08-24 15:48:26 -07003407std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3408 size_t size;
3409 switch (event.type) {
3410 case VerifiedInputEvent::Type::KEY: {
3411 size = sizeof(VerifiedKeyEvent);
3412 break;
3413 }
3414 case VerifiedInputEvent::Type::MOTION: {
3415 size = sizeof(VerifiedMotionEvent);
3416 break;
3417 }
3418 }
3419 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3420 return mHmacKeyManager.sign(start, size);
3421}
3422
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003423const std::array<uint8_t, 32> InputDispatcher::getSignature(
3424 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003425 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3426 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003427 // Only sign events up and down events as the purely move events
3428 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003429 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003430 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003431
3432 VerifiedMotionEvent verifiedEvent =
3433 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3434 verifiedEvent.actionMasked = actionMasked;
3435 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3436 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003437}
3438
3439const std::array<uint8_t, 32> InputDispatcher::getSignature(
3440 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3441 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3442 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3443 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003444 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003445}
3446
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003448 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003449 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003450 if (DEBUG_DISPATCH_CYCLE) {
3451 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3452 connection->getInputChannelName().c_str(), seq, toString(handled));
3453 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003455 if (connection->status == Connection::Status::BROKEN ||
3456 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457 return;
3458 }
3459
3460 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003461 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3462 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3463 };
3464 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465}
3466
3467void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003468 const sp<Connection>& connection,
3469 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003470 if (DEBUG_DISPATCH_CYCLE) {
3471 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3472 connection->getInputChannelName().c_str(), toString(notify));
3473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474
3475 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003476 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003477 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003478 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003479 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480
3481 // The connection appears to be unrecoverably broken.
3482 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003483 if (connection->status == Connection::Status::NORMAL) {
3484 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485
3486 if (notify) {
3487 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003488 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3489 connection->getInputChannelName().c_str());
3490
3491 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003492 scoped_unlock unlock(mLock);
3493 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3494 };
3495 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 }
3497 }
3498}
3499
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003500void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3501 while (!queue.empty()) {
3502 DispatchEntry* dispatchEntry = queue.front();
3503 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003504 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 }
3506}
3507
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003508void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003510 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 }
3512 delete dispatchEntry;
3513}
3514
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003515int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3516 std::scoped_lock _l(mLock);
3517 sp<Connection> connection = getConnectionLocked(connectionToken);
3518 if (connection == nullptr) {
3519 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3520 connectionToken.get(), events);
3521 return 0; // remove the callback
3522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003524 bool notify;
3525 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3526 if (!(events & ALOOPER_EVENT_INPUT)) {
3527 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3528 "events=0x%x",
3529 connection->getInputChannelName().c_str(), events);
3530 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 }
3532
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003533 nsecs_t currentTime = now();
3534 bool gotOne = false;
3535 status_t status = OK;
3536 for (;;) {
3537 Result<InputPublisher::ConsumerResponse> result =
3538 connection->inputPublisher.receiveConsumerResponse();
3539 if (!result.ok()) {
3540 status = result.error().code();
3541 break;
3542 }
3543
3544 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3545 const InputPublisher::Finished& finish =
3546 std::get<InputPublisher::Finished>(*result);
3547 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3548 finish.consumeTime);
3549 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003550 if (shouldReportMetricsForConnection(*connection)) {
3551 const InputPublisher::Timeline& timeline =
3552 std::get<InputPublisher::Timeline>(*result);
3553 mLatencyTracker
3554 .trackGraphicsLatency(timeline.inputEventId,
3555 connection->inputChannel->getConnectionToken(),
3556 std::move(timeline.graphicsTimeline));
3557 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003558 }
3559 gotOne = true;
3560 }
3561 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003562 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003563 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 return 1;
3565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566 }
3567
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003568 notify = status != DEAD_OBJECT || !connection->monitor;
3569 if (notify) {
3570 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3571 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3572 status);
3573 }
3574 } else {
3575 // Monitor channels are never explicitly unregistered.
3576 // We do it automatically when the remote endpoint is closed so don't warn about them.
3577 const bool stillHaveWindowHandle =
3578 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3579 notify = !connection->monitor && stillHaveWindowHandle;
3580 if (notify) {
3581 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3582 connection->getInputChannelName().c_str(), events);
3583 }
3584 }
3585
3586 // Remove the channel.
3587 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3588 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589}
3590
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003591void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003593 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003594 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 }
3596}
3597
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003598void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003599 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003600 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003601 for (const Monitor& monitor : monitors) {
3602 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003603 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003604 }
3605}
3606
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003608 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003609 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003610 if (connection == nullptr) {
3611 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003613
3614 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615}
3616
3617void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3618 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003619 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 return;
3621 }
3622
3623 nsecs_t currentTime = now();
3624
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003625 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003626 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003628 if (cancelationEvents.empty()) {
3629 return;
3630 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003631 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3632 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3633 "with reality: %s, mode=%d.",
3634 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3635 options.mode);
3636 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003637
Arthur Hungb3307ee2021-10-14 10:57:37 +00003638 std::string reason = std::string("reason=").append(options.reason);
3639 android_log_event_list(LOGTAG_INPUT_CANCEL)
3640 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3641
Svet Ganov5d3bc372020-01-26 23:11:07 -08003642 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003643 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003644 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3645 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003646 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003647 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003648 target.globalScaleFactor = windowInfo->globalScaleFactor;
3649 }
3650 target.inputChannel = connection->inputChannel;
3651 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3652
hongzuo liu95785e22022-09-06 02:51:35 +00003653 const bool wasEmpty = connection->outboundQueue.empty();
3654
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003655 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003656 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003657 switch (cancelationEventEntry->type) {
3658 case EventEntry::Type::KEY: {
3659 logOutboundKeyDetails("cancel - ",
3660 static_cast<const KeyEntry&>(*cancelationEventEntry));
3661 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003663 case EventEntry::Type::MOTION: {
3664 logOutboundMotionDetails("cancel - ",
3665 static_cast<const MotionEntry&>(*cancelationEventEntry));
3666 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003668 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003669 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003670 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3671 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003672 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003673 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003674 break;
3675 }
3676 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003677 case EventEntry::Type::DEVICE_RESET:
3678 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003679 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003680 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003681 break;
3682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 }
3684
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003685 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3686 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003688
hongzuo liu95785e22022-09-06 02:51:35 +00003689 // If the outbound queue was previously empty, start the dispatch cycle going.
3690 if (wasEmpty && !connection->outboundQueue.empty()) {
3691 startDispatchCycleLocked(currentTime, connection);
3692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693}
3694
Svet Ganov5d3bc372020-01-26 23:11:07 -08003695void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003696 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003697 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003698 return;
3699 }
3700
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003701 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003702 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003703
3704 if (downEvents.empty()) {
3705 return;
3706 }
3707
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003708 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003709 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3710 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003711 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003712
3713 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003714 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003715 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3716 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003717 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003718 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003719 target.globalScaleFactor = windowInfo->globalScaleFactor;
3720 }
3721 target.inputChannel = connection->inputChannel;
3722 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3723
hongzuo liu95785e22022-09-06 02:51:35 +00003724 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003725 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003726 switch (downEventEntry->type) {
3727 case EventEntry::Type::MOTION: {
3728 logOutboundMotionDetails("down - ",
3729 static_cast<const MotionEntry&>(*downEventEntry));
3730 break;
3731 }
3732
3733 case EventEntry::Type::KEY:
3734 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003735 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003736 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003737 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003738 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003739 case EventEntry::Type::SENSOR:
3740 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003741 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003742 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003743 break;
3744 }
3745 }
3746
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003747 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3748 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003749 }
3750
hongzuo liu95785e22022-09-06 02:51:35 +00003751 // If the outbound queue was previously empty, start the dispatch cycle going.
3752 if (wasEmpty && !connection->outboundQueue.empty()) {
3753 startDispatchCycleLocked(downTime, connection);
3754 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003755}
3756
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003757std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003758 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 ALOG_ASSERT(pointerIds.value != 0);
3760
3761 uint32_t splitPointerIndexMap[MAX_POINTERS];
3762 PointerProperties splitPointerProperties[MAX_POINTERS];
3763 PointerCoords splitPointerCoords[MAX_POINTERS];
3764
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003765 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 uint32_t splitPointerCount = 0;
3767
3768 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003769 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003771 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 uint32_t pointerId = uint32_t(pointerProperties.id);
3773 if (pointerIds.hasBit(pointerId)) {
3774 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3775 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3776 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003777 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 splitPointerCount += 1;
3779 }
3780 }
3781
3782 if (splitPointerCount != pointerIds.count()) {
3783 // This is bad. We are missing some of the pointers that we expected to deliver.
3784 // Most likely this indicates that we received an ACTION_MOVE events that has
3785 // different pointer ids than we expected based on the previous ACTION_DOWN
3786 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3787 // in this way.
3788 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003789 "we expected there to be %d pointers. This probably means we received "
3790 "a broken sequence of pointer ids from the input device.",
3791 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003792 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 }
3794
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003795 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003797 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3798 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3800 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003801 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802 uint32_t pointerId = uint32_t(pointerProperties.id);
3803 if (pointerIds.hasBit(pointerId)) {
3804 if (pointerIds.count() == 1) {
3805 // The first/last pointer went down/up.
3806 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003807 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003808 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3809 ? AMOTION_EVENT_ACTION_CANCEL
3810 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 } else {
3812 // A secondary pointer went down/up.
3813 uint32_t splitPointerIndex = 0;
3814 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3815 splitPointerIndex += 1;
3816 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003817 action = maskedAction |
3818 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 }
3820 } else {
3821 // An unrelated pointer changed.
3822 action = AMOTION_EVENT_ACTION_MOVE;
3823 }
3824 }
3825
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003826 if (action == AMOTION_EVENT_ACTION_DOWN) {
3827 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3828 "Split motion event has mismatching downTime and eventTime for "
3829 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3830 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3831 }
3832
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003833 int32_t newId = mIdGenerator.nextId();
3834 if (ATRACE_ENABLED()) {
3835 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3836 ") to MotionEvent(id=0x%" PRIx32 ").",
3837 originalMotionEntry.id, newId);
3838 ATRACE_NAME(message.c_str());
3839 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003840 std::unique_ptr<MotionEntry> splitMotionEntry =
3841 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3842 originalMotionEntry.deviceId, originalMotionEntry.source,
3843 originalMotionEntry.displayId,
3844 originalMotionEntry.policyFlags, action,
3845 originalMotionEntry.actionButton,
3846 originalMotionEntry.flags, originalMotionEntry.metaState,
3847 originalMotionEntry.buttonState,
3848 originalMotionEntry.classification,
3849 originalMotionEntry.edgeFlags,
3850 originalMotionEntry.xPrecision,
3851 originalMotionEntry.yPrecision,
3852 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003853 originalMotionEntry.yCursorPosition, splitDownTime,
3854 splitPointerCount, splitPointerProperties,
3855 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003857 if (originalMotionEntry.injectionState) {
3858 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859 splitMotionEntry->injectionState->refCount += 1;
3860 }
3861
3862 return splitMotionEntry;
3863}
3864
3865void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003866 if (DEBUG_INBOUND_EVENT_DETAILS) {
3867 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869
Antonio Kantekf16f2832021-09-28 04:39:20 +00003870 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003872 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003874 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3875 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3876 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877 } // release lock
3878
3879 if (needWake) {
3880 mLooper->wake();
3881 }
3882}
3883
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003884/**
3885 * If one of the meta shortcuts is detected, process them here:
3886 * Meta + Backspace -> generate BACK
3887 * Meta + Enter -> generate HOME
3888 * This will potentially overwrite keyCode and metaState.
3889 */
3890void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003891 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003892 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3893 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3894 if (keyCode == AKEYCODE_DEL) {
3895 newKeyCode = AKEYCODE_BACK;
3896 } else if (keyCode == AKEYCODE_ENTER) {
3897 newKeyCode = AKEYCODE_HOME;
3898 }
3899 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003900 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003901 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003902 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003903 keyCode = newKeyCode;
3904 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3905 }
3906 } else if (action == AKEY_EVENT_ACTION_UP) {
3907 // In order to maintain a consistent stream of up and down events, check to see if the key
3908 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3909 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003910 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003911 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003912 auto replacementIt = mReplacedKeys.find(replacement);
3913 if (replacementIt != mReplacedKeys.end()) {
3914 keyCode = replacementIt->second;
3915 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003916 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3917 }
3918 }
3919}
3920
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003922 if (DEBUG_INBOUND_EVENT_DETAILS) {
3923 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3924 "policyFlags=0x%x, action=0x%x, "
3925 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3926 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3927 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3928 args->downTime);
3929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930 if (!validateKeyEvent(args->action)) {
3931 return;
3932 }
3933
3934 uint32_t policyFlags = args->policyFlags;
3935 int32_t flags = args->flags;
3936 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003937 // InputDispatcher tracks and generates key repeats on behalf of
3938 // whatever notifies it, so repeatCount should always be set to 0
3939 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3941 policyFlags |= POLICY_FLAG_VIRTUAL;
3942 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 if (policyFlags & POLICY_FLAG_FUNCTION) {
3945 metaState |= AMETA_FUNCTION_ON;
3946 }
3947
3948 policyFlags |= POLICY_FLAG_TRUSTED;
3949
Michael Wright78f24442014-08-06 15:55:28 -07003950 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003951 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003952
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003954 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003955 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3956 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957
Michael Wright2b3c3302018-03-02 17:19:13 +00003958 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003960 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3961 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003962 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964
Antonio Kantekf16f2832021-09-28 04:39:20 +00003965 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 { // acquire lock
3967 mLock.lock();
3968
3969 if (shouldSendKeyToInputFilterLocked(args)) {
3970 mLock.unlock();
3971
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003972 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3974 return; // event was consumed by the filter
3975 }
3976
3977 mLock.lock();
3978 }
3979
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003980 std::unique_ptr<KeyEntry> newEntry =
3981 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3982 args->displayId, policyFlags, args->action, flags,
3983 keyCode, args->scanCode, metaState, repeatCount,
3984 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003986 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 mLock.unlock();
3988 } // release lock
3989
3990 if (needWake) {
3991 mLooper->wake();
3992 }
3993}
3994
3995bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3996 return mInputFilterEnabled;
3997}
3998
3999void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004000 if (DEBUG_INBOUND_EVENT_DETAILS) {
4001 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4002 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004003 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004004 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4005 "yCursorPosition=%f, downTime=%" PRId64,
4006 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004007 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4008 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4009 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4010 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004011 for (uint32_t i = 0; i < args->pointerCount; i++) {
4012 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4013 "x=%f, y=%f, pressure=%f, size=%f, "
4014 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4015 "orientation=%f",
4016 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4017 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4018 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4019 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4020 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4021 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4022 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4023 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4024 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4025 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004028 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4029 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030 return;
4031 }
4032
4033 uint32_t policyFlags = args->policyFlags;
4034 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004035
4036 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004037 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004038 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4039 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004040 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042
Antonio Kantekf16f2832021-09-28 04:39:20 +00004043 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044 { // acquire lock
4045 mLock.lock();
4046
4047 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004048 ui::Transform displayTransform;
4049 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4050 displayTransform = it->second.transform;
4051 }
4052
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053 mLock.unlock();
4054
4055 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004056 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4057 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004058 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004059 displayTransform, args->xPrecision, args->yPrecision,
4060 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004061 args->downTime, args->eventTime, args->pointerCount,
4062 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063
4064 policyFlags |= POLICY_FLAG_FILTERED;
4065 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4066 return; // event was consumed by the filter
4067 }
4068
4069 mLock.lock();
4070 }
4071
4072 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004073 std::unique_ptr<MotionEntry> newEntry =
4074 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4075 args->source, args->displayId, policyFlags,
4076 args->action, args->actionButton, args->flags,
4077 args->metaState, args->buttonState,
4078 args->classification, args->edgeFlags,
4079 args->xPrecision, args->yPrecision,
4080 args->xCursorPosition, args->yCursorPosition,
4081 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004082 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004084 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4085 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4086 !mInputFilterEnabled) {
4087 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4088 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4089 }
4090
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004091 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 mLock.unlock();
4093 } // release lock
4094
4095 if (needWake) {
4096 mLooper->wake();
4097 }
4098}
4099
Chris Yef59a2f42020-10-16 12:55:26 -07004100void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004101 if (DEBUG_INBOUND_EVENT_DETAILS) {
4102 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4103 " sensorType=%s",
4104 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004105 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004106 }
Chris Yef59a2f42020-10-16 12:55:26 -07004107
Antonio Kantekf16f2832021-09-28 04:39:20 +00004108 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004109 { // acquire lock
4110 mLock.lock();
4111
4112 // Just enqueue a new sensor event.
4113 std::unique_ptr<SensorEntry> newEntry =
4114 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4115 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4116 args->sensorType, args->accuracy,
4117 args->accuracyChanged, args->values);
4118
4119 needWake = enqueueInboundEventLocked(std::move(newEntry));
4120 mLock.unlock();
4121 } // release lock
4122
4123 if (needWake) {
4124 mLooper->wake();
4125 }
4126}
4127
Chris Yefb552902021-02-03 17:18:37 -08004128void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004129 if (DEBUG_INBOUND_EVENT_DETAILS) {
4130 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4131 args->deviceId, args->isOn);
4132 }
Chris Yefb552902021-02-03 17:18:37 -08004133 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4134}
4135
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004137 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138}
4139
4140void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004141 if (DEBUG_INBOUND_EVENT_DETAILS) {
4142 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4143 "switchMask=0x%08x",
4144 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4145 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146
4147 uint32_t policyFlags = args->policyFlags;
4148 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004149 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150}
4151
4152void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004153 if (DEBUG_INBOUND_EVENT_DETAILS) {
4154 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4155 args->deviceId);
4156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157
Antonio Kantekf16f2832021-09-28 04:39:20 +00004158 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004160 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004162 std::unique_ptr<DeviceResetEntry> newEntry =
4163 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4164 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 } // release lock
4166
4167 if (needWake) {
4168 mLooper->wake();
4169 }
4170}
4171
Prabir Pradhan7e186182020-11-10 13:56:45 -08004172void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004173 if (DEBUG_INBOUND_EVENT_DETAILS) {
4174 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004175 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004176 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004177
Antonio Kantekf16f2832021-09-28 04:39:20 +00004178 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004179 { // acquire lock
4180 std::scoped_lock _l(mLock);
4181 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004182 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004183 needWake = enqueueInboundEventLocked(std::move(entry));
4184 } // release lock
4185
4186 if (needWake) {
4187 mLooper->wake();
4188 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004189}
4190
Prabir Pradhan5735a322022-04-11 17:23:34 +00004191InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4192 std::optional<int32_t> targetUid,
4193 InputEventInjectionSync syncMode,
4194 std::chrono::milliseconds timeout,
4195 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004196 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004197 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4198 "policyFlags=0x%08x",
4199 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4200 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004201 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004202 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203
Prabir Pradhan5735a322022-04-11 17:23:34 +00004204 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004206 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004207 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4208 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4209 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4210 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4211 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004212 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004213 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004214 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004215 }
4216
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004217 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004219 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004220 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4221 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004222 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004223 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004224 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004226 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004227 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4228 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4229 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004230 int32_t keyCode = incomingKey.getKeyCode();
4231 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004232 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004234 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004235 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004236 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4237 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4238 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004240 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4241 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004242 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004243
4244 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4245 android::base::Timer t;
4246 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4247 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4248 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4249 std::to_string(t.duration().count()).c_str());
4250 }
4251 }
4252
4253 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004254 std::unique_ptr<KeyEntry> injectedEntry =
4255 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004256 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004257 incomingKey.getDisplayId(), policyFlags, action,
4258 flags, keyCode, incomingKey.getScanCode(), metaState,
4259 incomingKey.getRepeatCount(),
4260 incomingKey.getDownTime());
4261 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004262 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 }
4264
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004265 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004266 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004267 const int32_t action = motionEvent.getAction();
4268 const bool isPointerEvent =
4269 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4270 // If a pointer event has no displayId specified, inject it to the default display.
4271 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4272 ? ADISPLAY_ID_DEFAULT
4273 : event->getDisplayId();
4274 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004275 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004276 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004277 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004278 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004279 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004280 }
4281
4282 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004283 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004284 android::base::Timer t;
4285 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4286 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4287 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4288 std::to_string(t.duration().count()).c_str());
4289 }
4290 }
4291
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004292 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4293 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4294 }
4295
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004296 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004297 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4298 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004299 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004300 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4301 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004302 displayId, policyFlags, action, actionButton,
4303 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004304 motionEvent.getButtonState(),
4305 motionEvent.getClassification(),
4306 motionEvent.getEdgeFlags(),
4307 motionEvent.getXPrecision(),
4308 motionEvent.getYPrecision(),
4309 motionEvent.getRawXCursorPosition(),
4310 motionEvent.getRawYCursorPosition(),
4311 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004312 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004313 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004314 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004315 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004316 sampleEventTimes += 1;
4317 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004318 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004319 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4320 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004321 displayId, policyFlags, action, actionButton,
4322 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004323 motionEvent.getButtonState(),
4324 motionEvent.getClassification(),
4325 motionEvent.getEdgeFlags(),
4326 motionEvent.getXPrecision(),
4327 motionEvent.getYPrecision(),
4328 motionEvent.getRawXCursorPosition(),
4329 motionEvent.getRawYCursorPosition(),
4330 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004331 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004332 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004333 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4334 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004335 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004336 }
4337 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004340 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004341 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004342 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 }
4344
Prabir Pradhan5735a322022-04-11 17:23:34 +00004345 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004346 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 injectionState->injectionIsAsync = true;
4348 }
4349
4350 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004351 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352
4353 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004354 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004355 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004356 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 }
4358
4359 mLock.unlock();
4360
4361 if (needWake) {
4362 mLooper->wake();
4363 }
4364
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004365 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004367 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004369 if (syncMode == InputEventInjectionSync::NONE) {
4370 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 } else {
4372 for (;;) {
4373 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004374 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 break;
4376 }
4377
4378 nsecs_t remainingTimeout = endTime - now();
4379 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004380 if (DEBUG_INJECTION) {
4381 ALOGD("injectInputEvent - Timed out waiting for injection result "
4382 "to become available.");
4383 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004384 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 break;
4386 }
4387
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004388 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 }
4390
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004391 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4392 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004394 if (DEBUG_INJECTION) {
4395 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4396 injectionState->pendingForegroundDispatches);
4397 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398 nsecs_t remainingTimeout = endTime - now();
4399 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004400 if (DEBUG_INJECTION) {
4401 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4402 "dispatches to finish.");
4403 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004404 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 break;
4406 }
4407
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004408 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409 }
4410 }
4411 }
4412
4413 injectionState->release();
4414 } // release lock
4415
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004416 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004417 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419
4420 return injectionResult;
4421}
4422
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004423std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004424 std::array<uint8_t, 32> calculatedHmac;
4425 std::unique_ptr<VerifiedInputEvent> result;
4426 switch (event.getType()) {
4427 case AINPUT_EVENT_TYPE_KEY: {
4428 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4429 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4430 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004431 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004432 break;
4433 }
4434 case AINPUT_EVENT_TYPE_MOTION: {
4435 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4436 VerifiedMotionEvent verifiedMotionEvent =
4437 verifiedMotionEventFromMotionEvent(motionEvent);
4438 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004439 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004440 break;
4441 }
4442 default: {
4443 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4444 return nullptr;
4445 }
4446 }
4447 if (calculatedHmac == INVALID_HMAC) {
4448 return nullptr;
4449 }
4450 if (calculatedHmac != event.getHmac()) {
4451 return nullptr;
4452 }
4453 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004454}
4455
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004456void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004457 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004458 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004460 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004461 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004464 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465 // Log the outcome since the injector did not wait for the injection result.
4466 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004467 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004468 ALOGV("Asynchronous input event injection succeeded.");
4469 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004470 case InputEventInjectionResult::TARGET_MISMATCH:
4471 ALOGV("Asynchronous input event injection target mismatch.");
4472 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004473 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004474 ALOGW("Asynchronous input event injection failed.");
4475 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004476 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004477 ALOGW("Asynchronous input event injection timed out.");
4478 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004479 case InputEventInjectionResult::PENDING:
4480 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4481 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 }
4483 }
4484
4485 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004486 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487 }
4488}
4489
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004490void InputDispatcher::transformMotionEntryForInjectionLocked(
4491 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004492 // Input injection works in the logical display coordinate space, but the input pipeline works
4493 // display space, so we need to transform the injected events accordingly.
4494 const auto it = mDisplayInfos.find(entry.displayId);
4495 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004496 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004497
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004498 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4499 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4500 const vec2 cursor =
4501 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4502 {entry.xCursorPosition, entry.yCursorPosition});
4503 entry.xCursorPosition = cursor.x;
4504 entry.yCursorPosition = cursor.y;
4505 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004506 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004507 entry.pointerCoords[i] =
4508 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4509 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004510 }
4511}
4512
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004513void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4514 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515 if (injectionState) {
4516 injectionState->pendingForegroundDispatches += 1;
4517 }
4518}
4519
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004520void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4521 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522 if (injectionState) {
4523 injectionState->pendingForegroundDispatches -= 1;
4524
4525 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004526 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527 }
4528 }
4529}
4530
chaviw98318de2021-05-19 16:45:23 -05004531const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004532 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004533 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004534 auto it = mWindowHandlesByDisplay.find(displayId);
4535 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004536}
4537
chaviw98318de2021-05-19 16:45:23 -05004538sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004539 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004540 if (windowHandleToken == nullptr) {
4541 return nullptr;
4542 }
4543
Arthur Hungb92218b2018-08-14 12:00:21 +08004544 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004545 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4546 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004547 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004548 return windowHandle;
4549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004550 }
4551 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004552 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553}
4554
chaviw98318de2021-05-19 16:45:23 -05004555sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4556 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004557 if (windowHandleToken == nullptr) {
4558 return nullptr;
4559 }
4560
chaviw98318de2021-05-19 16:45:23 -05004561 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004562 if (windowHandle->getToken() == windowHandleToken) {
4563 return windowHandle;
4564 }
4565 }
4566 return nullptr;
4567}
4568
chaviw98318de2021-05-19 16:45:23 -05004569sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4570 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004571 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004572 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4573 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004574 if (handle->getId() == windowHandle->getId() &&
4575 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004576 if (windowHandle->getInfo()->displayId != it.first) {
4577 ALOGE("Found window %s in display %" PRId32
4578 ", but it should belong to display %" PRId32,
4579 windowHandle->getName().c_str(), it.first,
4580 windowHandle->getInfo()->displayId);
4581 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004582 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584 }
4585 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004586 return nullptr;
4587}
4588
chaviw98318de2021-05-19 16:45:23 -05004589sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004590 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4591 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592}
4593
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004594bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4595 const MotionEntry& motionEntry) const {
4596 const WindowInfo& info = *window->getInfo();
4597
4598 // Skip spy window targets that are not valid for targeted injection.
4599 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004600 return false;
4601 }
4602
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004603 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4604 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4605 return false;
4606 }
4607
4608 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4609 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4610 window->getName().c_str());
4611 return false;
4612 }
4613
4614 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004615 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004616 ALOGW("Not sending touch to %s because there's no corresponding connection",
4617 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004618 return false;
4619 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004620
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004621 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004622 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004623 return false;
4624 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004625
4626 // Drop events that can't be trusted due to occlusion
4627 const auto [x, y] = resolveTouchedPosition(motionEntry);
4628 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4629 if (!isTouchTrustedLocked(occlusionInfo)) {
4630 if (DEBUG_TOUCH_OCCLUSION) {
4631 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4632 for (const auto& log : occlusionInfo.debugInfo) {
4633 ALOGD("%s", log.c_str());
4634 }
4635 }
4636 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4637 occlusionInfo.obscuringUid);
4638 return false;
4639 }
4640
4641 // Drop touch events if requested by input feature
4642 if (shouldDropInput(motionEntry, window)) {
4643 return false;
4644 }
4645
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004646 return true;
4647}
4648
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004649std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4650 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004651 auto connectionIt = mConnectionsByToken.find(token);
4652 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004653 return nullptr;
4654 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004655 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004656}
4657
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004658void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004659 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4660 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004661 // Remove all handles on a display if there are no windows left.
4662 mWindowHandlesByDisplay.erase(displayId);
4663 return;
4664 }
4665
4666 // Since we compare the pointer of input window handles across window updates, we need
4667 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004668 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4669 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4670 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004671 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004672 }
4673
chaviw98318de2021-05-19 16:45:23 -05004674 std::vector<sp<WindowInfoHandle>> newHandles;
4675 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004676 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004677 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004678 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004679 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004680 const bool canReceiveInput =
4681 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4682 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004683 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004684 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004685 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004686 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004687 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004688 }
4689
4690 if (info->displayId != displayId) {
4691 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4692 handle->getName().c_str(), displayId, info->displayId);
4693 continue;
4694 }
4695
Robert Carredd13602020-04-13 17:24:34 -07004696 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4697 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004698 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004699 oldHandle->updateFrom(handle);
4700 newHandles.push_back(oldHandle);
4701 } else {
4702 newHandles.push_back(handle);
4703 }
4704 }
4705
4706 // Insert or replace
4707 mWindowHandlesByDisplay[displayId] = newHandles;
4708}
4709
Arthur Hung72d8dc32020-03-28 00:48:39 +00004710void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004711 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004712 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004713 { // acquire lock
4714 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004715 for (const auto& [displayId, handles] : handlesPerDisplay) {
4716 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004717 }
4718 }
4719 // Wake up poll loop since it may need to make new input dispatching choices.
4720 mLooper->wake();
4721}
4722
Arthur Hungb92218b2018-08-14 12:00:21 +08004723/**
4724 * Called from InputManagerService, update window handle list by displayId that can receive input.
4725 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4726 * If set an empty list, remove all handles from the specific display.
4727 * For focused handle, check if need to change and send a cancel event to previous one.
4728 * For removed handle, check if need to send a cancel event if already in touch.
4729 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004730void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004731 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004732 if (DEBUG_FOCUS) {
4733 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004734 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004735 windowList += iwh->getName() + " ";
4736 }
4737 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4738 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739
Prabir Pradhand65552b2021-10-07 11:23:50 -07004740 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004741 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004742 const WindowInfo& info = *window->getInfo();
4743
4744 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004745 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004746 if (noInputWindow && window->getToken() != nullptr) {
4747 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4748 window->getName().c_str());
4749 window->releaseChannel();
4750 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004751
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004752 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004753 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4754 !info.inputConfig.test(
4755 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004756 "%s has feature SPY, but is not a trusted overlay.",
4757 window->getName().c_str());
4758
Prabir Pradhand65552b2021-10-07 11:23:50 -07004759 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004760 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4761 !info.inputConfig.test(
4762 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004763 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4764 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004765 }
4766
Arthur Hung72d8dc32020-03-28 00:48:39 +00004767 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004768 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004770 // Save the old windows' orientation by ID before it gets updated.
4771 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004772 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004773 oldWindowOrientations.emplace(handle->getId(),
4774 handle->getInfo()->transform.getOrientation());
4775 }
4776
chaviw98318de2021-05-19 16:45:23 -05004777 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004778
chaviw98318de2021-05-19 16:45:23 -05004779 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004780 if (mLastHoverWindowHandle &&
4781 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4782 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004783 mLastHoverWindowHandle = nullptr;
4784 }
4785
Vishnu Nairc519ff72021-01-21 08:23:08 -08004786 std::optional<FocusResolver::FocusChanges> changes =
4787 mFocusResolver.setInputWindows(displayId, windowHandles);
4788 if (changes) {
4789 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004790 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004792 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4793 mTouchStatesByDisplay.find(displayId);
4794 if (stateIt != mTouchStatesByDisplay.end()) {
4795 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004796 for (size_t i = 0; i < state.windows.size();) {
4797 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004798 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004799 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004800 ALOGD("Touched window was removed: %s in display %" PRId32,
4801 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004802 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004803 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004804 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4805 if (touchedInputChannel != nullptr) {
4806 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4807 "touched window was removed");
4808 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004809 // Since we are about to drop the touch, cancel the events for the wallpaper as
4810 // well.
4811 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004812 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4813 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004814 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4815 if (wallpaper != nullptr) {
4816 sp<Connection> wallpaperConnection =
4817 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004818 if (wallpaperConnection != nullptr) {
4819 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4820 options);
4821 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004822 }
4823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004825 state.windows.erase(state.windows.begin() + i);
4826 } else {
4827 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828 }
4829 }
arthurhungb89ccb02020-12-30 16:19:01 +08004830
arthurhung6d4bed92021-03-17 11:59:33 +08004831 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004832 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004833 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004834 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004835 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004836 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4837 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004838 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004839 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004840 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004841
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004842 // Determine if the orientation of any of the input windows have changed, and cancel all
4843 // pointer events if necessary.
4844 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4845 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4846 if (newWindowHandle != nullptr &&
4847 newWindowHandle->getInfo()->transform.getOrientation() !=
4848 oldWindowOrientations[oldWindowHandle->getId()]) {
4849 std::shared_ptr<InputChannel> inputChannel =
4850 getInputChannelLocked(newWindowHandle->getToken());
4851 if (inputChannel != nullptr) {
4852 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4853 "touched window's orientation changed");
4854 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004855 }
4856 }
4857 }
4858
Arthur Hung72d8dc32020-03-28 00:48:39 +00004859 // Release information for windows that are no longer present.
4860 // This ensures that unused input channels are released promptly.
4861 // Otherwise, they might stick around until the window handle is destroyed
4862 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004863 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004864 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004865 if (DEBUG_FOCUS) {
4866 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004867 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004868 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004869 }
chaviw291d88a2019-02-14 10:33:58 -08004870 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871}
4872
4873void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004874 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004875 if (DEBUG_FOCUS) {
4876 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4877 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4878 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004879 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004880 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004881 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 } // release lock
4883
4884 // Wake up poll loop since it may need to make new input dispatching choices.
4885 mLooper->wake();
4886}
4887
Vishnu Nair599f1412021-06-21 10:39:58 -07004888void InputDispatcher::setFocusedApplicationLocked(
4889 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4890 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4891 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4892
4893 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4894 return; // This application is already focused. No need to wake up or change anything.
4895 }
4896
4897 // Set the new application handle.
4898 if (inputApplicationHandle != nullptr) {
4899 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4900 } else {
4901 mFocusedApplicationHandlesByDisplay.erase(displayId);
4902 }
4903
4904 // No matter what the old focused application was, stop waiting on it because it is
4905 // no longer focused.
4906 resetNoFocusedWindowTimeoutLocked();
4907}
4908
Tiger Huang721e26f2018-07-24 22:26:19 +08004909/**
4910 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4911 * the display not specified.
4912 *
4913 * We track any unreleased events for each window. If a window loses the ability to receive the
4914 * released event, we will send a cancel event to it. So when the focused display is changed, we
4915 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4916 * display. The display-specified events won't be affected.
4917 */
4918void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004919 if (DEBUG_FOCUS) {
4920 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4921 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004922 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004923 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004924
4925 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004926 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004927 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004928 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004929 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004930 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004931 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004932 CancelationOptions
4933 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4934 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004935 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004936 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4937 }
4938 }
4939 mFocusedDisplayId = displayId;
4940
Chris Ye3c2d6f52020-08-09 10:39:48 -07004941 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004942 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004943 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004944
Vishnu Nairad321cd2020-08-20 16:40:21 -07004945 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004946 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004947 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004948 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004949 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004950 }
4951 }
4952 }
4953
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004954 if (DEBUG_FOCUS) {
4955 logDispatchStateLocked();
4956 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004957 } // release lock
4958
4959 // Wake up poll loop since it may need to make new input dispatching choices.
4960 mLooper->wake();
4961}
4962
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004964 if (DEBUG_FOCUS) {
4965 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4966 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967
4968 bool changed;
4969 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004970 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971
4972 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4973 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004974 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004975 }
4976
4977 if (mDispatchEnabled && !enabled) {
4978 resetAndDropEverythingLocked("dispatcher is being disabled");
4979 }
4980
4981 mDispatchEnabled = enabled;
4982 mDispatchFrozen = frozen;
4983 changed = true;
4984 } else {
4985 changed = false;
4986 }
4987
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004988 if (DEBUG_FOCUS) {
4989 logDispatchStateLocked();
4990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991 } // release lock
4992
4993 if (changed) {
4994 // Wake up poll loop since it may need to make new input dispatching choices.
4995 mLooper->wake();
4996 }
4997}
4998
4999void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005000 if (DEBUG_FOCUS) {
5001 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003
5004 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005005 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006
5007 if (mInputFilterEnabled == enabled) {
5008 return;
5009 }
5010
5011 mInputFilterEnabled = enabled;
5012 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5013 } // release lock
5014
5015 // Wake up poll loop since there might be work to do to drop everything.
5016 mLooper->wake();
5017}
5018
Antonio Kanteka042c022022-07-06 16:51:07 -07005019bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5020 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005021 bool needWake = false;
5022 {
5023 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005024 ALOGD_IF(DEBUG_TOUCH_MODE,
5025 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5026 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5027 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5028 mTouchModePerDisplay.count(displayId) == 0
5029 ? "not set"
5030 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5031
Antonio Kantek15beb512022-06-13 22:35:41 +00005032 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5033 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005034 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005035 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005036 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005037 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5038 !recentWindowsAreOwnedByLocked(pid, uid)) {
5039 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5040 "window nor none of the previously interacted window",
5041 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005042 return false;
5043 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005044 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005045 mTouchModePerDisplay[displayId] = inTouchMode;
5046 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5047 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005048 needWake = enqueueInboundEventLocked(std::move(entry));
5049 } // release lock
5050
5051 if (needWake) {
5052 mLooper->wake();
5053 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005054 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005055}
5056
Antonio Kantek48710e42022-03-24 14:19:30 -07005057bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5058 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5059 if (focusedToken == nullptr) {
5060 return false;
5061 }
5062 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5063 return isWindowOwnedBy(windowHandle, pid, uid);
5064}
5065
5066bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5067 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5068 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5069 const sp<WindowInfoHandle> windowHandle =
5070 getWindowHandleLocked(connectionToken);
5071 return isWindowOwnedBy(windowHandle, pid, uid);
5072 }) != mInteractionConnectionTokens.end();
5073}
5074
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005075void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5076 if (opacity < 0 || opacity > 1) {
5077 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5078 return;
5079 }
5080
5081 std::scoped_lock lock(mLock);
5082 mMaximumObscuringOpacityForTouch = opacity;
5083}
5084
Arthur Hungabbb9d82021-09-01 14:52:30 +00005085std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5086 const sp<IBinder>& token) {
5087 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5088 for (TouchedWindow& w : state.windows) {
5089 if (w.windowHandle->getToken() == token) {
5090 return std::make_pair(&state, &w);
5091 }
5092 }
5093 }
5094 return std::make_pair(nullptr, nullptr);
5095}
5096
arthurhungb89ccb02020-12-30 16:19:01 +08005097bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5098 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005099 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005100 if (DEBUG_FOCUS) {
5101 ALOGD("Trivial transfer to same window.");
5102 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005103 return true;
5104 }
5105
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005107 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005108
Arthur Hungabbb9d82021-09-01 14:52:30 +00005109 // Find the target touch state and touched window by fromToken.
5110 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5111 if (state == nullptr || touchedWindow == nullptr) {
5112 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005113 return false;
5114 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005115
5116 const int32_t displayId = state->displayId;
5117 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5118 if (toWindowHandle == nullptr) {
5119 ALOGW("Cannot transfer focus because to window not found.");
5120 return false;
5121 }
5122
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005123 if (DEBUG_FOCUS) {
5124 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005125 touchedWindow->windowHandle->getName().c_str(),
5126 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127 }
5128
Arthur Hungabbb9d82021-09-01 14:52:30 +00005129 // Erase old window.
5130 int32_t oldTargetFlags = touchedWindow->targetFlags;
5131 BitSet32 pointerIds = touchedWindow->pointerIds;
5132 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005133
Arthur Hungabbb9d82021-09-01 14:52:30 +00005134 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005135 nsecs_t downTimeInTarget = now();
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005136 int32_t newTargetFlags =
5137 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5138 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5139 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5140 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005141 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142
Arthur Hungabbb9d82021-09-01 14:52:30 +00005143 // Store the dragging window.
5144 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005145 if (pointerIds.count() != 1) {
5146 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5147 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005148 return false;
5149 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005150 // Track the pointer id for drag window and generate the drag state.
5151 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005152 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 }
5154
Arthur Hungabbb9d82021-09-01 14:52:30 +00005155 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005156 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5157 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005158 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005159 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005160 CancelationOptions
5161 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5162 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005164 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165 }
5166
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005167 if (DEBUG_FOCUS) {
5168 logDispatchStateLocked();
5169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 } // release lock
5171
5172 // Wake up poll loop since it may need to make new input dispatching choices.
5173 mLooper->wake();
5174 return true;
5175}
5176
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005177/**
5178 * Get the touched foreground window on the given display.
5179 * Return null if there are no windows touched on that display, or if more than one foreground
5180 * window is being touched.
5181 */
5182sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5183 auto stateIt = mTouchStatesByDisplay.find(displayId);
5184 if (stateIt == mTouchStatesByDisplay.end()) {
5185 ALOGI("No touch state on display %" PRId32, displayId);
5186 return nullptr;
5187 }
5188
5189 const TouchState& state = stateIt->second;
5190 sp<WindowInfoHandle> touchedForegroundWindow;
5191 // If multiple foreground windows are touched, return nullptr
5192 for (const TouchedWindow& window : state.windows) {
5193 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5194 if (touchedForegroundWindow != nullptr) {
5195 ALOGI("Two or more foreground windows: %s and %s",
5196 touchedForegroundWindow->getName().c_str(),
5197 window.windowHandle->getName().c_str());
5198 return nullptr;
5199 }
5200 touchedForegroundWindow = window.windowHandle;
5201 }
5202 }
5203 return touchedForegroundWindow;
5204}
5205
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005206// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005207bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005208 sp<IBinder> fromToken;
5209 { // acquire lock
5210 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005211 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005212 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005213 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5214 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005215 return false;
5216 }
5217
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005218 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5219 if (from == nullptr) {
5220 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5221 return false;
5222 }
5223
5224 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005225 } // release lock
5226
5227 return transferTouchFocus(fromToken, destChannelToken);
5228}
5229
Michael Wrightd02c5b62014-02-10 15:10:22 -08005230void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005231 if (DEBUG_FOCUS) {
5232 ALOGD("Resetting and dropping all events (%s).", reason);
5233 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005234
5235 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5236 synthesizeCancelationEventsForAllConnectionsLocked(options);
5237
5238 resetKeyRepeatLocked();
5239 releasePendingEventLocked();
5240 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005241 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005242
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005243 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005244 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005245 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005246 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247}
5248
5249void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005250 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251 dumpDispatchStateLocked(dump);
5252
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005253 std::istringstream stream(dump);
5254 std::string line;
5255
5256 while (std::getline(stream, line, '\n')) {
5257 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258 }
5259}
5260
Prabir Pradhan99987712020-11-10 18:43:05 -08005261std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5262 std::string dump;
5263
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005264 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5265 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005266
5267 std::string windowName = "None";
5268 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005269 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005270 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5271 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5272 : "token has capture without window";
5273 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005274 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005275
5276 return dump;
5277}
5278
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005279void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005280 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5281 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5282 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005283 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284
Tiger Huang721e26f2018-07-24 22:26:19 +08005285 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5286 dump += StringPrintf(INDENT "FocusedApplications:\n");
5287 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5288 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005289 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005290 const std::chrono::duration timeout =
5291 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005292 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005293 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005294 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005297 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005299
Vishnu Nairc519ff72021-01-21 08:23:08 -08005300 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005301 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005303 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005304 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005305 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5306 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005307 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005308 state.displayId, toString(state.down), toString(state.split),
5309 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005310 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005311 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005312 for (size_t i = 0; i < state.windows.size(); i++) {
5313 const TouchedWindow& touchedWindow = state.windows[i];
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005314 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, "
5315 "targetFlags=0x%x, firstDownTimeInTarget=%" PRId64
5316 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005317 i, touchedWindow.windowHandle->getName().c_str(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005318 touchedWindow.pointerIds.value, touchedWindow.targetFlags,
5319 ns2ms(touchedWindow.firstDownTimeInTarget.value_or(0)));
Jeff Brownf086ddb2014-02-11 14:28:48 -08005320 }
5321 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005322 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 }
5325 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005326 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327 }
5328
arthurhung6d4bed92021-03-17 11:59:33 +08005329 if (mDragState) {
5330 dump += StringPrintf(INDENT "DragState:\n");
5331 mDragState->dump(dump, INDENT2);
5332 }
5333
Arthur Hungb92218b2018-08-14 12:00:21 +08005334 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005335 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5336 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5337 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5338 const auto& displayInfo = it->second;
5339 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5340 displayInfo.logicalHeight);
5341 displayInfo.transform.dump(dump, "transform", INDENT4);
5342 } else {
5343 dump += INDENT2 "No DisplayInfo found!\n";
5344 }
5345
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005346 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005347 dump += INDENT2 "Windows:\n";
5348 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005349 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5350 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005352 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005353 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005354 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005355 "applicationInfo.name=%s, "
5356 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005357 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005358 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005359 windowInfo->displayId,
5360 windowInfo->inputConfig.string().c_str(),
5361 windowInfo->alpha, windowInfo->frameLeft,
5362 windowInfo->frameTop, windowInfo->frameRight,
5363 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005364 windowInfo->applicationInfo.name.c_str(),
5365 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005366 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005367 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005368 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005369 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005370 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005371 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005372 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005373 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005374 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005375 }
5376 } else {
5377 dump += INDENT2 "Windows: <none>\n";
5378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005379 }
5380 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005381 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382 }
5383
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005384 if (!mGlobalMonitorsByDisplay.empty()) {
5385 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5386 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005387 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005390 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391 }
5392
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005393 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005394
5395 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005396 if (!mRecentQueue.empty()) {
5397 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005398 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005399 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005400 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005401 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402 }
5403 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005404 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405 }
5406
5407 // Dump event currently being dispatched.
5408 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005409 dump += INDENT "PendingEvent:\n";
5410 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005411 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005412 dump += StringPrintf(", age=%" PRId64 "ms\n",
5413 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005415 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 }
5417
5418 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005419 if (!mInboundQueue.empty()) {
5420 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005421 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005422 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005423 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005424 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425 }
5426 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005427 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 }
5429
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005430 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005431 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005432 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5433 const KeyReplacement& replacement = pair.first;
5434 int32_t newKeyCode = pair.second;
5435 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005436 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005437 }
5438 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005439 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005440 }
5441
Prabir Pradhancef936d2021-07-21 16:17:52 +00005442 if (!mCommandQueue.empty()) {
5443 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5444 } else {
5445 dump += INDENT "CommandQueue: <empty>\n";
5446 }
5447
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005448 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005449 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005450 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005451 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005452 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005453 connection->inputChannel->getFd().get(),
5454 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005455 connection->getWindowName().c_str(),
5456 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005457 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005459 if (!connection->outboundQueue.empty()) {
5460 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5461 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005462 dump += dumpQueue(connection->outboundQueue, currentTime);
5463
Michael Wrightd02c5b62014-02-10 15:10:22 -08005464 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005465 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466 }
5467
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005468 if (!connection->waitQueue.empty()) {
5469 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5470 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005471 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005472 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005473 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474 }
5475 }
5476 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005477 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 }
5479
5480 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005481 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5482 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005483 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005484 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 }
5486
Antonio Kantek15beb512022-06-13 22:35:41 +00005487 if (!mTouchModePerDisplay.empty()) {
5488 dump += INDENT "TouchModePerDisplay:\n";
5489 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5490 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5491 std::to_string(touchMode).c_str());
5492 }
5493 } else {
5494 dump += INDENT "TouchModePerDisplay: <none>\n";
5495 }
5496
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005497 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005498 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5499 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5500 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005501 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005502 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005503}
5504
Michael Wright3dd60e22019-03-27 22:06:44 +00005505void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5506 const size_t numMonitors = monitors.size();
5507 for (size_t i = 0; i < numMonitors; i++) {
5508 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005509 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005510 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5511 dump += "\n";
5512 }
5513}
5514
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005515class LooperEventCallback : public LooperCallback {
5516public:
5517 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5518 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5519
5520private:
5521 std::function<int(int events)> mCallback;
5522};
5523
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005524Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005525 if (DEBUG_CHANNEL_CREATION) {
5526 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5527 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005529 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005530 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005531 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005532
5533 if (result) {
5534 return base::Error(result) << "Failed to open input channel pair with name " << name;
5535 }
5536
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005538 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005539 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005540 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005541 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005542 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005544 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5545 ALOGE("Created a new connection, but the token %p is already known", token.get());
5546 }
5547 mConnectionsByToken.emplace(token, connection);
5548
5549 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5550 this, std::placeholders::_1, token);
5551
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005552 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5553 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005554 } // release lock
5555
5556 // Wake the looper because some connections have changed.
5557 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005558 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559}
5560
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005561Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005562 const std::string& name,
5563 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005564 std::shared_ptr<InputChannel> serverChannel;
5565 std::unique_ptr<InputChannel> clientChannel;
5566 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5567 if (result) {
5568 return base::Error(result) << "Failed to open input channel pair with name " << name;
5569 }
5570
Michael Wright3dd60e22019-03-27 22:06:44 +00005571 { // acquire lock
5572 std::scoped_lock _l(mLock);
5573
5574 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005575 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5576 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005577 }
5578
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005579 sp<Connection> connection =
5580 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005581 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005582 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005583
5584 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5585 ALOGE("Created a new connection, but the token %p is already known", token.get());
5586 }
5587 mConnectionsByToken.emplace(token, connection);
5588 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5589 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005590
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005591 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005592
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005593 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5594 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005595 }
Garfield Tan15601662020-09-22 15:32:38 -07005596
Michael Wright3dd60e22019-03-27 22:06:44 +00005597 // Wake the looper because some connections have changed.
5598 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005599 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005600}
5601
Garfield Tan15601662020-09-22 15:32:38 -07005602status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005603 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005604 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605
Garfield Tan15601662020-09-22 15:32:38 -07005606 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607 if (status) {
5608 return status;
5609 }
5610 } // release lock
5611
5612 // Wake the poll loop because removing the connection may have changed the current
5613 // synchronization state.
5614 mLooper->wake();
5615 return OK;
5616}
5617
Garfield Tan15601662020-09-22 15:32:38 -07005618status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5619 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005620 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005621 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005622 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623 return BAD_VALUE;
5624 }
5625
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005626 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005627
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005629 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630 }
5631
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005632 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005633
5634 nsecs_t currentTime = now();
5635 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5636
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005637 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638 return OK;
5639}
5640
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005641void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005642 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5643 auto& [displayId, monitors] = *it;
5644 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5645 return monitor.inputChannel->getConnectionToken() == connectionToken;
5646 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005647
Michael Wright3dd60e22019-03-27 22:06:44 +00005648 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005649 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005650 } else {
5651 ++it;
5652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005653 }
5654}
5655
Michael Wright3dd60e22019-03-27 22:06:44 +00005656status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005657 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005658 return pilferPointersLocked(token);
5659}
Michael Wright3dd60e22019-03-27 22:06:44 +00005660
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005661status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005662 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5663 if (!requestingChannel) {
5664 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5665 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005666 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005667
5668 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5669 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5670 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5671 " Ignoring.");
5672 return BAD_VALUE;
5673 }
5674
5675 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005676 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005677 // Send cancel events to all the input channels we're stealing from.
5678 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5679 "input channel stole pointer stream");
5680 options.deviceId = state.deviceId;
5681 options.displayId = state.displayId;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005682 if (state.split) {
5683 // If split pointers then selectively cancel pointers otherwise cancel all pointers
5684 options.pointerIds = window.pointerIds;
5685 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005686 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005687 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005688 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005689 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005690 if (channel != nullptr && channel->getConnectionToken() != token) {
5691 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5692 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5693 canceledWindows += channel->getName();
5694 }
5695 }
5696 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5697 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5698 canceledWindows.c_str());
5699
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005700 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005701 // This only blocks relevant pointers to be sent to other windows
5702 window.isPilferingPointers = true;
5703
5704 if (state.split) {
5705 state.cancelPointersForWindowsExcept(window.pointerIds, token);
5706 } else {
5707 state.filterWindowsExcept(token);
5708 }
Michael Wright3dd60e22019-03-27 22:06:44 +00005709 return OK;
5710}
5711
Prabir Pradhan99987712020-11-10 18:43:05 -08005712void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5713 { // acquire lock
5714 std::scoped_lock _l(mLock);
5715 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005716 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005717 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5718 windowHandle != nullptr ? windowHandle->getName().c_str()
5719 : "token without window");
5720 }
5721
Vishnu Nairc519ff72021-01-21 08:23:08 -08005722 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005723 if (focusedToken != windowToken) {
5724 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5725 enabled ? "enable" : "disable");
5726 return;
5727 }
5728
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005729 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005730 ALOGW("Ignoring request to %s Pointer Capture: "
5731 "window has %s requested pointer capture.",
5732 enabled ? "enable" : "disable", enabled ? "already" : "not");
5733 return;
5734 }
5735
Christine Franksb768bb42021-11-29 12:11:31 -08005736 if (enabled) {
5737 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5738 mIneligibleDisplaysForPointerCapture.end(),
5739 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5740 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5741 return;
5742 }
5743 }
5744
Prabir Pradhan99987712020-11-10 18:43:05 -08005745 setPointerCaptureLocked(enabled);
5746 } // release lock
5747
5748 // Wake the thread to process command entries.
5749 mLooper->wake();
5750}
5751
Christine Franksb768bb42021-11-29 12:11:31 -08005752void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5753 { // acquire lock
5754 std::scoped_lock _l(mLock);
5755 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5756 if (!isEligible) {
5757 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5758 }
5759 } // release lock
5760}
5761
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005762std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5763 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005764 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005765 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005766 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005767 }
5768 }
5769 }
5770 return std::nullopt;
5771}
5772
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005773sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005774 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005775 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005776 }
5777
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005778 for (const auto& [token, connection] : mConnectionsByToken) {
5779 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005780 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781 }
5782 }
Robert Carr4e670e52018-08-15 13:26:12 -07005783
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005784 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005785}
5786
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005787std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5788 sp<Connection> connection = getConnectionLocked(connectionToken);
5789 if (connection == nullptr) {
5790 return "<nullptr>";
5791 }
5792 return connection->getInputChannelName();
5793}
5794
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005795void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005796 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005797 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005798}
5799
Prabir Pradhancef936d2021-07-21 16:17:52 +00005800void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5801 const sp<Connection>& connection, uint32_t seq,
5802 bool handled, nsecs_t consumeTime) {
5803 // Handle post-event policy actions.
5804 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5805 if (dispatchEntryIt == connection->waitQueue.end()) {
5806 return;
5807 }
5808 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5809 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5810 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5811 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5812 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5813 }
5814 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5815 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5816 connection->inputChannel->getConnectionToken(),
5817 dispatchEntry->deliveryTime, consumeTime, finishTime);
5818 }
5819
5820 bool restartEvent;
5821 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5822 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5823 restartEvent =
5824 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5825 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5826 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5827 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5828 handled);
5829 } else {
5830 restartEvent = false;
5831 }
5832
5833 // Dequeue the event and start the next cycle.
5834 // Because the lock might have been released, it is possible that the
5835 // contents of the wait queue to have been drained, so we need to double-check
5836 // a few things.
5837 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5838 if (dispatchEntryIt != connection->waitQueue.end()) {
5839 dispatchEntry = *dispatchEntryIt;
5840 connection->waitQueue.erase(dispatchEntryIt);
5841 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5842 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5843 if (!connection->responsive) {
5844 connection->responsive = isConnectionResponsive(*connection);
5845 if (connection->responsive) {
5846 // The connection was unresponsive, and now it's responsive.
5847 processConnectionResponsiveLocked(*connection);
5848 }
5849 }
5850 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005851 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005852 connection->outboundQueue.push_front(dispatchEntry);
5853 traceOutboundQueueLength(*connection);
5854 } else {
5855 releaseDispatchEntry(dispatchEntry);
5856 }
5857 }
5858
5859 // Start the next dispatch cycle for this connection.
5860 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005861}
5862
Prabir Pradhancef936d2021-07-21 16:17:52 +00005863void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5864 const sp<IBinder>& newToken) {
5865 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5866 scoped_unlock unlock(mLock);
5867 mPolicy->notifyFocusChanged(oldToken, newToken);
5868 };
5869 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005870}
5871
Prabir Pradhancef936d2021-07-21 16:17:52 +00005872void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5873 auto command = [this, token, x, y]() REQUIRES(mLock) {
5874 scoped_unlock unlock(mLock);
5875 mPolicy->notifyDropWindow(token, x, y);
5876 };
5877 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005878}
5879
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005880void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5881 if (connection == nullptr) {
5882 LOG_ALWAYS_FATAL("Caller must check for nullness");
5883 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005884 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5885 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005886 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005887 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005888 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005889 return;
5890 }
5891 /**
5892 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5893 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5894 * has changed. This could cause newer entries to time out before the already dispatched
5895 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5896 * processes the events linearly. So providing information about the oldest entry seems to be
5897 * most useful.
5898 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005899 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005900 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5901 std::string reason =
5902 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005903 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005904 ns2ms(currentWait),
5905 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005906 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005907 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005908
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005909 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5910
5911 // Stop waking up for events on this connection, it is already unresponsive
5912 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005913}
5914
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005915void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5916 std::string reason =
5917 StringPrintf("%s does not have a focused window", application->getName().c_str());
5918 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005919
Prabir Pradhancef936d2021-07-21 16:17:52 +00005920 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5921 scoped_unlock unlock(mLock);
5922 mPolicy->notifyNoFocusedWindowAnr(application);
5923 };
5924 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005925}
5926
chaviw98318de2021-05-19 16:45:23 -05005927void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005928 const std::string& reason) {
5929 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5930 updateLastAnrStateLocked(windowLabel, reason);
5931}
5932
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005933void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5934 const std::string& reason) {
5935 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005936 updateLastAnrStateLocked(windowLabel, reason);
5937}
5938
5939void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5940 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005942 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943 struct tm tm;
5944 localtime_r(&t, &tm);
5945 char timestr[64];
5946 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005947 mLastAnrState.clear();
5948 mLastAnrState += INDENT "ANR:\n";
5949 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005950 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5951 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005952 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005953}
5954
Prabir Pradhancef936d2021-07-21 16:17:52 +00005955void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5956 KeyEntry& entry) {
5957 const KeyEvent event = createKeyEvent(entry);
5958 nsecs_t delay = 0;
5959 { // release lock
5960 scoped_unlock unlock(mLock);
5961 android::base::Timer t;
5962 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5963 entry.policyFlags);
5964 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5965 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5966 std::to_string(t.duration().count()).c_str());
5967 }
5968 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005969
5970 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005971 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005972 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005973 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005974 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005975 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5976 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005978}
5979
Prabir Pradhancef936d2021-07-21 16:17:52 +00005980void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005981 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005982 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005983 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005984 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005985 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005986 };
5987 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005988}
5989
Prabir Pradhanedd96402022-02-15 01:46:16 -08005990void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5991 std::optional<int32_t> pid) {
5992 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005993 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005994 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005995 };
5996 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005997}
5998
5999/**
6000 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6001 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6002 * command entry to the command queue.
6003 */
6004void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6005 std::string reason) {
6006 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006007 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006008 if (connection.monitor) {
6009 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6010 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006011 pid = findMonitorPidByTokenLocked(connectionToken);
6012 } else {
6013 // The connection is a window
6014 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6015 reason.c_str());
6016 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6017 if (handle != nullptr) {
6018 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006019 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006020 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006021 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006022}
6023
6024/**
6025 * Tell the policy that a connection has become responsive so that it can stop ANR.
6026 */
6027void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6028 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006029 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006030 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006031 pid = findMonitorPidByTokenLocked(connectionToken);
6032 } else {
6033 // The connection is a window
6034 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6035 if (handle != nullptr) {
6036 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006037 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006038 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006039 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006040}
6041
Prabir Pradhancef936d2021-07-21 16:17:52 +00006042bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006043 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006044 KeyEntry& keyEntry, bool handled) {
6045 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006046 if (!handled) {
6047 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006048 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006049 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006050 return false;
6051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006052
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006053 // Get the fallback key state.
6054 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006055 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006056 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006057 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006058 connection->inputState.removeFallbackKey(originalKeyCode);
6059 }
6060
6061 if (handled || !dispatchEntry->hasForegroundTarget()) {
6062 // If the application handles the original key for which we previously
6063 // generated a fallback or if the window is not a foreground window,
6064 // then cancel the associated fallback key, if any.
6065 if (fallbackKeyCode != -1) {
6066 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006067 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6068 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6069 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6070 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6071 keyEntry.policyFlags);
6072 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006073 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006074 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006075
6076 mLock.unlock();
6077
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006078 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006079 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006080
6081 mLock.lock();
6082
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006083 // Cancel the fallback key.
6084 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006085 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006086 "application handled the original non-fallback key "
6087 "or is no longer a foreground target, "
6088 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006089 options.keyCode = fallbackKeyCode;
6090 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006091 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006092 connection->inputState.removeFallbackKey(originalKeyCode);
6093 }
6094 } else {
6095 // If the application did not handle a non-fallback key, first check
6096 // that we are in a good state to perform unhandled key event processing
6097 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006098 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006099 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006100 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6101 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6102 "since this is not an initial down. "
6103 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6104 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6105 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006106 return false;
6107 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006108
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006109 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006110 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6111 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6112 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6113 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6114 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006115 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006116
6117 mLock.unlock();
6118
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006119 bool fallback =
6120 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006121 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006122
6123 mLock.lock();
6124
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006125 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006126 connection->inputState.removeFallbackKey(originalKeyCode);
6127 return false;
6128 }
6129
6130 // Latch the fallback keycode for this key on an initial down.
6131 // The fallback keycode cannot change at any other point in the lifecycle.
6132 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006133 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006134 fallbackKeyCode = event.getKeyCode();
6135 } else {
6136 fallbackKeyCode = AKEYCODE_UNKNOWN;
6137 }
6138 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6139 }
6140
6141 ALOG_ASSERT(fallbackKeyCode != -1);
6142
6143 // Cancel the fallback key if the policy decides not to send it anymore.
6144 // We will continue to dispatch the key to the policy but we will no
6145 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006146 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6147 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006148 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6149 if (fallback) {
6150 ALOGD("Unhandled key event: Policy requested to send key %d"
6151 "as a fallback for %d, but on the DOWN it had requested "
6152 "to send %d instead. Fallback canceled.",
6153 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6154 } else {
6155 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6156 "but on the DOWN it had requested to send %d. "
6157 "Fallback canceled.",
6158 originalKeyCode, fallbackKeyCode);
6159 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006160 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006161
6162 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6163 "canceling fallback, policy no longer desires it");
6164 options.keyCode = fallbackKeyCode;
6165 synthesizeCancelationEventsForConnectionLocked(connection, options);
6166
6167 fallback = false;
6168 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006169 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006170 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006171 }
6172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006173
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006174 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6175 {
6176 std::string msg;
6177 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6178 connection->inputState.getFallbackKeys();
6179 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6180 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6181 }
6182 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6183 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006184 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006185 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006186
6187 if (fallback) {
6188 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006189 keyEntry.eventTime = event.getEventTime();
6190 keyEntry.deviceId = event.getDeviceId();
6191 keyEntry.source = event.getSource();
6192 keyEntry.displayId = event.getDisplayId();
6193 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6194 keyEntry.keyCode = fallbackKeyCode;
6195 keyEntry.scanCode = event.getScanCode();
6196 keyEntry.metaState = event.getMetaState();
6197 keyEntry.repeatCount = event.getRepeatCount();
6198 keyEntry.downTime = event.getDownTime();
6199 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006200
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006201 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6202 ALOGD("Unhandled key event: Dispatching fallback key. "
6203 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6204 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6205 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006206 return true; // restart the event
6207 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006208 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6209 ALOGD("Unhandled key event: No fallback key.");
6210 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006211
6212 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006213 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006214 }
6215 }
6216 return false;
6217}
6218
Prabir Pradhancef936d2021-07-21 16:17:52 +00006219bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006220 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006221 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006222 return false;
6223}
6224
Michael Wrightd02c5b62014-02-10 15:10:22 -08006225void InputDispatcher::traceInboundQueueLengthLocked() {
6226 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006227 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006228 }
6229}
6230
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006231void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006232 if (ATRACE_ENABLED()) {
6233 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006234 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6235 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006236 }
6237}
6238
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006239void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006240 if (ATRACE_ENABLED()) {
6241 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006242 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6243 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006244 }
6245}
6246
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006247void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006248 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006249
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006250 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006251 dumpDispatchStateLocked(dump);
6252
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006253 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006254 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006255 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256 }
6257}
6258
6259void InputDispatcher::monitor() {
6260 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006261 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006263 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006264}
6265
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006266/**
6267 * Wake up the dispatcher and wait until it processes all events and commands.
6268 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6269 * this method can be safely called from any thread, as long as you've ensured that
6270 * the work you are interested in completing has already been queued.
6271 */
6272bool InputDispatcher::waitForIdle() {
6273 /**
6274 * Timeout should represent the longest possible time that a device might spend processing
6275 * events and commands.
6276 */
6277 constexpr std::chrono::duration TIMEOUT = 100ms;
6278 std::unique_lock lock(mLock);
6279 mLooper->wake();
6280 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6281 return result == std::cv_status::no_timeout;
6282}
6283
Vishnu Naire798b472020-07-23 13:52:21 -07006284/**
6285 * Sets focus to the window identified by the token. This must be called
6286 * after updating any input window handles.
6287 *
6288 * Params:
6289 * request.token - input channel token used to identify the window that should gain focus.
6290 * request.focusedToken - the token that the caller expects currently to be focused. If the
6291 * specified token does not match the currently focused window, this request will be dropped.
6292 * If the specified focused token matches the currently focused window, the call will succeed.
6293 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6294 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6295 * when requesting the focus change. This determines which request gets
6296 * precedence if there is a focus change request from another source such as pointer down.
6297 */
Vishnu Nair958da932020-08-21 17:12:37 -07006298void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6299 { // acquire lock
6300 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006301 std::optional<FocusResolver::FocusChanges> changes =
6302 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6303 if (changes) {
6304 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006305 }
6306 } // release lock
6307 // Wake up poll loop since it may need to make new input dispatching choices.
6308 mLooper->wake();
6309}
6310
Vishnu Nairc519ff72021-01-21 08:23:08 -08006311void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6312 if (changes.oldFocus) {
6313 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006314 if (focusedInputChannel) {
6315 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6316 "focus left window");
6317 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006318 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006319 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006320 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006321 if (changes.newFocus) {
6322 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006323 }
6324
Prabir Pradhan99987712020-11-10 18:43:05 -08006325 // If a window has pointer capture, then it must have focus. We need to ensure that this
6326 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6327 // If the window loses focus before it loses pointer capture, then the window can be in a state
6328 // where it has pointer capture but not focus, violating the contract. Therefore we must
6329 // dispatch the pointer capture event before the focus event. Since focus events are added to
6330 // the front of the queue (above), we add the pointer capture event to the front of the queue
6331 // after the focus events are added. This ensures the pointer capture event ends up at the
6332 // front.
6333 disablePointerCaptureForcedLocked();
6334
Vishnu Nairc519ff72021-01-21 08:23:08 -08006335 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006336 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006337 }
6338}
Vishnu Nair958da932020-08-21 17:12:37 -07006339
Prabir Pradhan99987712020-11-10 18:43:05 -08006340void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006341 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006342 return;
6343 }
6344
6345 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6346
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006347 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006348 setPointerCaptureLocked(false);
6349 }
6350
6351 if (!mWindowTokenWithPointerCapture) {
6352 // No need to send capture changes because no window has capture.
6353 return;
6354 }
6355
6356 if (mPendingEvent != nullptr) {
6357 // Move the pending event to the front of the queue. This will give the chance
6358 // for the pending event to be dropped if it is a captured event.
6359 mInboundQueue.push_front(mPendingEvent);
6360 mPendingEvent = nullptr;
6361 }
6362
6363 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006364 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006365 mInboundQueue.push_front(std::move(entry));
6366}
6367
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006368void InputDispatcher::setPointerCaptureLocked(bool enable) {
6369 mCurrentPointerCaptureRequest.enable = enable;
6370 mCurrentPointerCaptureRequest.seq++;
6371 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006372 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006373 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006374 };
6375 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006376}
6377
Vishnu Nair599f1412021-06-21 10:39:58 -07006378void InputDispatcher::displayRemoved(int32_t displayId) {
6379 { // acquire lock
6380 std::scoped_lock _l(mLock);
6381 // Set an empty list to remove all handles from the specific display.
6382 setInputWindowsLocked(/* window handles */ {}, displayId);
6383 setFocusedApplicationLocked(displayId, nullptr);
6384 // Call focus resolver to clean up stale requests. This must be called after input windows
6385 // have been removed for the removed display.
6386 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006387 // Reset pointer capture eligibility, regardless of previous state.
6388 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006389 // Remove the associated touch mode state.
6390 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006391 } // release lock
6392
6393 // Wake up poll loop since it may need to make new input dispatching choices.
6394 mLooper->wake();
6395}
6396
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006397void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6398 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006399 // The listener sends the windows as a flattened array. Separate the windows by display for
6400 // more convenient parsing.
6401 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006402 for (const auto& info : windowInfos) {
6403 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006404 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006405 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006406
6407 { // acquire lock
6408 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006409
6410 // Ensure that we have an entry created for all existing displays so that if a displayId has
6411 // no windows, we can tell that the windows were removed from the display.
6412 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6413 handlesPerDisplay[displayId];
6414 }
6415
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006416 mDisplayInfos.clear();
6417 for (const auto& displayInfo : displayInfos) {
6418 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6419 }
6420
6421 for (const auto& [displayId, handles] : handlesPerDisplay) {
6422 setInputWindowsLocked(handles, displayId);
6423 }
6424 }
6425 // Wake up poll loop since it may need to make new input dispatching choices.
6426 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006427}
6428
Vishnu Nair062a8672021-09-03 16:07:44 -07006429bool InputDispatcher::shouldDropInput(
6430 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006431 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6432 (windowHandle->getInfo()->inputConfig.test(
6433 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006434 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006435 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6436 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006437 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006438 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006439 windowHandle->getInfo()->displayId);
6440 return true;
6441 }
6442 return false;
6443}
6444
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006445void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6446 const std::vector<gui::WindowInfo>& windowInfos,
6447 const std::vector<DisplayInfo>& displayInfos) {
6448 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6449}
6450
Arthur Hungdfd528e2021-12-08 13:23:04 +00006451void InputDispatcher::cancelCurrentTouch() {
6452 {
6453 std::scoped_lock _l(mLock);
6454 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6455 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6456 "cancel current touch");
6457 synthesizeCancelationEventsForAllConnectionsLocked(options);
6458
6459 mTouchStatesByDisplay.clear();
6460 mLastHoverWindowHandle.clear();
6461 }
6462 // Wake up poll loop since there might be work to do.
6463 mLooper->wake();
6464}
6465
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006466void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6467 std::scoped_lock _l(mLock);
6468 mMonitorDispatchingTimeout = timeout;
6469}
6470
Garfield Tane84e6f92019-08-29 17:28:41 -07006471} // namespace android::inputdispatcher