blob: 63a241887b1c745a883fbafaf2df29952ffe0b6c [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 =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001695 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001696 /*byref*/ injectionResult);
1697 for (const TouchedWindow& touchedWindow : touchedWindows) {
1698 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED,
1699 "Shouldn't be adding window if the injection didn't succeed.");
1700 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1701 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
1702 inputTargets);
1703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704 } else {
1705 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001706 sp<WindowInfoHandle> focusedWindow =
1707 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1708 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1709 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1710 addWindowTargetLocked(focusedWindow,
1711 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1712 BitSet32(0), getDownTime(*entry), inputTargets);
1713 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001715 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 return false;
1717 }
1718
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001719 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001720 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001721 return true;
1722 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001723 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001724 CancelationOptions::Mode mode(isPointerEvent
1725 ? CancelationOptions::CANCEL_POINTER_EVENTS
1726 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1727 CancelationOptions options(mode, "input event injection failed");
1728 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 return true;
1730 }
1731
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001732 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001733 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734
1735 // Dispatch the motion.
1736 if (conflictingPointerActions) {
1737 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001738 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 synthesizeCancelationEventsForAllConnectionsLocked(options);
1740 }
1741 dispatchEventLocked(currentTime, entry, inputTargets);
1742 return true;
1743}
1744
chaviw98318de2021-05-19 16:45:23 -05001745void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001746 bool isExiting, const int32_t rawX,
1747 const int32_t rawY) {
1748 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001749 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001750 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1751 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001752
1753 enqueueInboundEventLocked(std::move(dragEntry));
1754}
1755
1756void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1757 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1758 if (channel == nullptr) {
1759 return; // Window has gone away
1760 }
1761 InputTarget target;
1762 target.inputChannel = channel;
1763 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1764 entry->dispatchInProgress = true;
1765 dispatchEventLocked(currentTime, entry, {target});
1766}
1767
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001768void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001769 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1770 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1771 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001772 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001773 "metaState=0x%x, buttonState=0x%x,"
1774 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1775 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001776 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1777 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1778 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001779
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001780 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1781 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1782 "x=%f, y=%f, pressure=%f, size=%f, "
1783 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1784 "orientation=%f",
1785 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1786 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1787 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1788 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1789 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1790 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1791 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1792 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1793 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1794 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797}
1798
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001799void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1800 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001801 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001802 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001803 if (DEBUG_DISPATCH_CYCLE) {
1804 ALOGD("dispatchEventToCurrentInputTargets");
1805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001807 updateInteractionTokensLocked(*eventEntry, inputTargets);
1808
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1810
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001811 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001813 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001814 sp<Connection> connection =
1815 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001816 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001817 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001819 if (DEBUG_FOCUS) {
1820 ALOGD("Dropping event delivery to target with channel '%s' because it "
1821 "is no longer registered with the input dispatcher.",
1822 inputTarget.inputChannel->getName().c_str());
1823 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824 }
1825 }
1826}
1827
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001828void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1829 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1830 // If the policy decides to close the app, we will get a channel removal event via
1831 // unregisterInputChannel, and will clean up the connection that way. We are already not
1832 // sending new pointers to the connection when it blocked, but focused events will continue to
1833 // pile up.
1834 ALOGW("Canceling events for %s because it is unresponsive",
1835 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001836 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001837 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1838 "application not responding");
1839 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001840 }
1841}
1842
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001843void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001844 if (DEBUG_FOCUS) {
1845 ALOGD("Resetting ANR timeouts.");
1846 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847
1848 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001849 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001850 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851}
1852
Tiger Huang721e26f2018-07-24 22:26:19 +08001853/**
1854 * Get the display id that the given event should go to. If this event specifies a valid display id,
1855 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1856 * Focused display is the display that the user most recently interacted with.
1857 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001858int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001859 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001860 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001861 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001862 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1863 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001864 break;
1865 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001866 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001867 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1868 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001869 break;
1870 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001871 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001872 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001873 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001874 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001875 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001876 case EventEntry::Type::SENSOR:
1877 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001878 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001879 return ADISPLAY_ID_NONE;
1880 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001881 }
1882 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1883}
1884
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001885bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1886 const char* focusedWindowName) {
1887 if (mAnrTracker.empty()) {
1888 // already processed all events that we waited for
1889 mKeyIsWaitingForEventsTimeout = std::nullopt;
1890 return false;
1891 }
1892
1893 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1894 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001895 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001896 mKeyIsWaitingForEventsTimeout = currentTime +
1897 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1898 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001899 return true;
1900 }
1901
1902 // We still have pending events, and already started the timer
1903 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1904 return true; // Still waiting
1905 }
1906
1907 // Waited too long, and some connection still hasn't processed all motions
1908 // Just send the key to the focused window
1909 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1910 focusedWindowName);
1911 mKeyIsWaitingForEventsTimeout = std::nullopt;
1912 return false;
1913}
1914
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001915sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1916 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1917 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001918 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001919 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920
Tiger Huang721e26f2018-07-24 22:26:19 +08001921 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001922 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001923 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001924 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1925
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 // If there is no currently focused window and no focused application
1927 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001928 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1929 ALOGI("Dropping %s event because there is no focused window or focused application in "
1930 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001931 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001932 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933 }
1934
Vishnu Nair062a8672021-09-03 16:07:44 -07001935 // Drop key events if requested by input feature
1936 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001937 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07001938 }
1939
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001940 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1941 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1942 // start interacting with another application via touch (app switch). This code can be removed
1943 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1944 // an app is expected to have a focused window.
1945 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1946 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1947 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001948 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1949 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1950 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001951 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001952 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001953 ALOGW("Waiting because no window has focus but %s may eventually add a "
1954 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001955 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001956 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001957 outInjectionResult = InputEventInjectionResult::PENDING;
1958 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001959 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1960 // Already raised ANR. Drop the event
1961 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001962 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001963 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001964 } else {
1965 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001966 outInjectionResult = InputEventInjectionResult::PENDING;
1967 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001968 }
1969 }
1970
1971 // we have a valid, non-null focused window
1972 resetNoFocusedWindowTimeoutLocked();
1973
Prabir Pradhan5735a322022-04-11 17:23:34 +00001974 // Verify targeted injection.
1975 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1976 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001977 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
1978 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979 }
1980
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001981 if (focusedWindowHandle->getInfo()->inputConfig.test(
1982 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001983 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001984 outInjectionResult = InputEventInjectionResult::PENDING;
1985 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001986 }
1987
1988 // If the event is a key event, then we must wait for all previous events to
1989 // complete before delivering it because previous events may have the
1990 // side-effect of transferring focus to a different window and we want to
1991 // ensure that the following keys are sent to the new window.
1992 //
1993 // Suppose the user touches a button in a window then immediately presses "A".
1994 // If the button causes a pop-up window to appear then we want to ensure that
1995 // the "A" key is delivered to the new pop-up window. This is because users
1996 // often anticipate pending UI changes when typing on a keyboard.
1997 // To obtain this behavior, we must serialize key events with respect to all
1998 // prior input events.
1999 if (entry.type == EventEntry::Type::KEY) {
2000 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2001 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002002 outInjectionResult = InputEventInjectionResult::PENDING;
2003 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 }
2006
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002007 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2008 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009}
2010
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002011/**
2012 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2013 * that are currently unresponsive.
2014 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002015std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2016 const std::vector<Monitor>& monitors) const {
2017 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002018 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002019 [this](const Monitor& monitor) REQUIRES(mLock) {
2020 sp<Connection> connection =
2021 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002022 if (connection == nullptr) {
2023 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002024 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002025 return false;
2026 }
2027 if (!connection->responsive) {
2028 ALOGW("Unresponsive monitor %s will not get the new gesture",
2029 connection->inputChannel->getName().c_str());
2030 return false;
2031 }
2032 return true;
2033 });
2034 return responsiveMonitors;
2035}
2036
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002037/**
2038 * In general, touch should be always split between windows. Some exceptions:
2039 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2040 * from the same device, *and* the window that's receiving the current pointer does not support
2041 * split touch.
2042 * 2. Don't split mouse events
2043 */
2044bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2045 const MotionEntry& entry) const {
2046 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2047 // We should never split mouse events
2048 return false;
2049 }
2050 for (const TouchedWindow& touchedWindow : touchState.windows) {
2051 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2052 // Spy windows should not affect whether or not touch is split.
2053 continue;
2054 }
2055 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2056 continue;
2057 }
2058 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2059 // being sent there. For now, use deviceId from touch state.
2060 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2061 return false;
2062 }
2063 }
2064 return true;
2065}
2066
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002067std::vector<TouchedWindow> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002068 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2069 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002070 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002072 std::vector<TouchedWindow> touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 // For security reasons, we defer updating the touch state until we are sure that
2074 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002075 const int32_t displayId = entry.displayId;
2076 const int32_t action = entry.action;
2077 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078
2079 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002080 outInjectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002081 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2082 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002084 // Copy current touch state into tempTouchState.
2085 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2086 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002087 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002088 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002089 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2090 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002091 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002092 }
2093
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002094 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002095 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2096 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2097 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002098
2099 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2100 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2101 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2102 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2103 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002104 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 bool wrongDevice = false;
2106 if (newGesture) {
2107 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002108 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002109 ALOGI("Dropping event because a pointer for a different device is already down "
2110 "in display %" PRId32,
2111 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002112 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002113 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 switchedDevice = false;
2115 wrongDevice = true;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002116 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002118 tempTouchState.reset();
2119 tempTouchState.down = down;
2120 tempTouchState.deviceId = entry.deviceId;
2121 tempTouchState.source = entry.source;
2122 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002124 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002125 ALOGI("Dropping move event because a pointer for a different device is already active "
2126 "in display %" PRId32,
2127 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002128 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002129 outInjectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002130 switchedDevice = false;
2131 wrongDevice = true;
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002132 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133 }
2134
2135 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2136 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002137 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002138 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002139 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002140 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002141 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002142 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002143
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002145 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002146 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2147 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002149 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002150 }
2151
Prabir Pradhan5735a322022-04-11 17:23:34 +00002152 // Verify targeted injection.
2153 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2154 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002155 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002156 newTouchedWindowHandle = nullptr;
2157 goto Failed;
2158 }
2159
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002160 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002161 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002162 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2163 // New window supports splitting, but we should never split mouse events.
2164 isSplit = !isFromMouse;
2165 } else if (isSplit) {
2166 // New window does not support splitting but we have already split events.
2167 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002168 newTouchedWindowHandle = nullptr;
2169 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002170 } else {
2171 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002172 // be delivered to a new window which supports split touch. Pointers from a mouse device
2173 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002174 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002175 }
2176
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002177 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002178 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002179 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2180 newHoverWindowHandle = nullptr;
2181 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002182 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002183 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002184 }
2185
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002186 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002187 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002188 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002189 // Process the foreground window first so that it is the first to receive the event.
2190 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002191 }
2192
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002193 if (newTouchedWindows.empty()) {
2194 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2195 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002196 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002197 goto Failed;
2198 }
2199
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002200 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002201 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002202 continue;
2203 }
2204
2205 // Set target flags.
2206 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2207
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002208 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2209 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002210 targetFlags |= InputTarget::FLAG_FOREGROUND;
2211 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002212
2213 if (isSplit) {
2214 targetFlags |= InputTarget::FLAG_SPLIT;
2215 }
2216 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2217 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2218 } else if (isWindowObscuredLocked(windowHandle)) {
2219 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2220 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002221
2222 // Update the temporary touch state.
2223 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002224 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002225
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002226 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2227 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002229
2230 // If any existing window is pilfering pointers from newly added window, remove it
2231 BitSet32 canceledPointers = BitSet32(0);
2232 for (const TouchedWindow& window : tempTouchState.windows) {
2233 if (window.isPilferingPointers) {
2234 canceledPointers |= window.pointerIds;
2235 }
2236 }
2237 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 } else {
2239 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2240
2241 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002242 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002243 if (DEBUG_FOCUS) {
2244 ALOGD("Dropping event because the pointer is not down or we previously "
2245 "dropped the pointer down event in display %" PRId32,
2246 displayId);
2247 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002248 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 goto Failed;
2250 }
2251
arthurhung6d4bed92021-03-17 11:59:33 +08002252 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002253
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002255 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002256 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002257 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002258 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002259 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002260 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002261 newTouchedWindowHandle =
2262 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002263
Prabir Pradhan5735a322022-04-11 17:23:34 +00002264 // Verify targeted injection.
2265 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2266 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002267 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002268 newTouchedWindowHandle = nullptr;
2269 goto Failed;
2270 }
2271
Vishnu Nair062a8672021-09-03 16:07:44 -07002272 // Drop touch events if requested by input feature
2273 if (newTouchedWindowHandle != nullptr &&
2274 shouldDropInput(entry, newTouchedWindowHandle)) {
2275 newTouchedWindowHandle = nullptr;
2276 }
2277
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002278 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2279 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002280 if (DEBUG_FOCUS) {
2281 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2282 oldTouchedWindowHandle->getName().c_str(),
2283 newTouchedWindowHandle->getName().c_str(), displayId);
2284 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002286 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2287 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2288 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289
2290 // Make a slippery entrance into the new window.
2291 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002292 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 }
2294
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002295 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2296 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2297 targetFlags |= InputTarget::FLAG_FOREGROUND;
2298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299 if (isSplit) {
2300 targetFlags |= InputTarget::FLAG_SPLIT;
2301 }
2302 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2303 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002304 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2305 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
2307
2308 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002309 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002310 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2311 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312 }
2313 }
2314 }
2315
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002316 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002318 // Let the previous window know that the hover sequence is over, unless we already did
2319 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002320 if (mLastHoverWindowHandle != nullptr &&
2321 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2322 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002323 if (DEBUG_HOVER) {
2324 ALOGD("Sending hover exit event to window %s.",
2325 mLastHoverWindowHandle->getName().c_str());
2326 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002327 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2328 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 }
2330
Garfield Tandf26e862020-07-01 20:18:19 -07002331 // Let the new window know that the hover sequence is starting, unless we already did it
2332 // when dispatching it as is to newTouchedWindowHandle.
2333 if (newHoverWindowHandle != nullptr &&
2334 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2335 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002336 if (DEBUG_HOVER) {
2337 ALOGD("Sending hover enter event to window %s.",
2338 newHoverWindowHandle->getName().c_str());
2339 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002340 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2341 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2342 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002343 }
2344 }
2345
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002346 // Ensure that we have at least one foreground window or at least one window that cannot be a
2347 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2348 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2349 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002350 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2351 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002352 return !canReceiveForegroundTouches(
2353 *touchedWindow.windowHandle->getInfo()) ||
2354 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002355 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002356 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2357 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002358 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002359 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360 }
2361
Prabir Pradhan5735a322022-04-11 17:23:34 +00002362 // Ensure that all touched windows are valid for injection.
2363 if (entry.injectionState != nullptr) {
2364 std::string errs;
2365 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2366 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2367 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2368 // dispatched to any uid, since the coords will be zeroed out later.
2369 continue;
2370 }
2371 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2372 if (err) errs += "\n - " + *err;
2373 }
2374 if (!errs.empty()) {
2375 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2376 "%d:%s",
2377 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002378 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002379 goto Failed;
2380 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002381 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002382
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383 // Check whether windows listening for outside touches are owned by the same UID. If it is
2384 // set the policy flag that we will not reveal coordinate information to this window.
2385 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002386 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002387 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002388 if (foregroundWindowHandle) {
2389 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002390 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002391 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002392 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2393 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2394 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002395 InputTarget::FLAG_ZERO_COORDS,
2396 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002397 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 }
2399 }
2400 }
2401 }
2402
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 // If this is the first pointer going down and the touched window has a wallpaper
2404 // then also add the touched wallpaper windows so they are locked in for the duration
2405 // of the touch gesture.
2406 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2407 // engine only supports touch events. We would need to add a mechanism similar
2408 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2409 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002410 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002411 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002412 if (foregroundWindowHandle &&
2413 foregroundWindowHandle->getInfo()->inputConfig.test(
2414 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002415 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002416 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002417 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2418 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002419 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002420 windowHandle->getInfo()->inputConfig.test(
2421 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002422 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002423 .addOrUpdateWindow(windowHandle,
2424 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2425 InputTarget::
2426 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2427 InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002428 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 }
2430 }
2431 }
2432 }
2433
2434 // Success! Output targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002435 touchedWindows = tempTouchState.windows;
2436 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437
2438 // Drop the outside or hover touch windows since we will not care about them
2439 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002440 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441
2442Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002444 if (switchedDevice) {
2445 if (DEBUG_FOCUS) {
2446 ALOGD("Conflicting pointer actions: Switched to a different device.");
2447 }
2448 *outConflictingPointerActions = true;
2449 }
2450
2451 if (isHoverAction) {
2452 // Started hovering, therefore no longer down.
2453 if (oldState && oldState->down) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002454 if (DEBUG_FOCUS) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002455 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2456 "down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002457 }
2458 *outConflictingPointerActions = true;
2459 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002460 tempTouchState.reset();
2461 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2462 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2463 tempTouchState.deviceId = entry.deviceId;
2464 tempTouchState.source = entry.source;
2465 tempTouchState.displayId = displayId;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002466 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002467 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2468 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2469 // All pointers up or canceled.
2470 tempTouchState.reset();
2471 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2472 // First pointer went down.
2473 if (oldState && oldState->down) {
2474 if (DEBUG_FOCUS) {
2475 ALOGD("Conflicting pointer actions: Down received while already down.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002477 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002478 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002479 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2480 // One pointer went up.
2481 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2482 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002484 for (size_t i = 0; i < tempTouchState.windows.size();) {
2485 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2486 touchedWindow.pointerIds.clearBit(pointerId);
2487 if (touchedWindow.pointerIds.isEmpty()) {
2488 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2489 continue;
2490 }
2491 i += 1;
2492 }
2493 } else if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2494 // If no split, we suppose all touched windows should receive pointer down.
2495 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2496 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2497 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2498 // Ignore drag window for it should just track one pointer.
2499 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2500 continue;
2501 }
2502 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 }
2505
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002506 // Save changes unless the action was scroll in which case the temporary touch
2507 // state was only valid for this one action.
2508 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
2509 if (tempTouchState.displayId >= 0) {
2510 mTouchStatesByDisplay[displayId] = tempTouchState;
2511 } else {
2512 mTouchStatesByDisplay.erase(displayId);
2513 }
2514 }
2515
2516 // Update hover state.
2517 mLastHoverWindowHandle = newHoverWindowHandle;
2518
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002519 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520}
2521
arthurhung6d4bed92021-03-17 11:59:33 +08002522void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002523 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2524 // have an explicit reason to support it.
2525 constexpr bool isStylus = false;
2526
chaviw98318de2021-05-19 16:45:23 -05002527 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002528 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002529 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002530 if (dropWindow) {
2531 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002532 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002533 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002534 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002535 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002536 }
2537 mDragState.reset();
2538}
2539
2540void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002541 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002542 return;
2543 }
2544
arthurhung6d4bed92021-03-17 11:59:33 +08002545 if (!mDragState->isStartDrag) {
2546 mDragState->isStartDrag = true;
2547 mDragState->isStylusButtonDownAtStart =
2548 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2549 }
2550
Arthur Hung54745652022-04-20 07:17:41 +00002551 // Find the pointer index by id.
2552 int32_t pointerIndex = 0;
2553 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2554 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2555 if (pointerProperties.id == mDragState->pointerId) {
2556 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002557 }
Arthur Hung54745652022-04-20 07:17:41 +00002558 }
arthurhung6d4bed92021-03-17 11:59:33 +08002559
Arthur Hung54745652022-04-20 07:17:41 +00002560 if (uint32_t(pointerIndex) == entry.pointerCount) {
2561 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002562 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002563 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002564 return;
2565 }
2566
2567 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2568 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2569 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2570
2571 switch (maskedAction) {
2572 case AMOTION_EVENT_ACTION_MOVE: {
2573 // Handle the special case : stylus button no longer pressed.
2574 bool isStylusButtonDown =
2575 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2576 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2577 finishDragAndDrop(entry.displayId, x, y);
2578 return;
2579 }
2580
2581 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2582 // until we have an explicit reason to support it.
2583 constexpr bool isStylus = false;
2584
2585 const sp<WindowInfoHandle> hoverWindowHandle =
2586 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2587 isStylus, false /*addOutsideTargets*/,
2588 true /*ignoreDragWindow*/);
2589 // enqueue drag exit if needed.
2590 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2591 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2592 if (mDragState->dragHoverWindowHandle != nullptr) {
2593 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2594 y);
2595 }
2596 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2597 }
2598 // enqueue drag location if needed.
2599 if (hoverWindowHandle != nullptr) {
2600 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2601 }
2602 break;
2603 }
2604
2605 case AMOTION_EVENT_ACTION_POINTER_UP:
2606 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2607 break;
2608 }
2609 // The drag pointer is up.
2610 [[fallthrough]];
2611 case AMOTION_EVENT_ACTION_UP:
2612 finishDragAndDrop(entry.displayId, x, y);
2613 break;
2614 case AMOTION_EVENT_ACTION_CANCEL: {
2615 ALOGD("Receiving cancel when drag and drop.");
2616 sendDropWindowCommandLocked(nullptr, 0, 0);
2617 mDragState.reset();
2618 break;
2619 }
arthurhungb89ccb02020-12-30 16:19:01 +08002620 }
2621}
2622
chaviw98318de2021-05-19 16:45:23 -05002623void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002624 int32_t targetFlags, BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002625 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002626 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002627 std::vector<InputTarget>::iterator it =
2628 std::find_if(inputTargets.begin(), inputTargets.end(),
2629 [&windowHandle](const InputTarget& inputTarget) {
2630 return inputTarget.inputChannel->getConnectionToken() ==
2631 windowHandle->getToken();
2632 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002633
chaviw98318de2021-05-19 16:45:23 -05002634 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002635
2636 if (it == inputTargets.end()) {
2637 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002638 std::shared_ptr<InputChannel> inputChannel =
2639 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002640 if (inputChannel == nullptr) {
2641 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2642 return;
2643 }
2644 inputTarget.inputChannel = inputChannel;
2645 inputTarget.flags = targetFlags;
2646 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002647 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002648 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2649 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002650 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002651 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002652 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002653 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002654 inputTargets.push_back(inputTarget);
2655 it = inputTargets.end() - 1;
2656 }
2657
2658 ALOG_ASSERT(it->flags == targetFlags);
2659 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2660
chaviw1ff3d1e2020-07-01 15:53:47 -07002661 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662}
2663
Michael Wright3dd60e22019-03-27 22:06:44 +00002664void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002665 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002666 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2667 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002668
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002669 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2670 InputTarget target;
2671 target.inputChannel = monitor.inputChannel;
2672 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002673 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2674 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002675 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2676 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002677 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002678 target.setDefaultPointerTransform(target.displayTransform);
2679 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 }
2681}
2682
Robert Carrc9bf1d32020-04-13 17:21:08 -07002683/**
2684 * Indicate whether one window handle should be considered as obscuring
2685 * another window handle. We only check a few preconditions. Actually
2686 * checking the bounds is left to the caller.
2687 */
chaviw98318de2021-05-19 16:45:23 -05002688static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2689 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002690 // Compare by token so cloned layers aren't counted
2691 if (haveSameToken(windowHandle, otherHandle)) {
2692 return false;
2693 }
2694 auto info = windowHandle->getInfo();
2695 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002696 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002697 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002698 } else if (otherInfo->alpha == 0 &&
2699 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002700 // Those act as if they were invisible, so we don't need to flag them.
2701 // We do want to potentially flag touchable windows even if they have 0
2702 // opacity, since they can consume touches and alter the effects of the
2703 // user interaction (eg. apps that rely on
2704 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2705 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2706 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002707 } else if (info->ownerUid == otherInfo->ownerUid) {
2708 // If ownerUid is the same we don't generate occlusion events as there
2709 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002710 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002711 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002712 return false;
2713 } else if (otherInfo->displayId != info->displayId) {
2714 return false;
2715 }
2716 return true;
2717}
2718
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002719/**
2720 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2721 * untrusted, one should check:
2722 *
2723 * 1. If result.hasBlockingOcclusion is true.
2724 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2725 * BLOCK_UNTRUSTED.
2726 *
2727 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2728 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2729 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2730 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2731 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2732 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2733 *
2734 * If neither of those is true, then it means the touch can be allowed.
2735 */
2736InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002737 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2738 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002739 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002740 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002741 TouchOcclusionInfo info;
2742 info.hasBlockingOcclusion = false;
2743 info.obscuringOpacity = 0;
2744 info.obscuringUid = -1;
2745 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002746 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002747 if (windowHandle == otherHandle) {
2748 break; // All future windows are below us. Exit early.
2749 }
chaviw98318de2021-05-19 16:45:23 -05002750 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002751 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2752 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002753 if (DEBUG_TOUCH_OCCLUSION) {
2754 info.debugInfo.push_back(
2755 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2756 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002757 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2758 // we perform the checks below to see if the touch can be propagated or not based on the
2759 // window's touch occlusion mode
2760 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2761 info.hasBlockingOcclusion = true;
2762 info.obscuringUid = otherInfo->ownerUid;
2763 info.obscuringPackage = otherInfo->packageName;
2764 break;
2765 }
2766 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2767 uint32_t uid = otherInfo->ownerUid;
2768 float opacity =
2769 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2770 // Given windows A and B:
2771 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2772 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2773 opacityByUid[uid] = opacity;
2774 if (opacity > info.obscuringOpacity) {
2775 info.obscuringOpacity = opacity;
2776 info.obscuringUid = uid;
2777 info.obscuringPackage = otherInfo->packageName;
2778 }
2779 }
2780 }
2781 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002782 if (DEBUG_TOUCH_OCCLUSION) {
2783 info.debugInfo.push_back(
2784 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2785 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002786 return info;
2787}
2788
chaviw98318de2021-05-19 16:45:23 -05002789std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002790 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002791 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2792 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2793 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2794 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002795 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2796 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2797 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2798 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2799 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002800 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002801 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002802}
2803
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002804bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2805 if (occlusionInfo.hasBlockingOcclusion) {
2806 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2807 occlusionInfo.obscuringUid);
2808 return false;
2809 }
2810 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2811 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2812 "%.2f, maximum allowed = %.2f)",
2813 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2814 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2815 return false;
2816 }
2817 return true;
2818}
2819
chaviw98318de2021-05-19 16:45:23 -05002820bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002821 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002823 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2824 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002825 if (windowHandle == otherHandle) {
2826 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827 }
chaviw98318de2021-05-19 16:45:23 -05002828 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002829 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002830 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 return true;
2832 }
2833 }
2834 return false;
2835}
2836
chaviw98318de2021-05-19 16:45:23 -05002837bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002838 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002839 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2840 const WindowInfo* windowInfo = windowHandle->getInfo();
2841 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002842 if (windowHandle == otherHandle) {
2843 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002844 }
chaviw98318de2021-05-19 16:45:23 -05002845 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002846 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002847 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002848 return true;
2849 }
2850 }
2851 return false;
2852}
2853
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002854std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002855 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002856 if (applicationHandle != nullptr) {
2857 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002858 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859 } else {
2860 return applicationHandle->getName();
2861 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002862 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002863 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002865 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 }
2867}
2868
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002869void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002870 if (!isUserActivityEvent(eventEntry)) {
2871 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002872 return;
2873 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002874 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002875 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002876 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002877 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002878 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002879 if (DEBUG_DISPATCH_CYCLE) {
2880 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882 return;
2883 }
2884 }
2885
2886 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002887 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002888 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002889 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2890 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002891 return;
2892 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002894 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002895 eventType = USER_ACTIVITY_EVENT_TOUCH;
2896 }
2897 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002898 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002899 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002900 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2901 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002902 return;
2903 }
2904 eventType = USER_ACTIVITY_EVENT_BUTTON;
2905 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002907 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002908 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002909 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002910 break;
2911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912 }
2913
Prabir Pradhancef936d2021-07-21 16:17:52 +00002914 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2915 REQUIRES(mLock) {
2916 scoped_unlock unlock(mLock);
2917 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2918 };
2919 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920}
2921
2922void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002923 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002924 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002925 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002926 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002927 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002928 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002929 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002930 ATRACE_NAME(message.c_str());
2931 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002932 if (DEBUG_DISPATCH_CYCLE) {
2933 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2934 "globalScaleFactor=%f, pointerIds=0x%x %s",
2935 connection->getInputChannelName().c_str(), inputTarget.flags,
2936 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2937 inputTarget.getPointerInfoString().c_str());
2938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939
2940 // Skip this event if the connection status is not normal.
2941 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002942 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002943 if (DEBUG_DISPATCH_CYCLE) {
2944 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002945 connection->getInputChannelName().c_str(),
2946 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948 return;
2949 }
2950
2951 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002952 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2953 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2954 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002955 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002957 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002958 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002959 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2960 "Splitting motion events requires a down time to be set for the "
2961 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002962 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002963 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2964 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965 if (!splitMotionEntry) {
2966 return; // split event was dropped
2967 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002968 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2969 std::string reason = std::string("reason=pointer cancel on split window");
2970 android_log_event_list(LOGTAG_INPUT_CANCEL)
2971 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2972 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002973 if (DEBUG_FOCUS) {
2974 ALOGD("channel '%s' ~ Split motion event.",
2975 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002976 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002977 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002978 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2979 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980 return;
2981 }
2982 }
2983
2984 // Not splitting. Enqueue dispatch entries for the event as is.
2985 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2986}
2987
2988void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002989 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002990 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002991 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002992 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002993 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002994 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002995 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002996 ATRACE_NAME(message.c_str());
2997 }
2998
hongzuo liu95785e22022-09-06 02:51:35 +00002999 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000
3001 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07003002 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003003 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003004 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003005 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07003006 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003007 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07003008 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003009 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003010 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003012 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003013 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014
3015 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003016 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017 startDispatchCycleLocked(currentTime, connection);
3018 }
3019}
3020
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003021void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003022 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003023 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003024 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003025 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003026 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3027 connection->getInputChannelName().c_str(),
3028 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003029 ATRACE_NAME(message.c_str());
3030 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003031 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032 if (!(inputTargetFlags & dispatchMode)) {
3033 return;
3034 }
3035 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
3036
3037 // This is a new event.
3038 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003039 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003040 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003042 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3043 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003044 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003046 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003047 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003048 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003049 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003050 dispatchEntry->resolvedAction = keyEntry.action;
3051 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003053 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3054 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003055 if (DEBUG_DISPATCH_CYCLE) {
3056 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3057 "event",
3058 connection->getInputChannelName().c_str());
3059 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003060 return; // skip the inconsistent event
3061 }
3062 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003065 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003066 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003067 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3068 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3069 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3070 static_cast<int32_t>(IdGenerator::Source::OTHER);
3071 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003072 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3073 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3074 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3075 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3076 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3077 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3078 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3079 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3080 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3081 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3082 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003083 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003084 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003085 }
3086 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003087 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3088 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003089 if (DEBUG_DISPATCH_CYCLE) {
3090 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3091 "enter event",
3092 connection->getInputChannelName().c_str());
3093 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003094 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3095 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003096 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003099 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003100 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3101 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3102 }
3103 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3104 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3105 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003107 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3108 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003109 if (DEBUG_DISPATCH_CYCLE) {
3110 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3111 "event",
3112 connection->getInputChannelName().c_str());
3113 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003114 return; // skip the inconsistent event
3115 }
3116
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003117 dispatchEntry->resolvedEventId =
3118 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3119 ? mIdGenerator.nextId()
3120 : motionEntry.id;
3121 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3122 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3123 ") to MotionEvent(id=0x%" PRIx32 ").",
3124 motionEntry.id, dispatchEntry->resolvedEventId);
3125 ATRACE_NAME(message.c_str());
3126 }
3127
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003128 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3129 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3130 // Skip reporting pointer down outside focus to the policy.
3131 break;
3132 }
3133
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003134 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003135 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003136
3137 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003139 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003140 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003141 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3142 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003143 break;
3144 }
Chris Yef59a2f42020-10-16 12:55:26 -07003145 case EventEntry::Type::SENSOR: {
3146 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3147 break;
3148 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003149 case EventEntry::Type::CONFIGURATION_CHANGED:
3150 case EventEntry::Type::DEVICE_RESET: {
3151 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003152 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003153 break;
3154 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155 }
3156
3157 // Remember that we are waiting for this dispatch to complete.
3158 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003159 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 }
3161
3162 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003163 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003164 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003165}
3166
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003167/**
3168 * This function is purely for debugging. It helps us understand where the user interaction
3169 * was taking place. For example, if user is touching launcher, we will see a log that user
3170 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3171 * We will see both launcher and wallpaper in that list.
3172 * Once the interaction with a particular set of connections starts, no new logs will be printed
3173 * until the set of interacted connections changes.
3174 *
3175 * The following items are skipped, to reduce the logspam:
3176 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3177 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3178 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3179 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3180 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003181 */
3182void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3183 const std::vector<InputTarget>& targets) {
3184 // Skip ACTION_UP events, and all events other than keys and motions
3185 if (entry.type == EventEntry::Type::KEY) {
3186 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3187 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3188 return;
3189 }
3190 } else if (entry.type == EventEntry::Type::MOTION) {
3191 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3192 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3193 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3194 return;
3195 }
3196 } else {
3197 return; // Not a key or a motion
3198 }
3199
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003200 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003201 std::vector<sp<Connection>> newConnections;
3202 for (const InputTarget& target : targets) {
3203 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3204 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3205 continue; // Skip windows that receive ACTION_OUTSIDE
3206 }
3207
3208 sp<IBinder> token = target.inputChannel->getConnectionToken();
3209 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003210 if (connection == nullptr) {
3211 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003212 }
3213 newConnectionTokens.insert(std::move(token));
3214 newConnections.emplace_back(connection);
3215 }
3216 if (newConnectionTokens == mInteractionConnectionTokens) {
3217 return; // no change
3218 }
3219 mInteractionConnectionTokens = newConnectionTokens;
3220
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003221 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003222 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003223 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003224 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003225 std::string message = "Interaction with: " + targetList;
3226 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003227 message += "<none>";
3228 }
3229 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3230}
3231
chaviwfd6d3512019-03-25 13:23:49 -07003232void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003233 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003234 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003235 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3236 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003237 return;
3238 }
3239
Vishnu Nairc519ff72021-01-21 08:23:08 -08003240 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003241 if (focusedToken == token) {
3242 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003243 return;
3244 }
3245
Prabir Pradhancef936d2021-07-21 16:17:52 +00003246 auto command = [this, token]() REQUIRES(mLock) {
3247 scoped_unlock unlock(mLock);
3248 mPolicy->onPointerDownOutsideFocus(token);
3249 };
3250 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251}
3252
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003253status_t InputDispatcher::publishMotionEvent(Connection& connection,
3254 DispatchEntry& dispatchEntry) const {
3255 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3256 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3257
3258 PointerCoords scaledCoords[MAX_POINTERS];
3259 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3260
3261 // Set the X and Y offset and X and Y scale depending on the input source.
3262 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
3263 !(dispatchEntry.targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3264 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3265 if (globalScaleFactor != 1.0f) {
3266 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3267 scaledCoords[i] = motionEntry.pointerCoords[i];
3268 // Don't apply window scale here since we don't want scale to affect raw
3269 // coordinates. The scale will be sent back to the client and applied
3270 // later when requesting relative coordinates.
3271 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3272 1 /* windowYScale */);
3273 }
3274 usingCoords = scaledCoords;
3275 }
3276 } else if (dispatchEntry.targetFlags & InputTarget::FLAG_ZERO_COORDS) {
3277 // We don't want the dispatch target to know the coordinates
3278 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3279 scaledCoords[i].clear();
3280 }
3281 usingCoords = scaledCoords;
3282 }
3283
3284 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3285
3286 // Publish the motion event.
3287 return connection.inputPublisher
3288 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3289 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3290 std::move(hmac), dispatchEntry.resolvedAction,
3291 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3292 motionEntry.edgeFlags, motionEntry.metaState,
3293 motionEntry.buttonState, motionEntry.classification,
3294 dispatchEntry.transform, motionEntry.xPrecision,
3295 motionEntry.yPrecision, motionEntry.xCursorPosition,
3296 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3297 motionEntry.downTime, motionEntry.eventTime,
3298 motionEntry.pointerCount, motionEntry.pointerProperties,
3299 usingCoords);
3300}
3301
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003303 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003304 if (ATRACE_ENABLED()) {
3305 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003306 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003307 ATRACE_NAME(message.c_str());
3308 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003309 if (DEBUG_DISPATCH_CYCLE) {
3310 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003313 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003314 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003316 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003317 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318
3319 // Publish the event.
3320 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003321 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3322 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003323 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003324 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3325 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003327 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003328 status = connection->inputPublisher
3329 .publishKeyEvent(dispatchEntry->seq,
3330 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3331 keyEntry.source, keyEntry.displayId,
3332 std::move(hmac), dispatchEntry->resolvedAction,
3333 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3334 keyEntry.scanCode, keyEntry.metaState,
3335 keyEntry.repeatCount, keyEntry.downTime,
3336 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338 }
3339
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003340 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003341 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003342 break;
3343 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003344
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003345 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003346 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003347 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003348 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003349 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003350 break;
3351 }
3352
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003353 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3354 const TouchModeEntry& touchModeEntry =
3355 static_cast<const TouchModeEntry&>(eventEntry);
3356 status = connection->inputPublisher
3357 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3358 touchModeEntry.inTouchMode);
3359
3360 break;
3361 }
3362
Prabir Pradhan99987712020-11-10 18:43:05 -08003363 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3364 const auto& captureEntry =
3365 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3366 status = connection->inputPublisher
3367 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003368 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003369 break;
3370 }
3371
arthurhungb89ccb02020-12-30 16:19:01 +08003372 case EventEntry::Type::DRAG: {
3373 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3374 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3375 dragEntry.id, dragEntry.x,
3376 dragEntry.y,
3377 dragEntry.isExiting);
3378 break;
3379 }
3380
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003381 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003382 case EventEntry::Type::DEVICE_RESET:
3383 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003384 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003385 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003386 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 }
3389
3390 // Check the result.
3391 if (status) {
3392 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003393 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003395 "This is unexpected because the wait queue is empty, so the pipe "
3396 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003397 "event to it, status=%s(%d)",
3398 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3399 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3401 } else {
3402 // Pipe is full and we are waiting for the app to finish process some events
3403 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003404 if (DEBUG_DISPATCH_CYCLE) {
3405 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3406 "waiting for the application to catch up",
3407 connection->getInputChannelName().c_str());
3408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 }
3410 } else {
3411 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003412 "status=%s(%d)",
3413 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3414 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3416 }
3417 return;
3418 }
3419
3420 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003421 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3422 connection->outboundQueue.end(),
3423 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003424 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003425 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003426 if (connection->responsive) {
3427 mAnrTracker.insert(dispatchEntry->timeoutTime,
3428 connection->inputChannel->getConnectionToken());
3429 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003430 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431 }
3432}
3433
chaviw09c8d2d2020-08-24 15:48:26 -07003434std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3435 size_t size;
3436 switch (event.type) {
3437 case VerifiedInputEvent::Type::KEY: {
3438 size = sizeof(VerifiedKeyEvent);
3439 break;
3440 }
3441 case VerifiedInputEvent::Type::MOTION: {
3442 size = sizeof(VerifiedMotionEvent);
3443 break;
3444 }
3445 }
3446 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3447 return mHmacKeyManager.sign(start, size);
3448}
3449
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003450const std::array<uint8_t, 32> InputDispatcher::getSignature(
3451 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003452 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3453 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003454 // Only sign events up and down events as the purely move events
3455 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003456 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003457 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003458
3459 VerifiedMotionEvent verifiedEvent =
3460 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3461 verifiedEvent.actionMasked = actionMasked;
3462 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3463 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003464}
3465
3466const std::array<uint8_t, 32> InputDispatcher::getSignature(
3467 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3468 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3469 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3470 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003471 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003472}
3473
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003475 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003476 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003477 if (DEBUG_DISPATCH_CYCLE) {
3478 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3479 connection->getInputChannelName().c_str(), seq, toString(handled));
3480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003482 if (connection->status == Connection::Status::BROKEN ||
3483 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484 return;
3485 }
3486
3487 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003488 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3489 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3490 };
3491 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492}
3493
3494void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003495 const sp<Connection>& connection,
3496 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003497 if (DEBUG_DISPATCH_CYCLE) {
3498 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3499 connection->getInputChannelName().c_str(), toString(notify));
3500 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501
3502 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003503 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003504 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003505 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003506 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507
3508 // The connection appears to be unrecoverably broken.
3509 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003510 if (connection->status == Connection::Status::NORMAL) {
3511 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512
3513 if (notify) {
3514 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003515 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3516 connection->getInputChannelName().c_str());
3517
3518 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003519 scoped_unlock unlock(mLock);
3520 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3521 };
3522 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523 }
3524 }
3525}
3526
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003527void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3528 while (!queue.empty()) {
3529 DispatchEntry* dispatchEntry = queue.front();
3530 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003531 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 }
3533}
3534
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003535void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003537 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 }
3539 delete dispatchEntry;
3540}
3541
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003542int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3543 std::scoped_lock _l(mLock);
3544 sp<Connection> connection = getConnectionLocked(connectionToken);
3545 if (connection == nullptr) {
3546 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3547 connectionToken.get(), events);
3548 return 0; // remove the callback
3549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003551 bool notify;
3552 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3553 if (!(events & ALOOPER_EVENT_INPUT)) {
3554 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3555 "events=0x%x",
3556 connection->getInputChannelName().c_str(), events);
3557 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 }
3559
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003560 nsecs_t currentTime = now();
3561 bool gotOne = false;
3562 status_t status = OK;
3563 for (;;) {
3564 Result<InputPublisher::ConsumerResponse> result =
3565 connection->inputPublisher.receiveConsumerResponse();
3566 if (!result.ok()) {
3567 status = result.error().code();
3568 break;
3569 }
3570
3571 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3572 const InputPublisher::Finished& finish =
3573 std::get<InputPublisher::Finished>(*result);
3574 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3575 finish.consumeTime);
3576 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003577 if (shouldReportMetricsForConnection(*connection)) {
3578 const InputPublisher::Timeline& timeline =
3579 std::get<InputPublisher::Timeline>(*result);
3580 mLatencyTracker
3581 .trackGraphicsLatency(timeline.inputEventId,
3582 connection->inputChannel->getConnectionToken(),
3583 std::move(timeline.graphicsTimeline));
3584 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003585 }
3586 gotOne = true;
3587 }
3588 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003589 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003590 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 return 1;
3592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 }
3594
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003595 notify = status != DEAD_OBJECT || !connection->monitor;
3596 if (notify) {
3597 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3598 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3599 status);
3600 }
3601 } else {
3602 // Monitor channels are never explicitly unregistered.
3603 // We do it automatically when the remote endpoint is closed so don't warn about them.
3604 const bool stillHaveWindowHandle =
3605 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3606 notify = !connection->monitor && stillHaveWindowHandle;
3607 if (notify) {
3608 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3609 connection->getInputChannelName().c_str(), events);
3610 }
3611 }
3612
3613 // Remove the channel.
3614 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3615 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616}
3617
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003618void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003620 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003621 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 }
3623}
3624
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003625void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003626 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003627 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003628 for (const Monitor& monitor : monitors) {
3629 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003630 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003631 }
3632}
3633
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003635 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003636 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003637 if (connection == nullptr) {
3638 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003640
3641 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642}
3643
3644void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3645 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003646 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647 return;
3648 }
3649
3650 nsecs_t currentTime = now();
3651
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003652 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003653 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003655 if (cancelationEvents.empty()) {
3656 return;
3657 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003658 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3659 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3660 "with reality: %s, mode=%d.",
3661 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3662 options.mode);
3663 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003664
Arthur Hungb3307ee2021-10-14 10:57:37 +00003665 std::string reason = std::string("reason=").append(options.reason);
3666 android_log_event_list(LOGTAG_INPUT_CANCEL)
3667 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3668
Svet Ganov5d3bc372020-01-26 23:11:07 -08003669 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003670 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003671 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3672 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003673 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003674 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003675 target.globalScaleFactor = windowInfo->globalScaleFactor;
3676 }
3677 target.inputChannel = connection->inputChannel;
3678 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3679
hongzuo liu95785e22022-09-06 02:51:35 +00003680 const bool wasEmpty = connection->outboundQueue.empty();
3681
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003682 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003683 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003684 switch (cancelationEventEntry->type) {
3685 case EventEntry::Type::KEY: {
3686 logOutboundKeyDetails("cancel - ",
3687 static_cast<const KeyEntry&>(*cancelationEventEntry));
3688 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003690 case EventEntry::Type::MOTION: {
3691 logOutboundMotionDetails("cancel - ",
3692 static_cast<const MotionEntry&>(*cancelationEventEntry));
3693 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003695 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003696 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003697 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3698 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003699 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003700 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003701 break;
3702 }
3703 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003704 case EventEntry::Type::DEVICE_RESET:
3705 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003706 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003707 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003708 break;
3709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 }
3711
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003712 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3713 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003715
hongzuo liu95785e22022-09-06 02:51:35 +00003716 // If the outbound queue was previously empty, start the dispatch cycle going.
3717 if (wasEmpty && !connection->outboundQueue.empty()) {
3718 startDispatchCycleLocked(currentTime, connection);
3719 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720}
3721
Svet Ganov5d3bc372020-01-26 23:11:07 -08003722void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003723 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003724 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003725 return;
3726 }
3727
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003728 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003729 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003730
3731 if (downEvents.empty()) {
3732 return;
3733 }
3734
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003735 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003736 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3737 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003738 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003739
3740 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003741 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003742 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3743 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003744 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003745 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003746 target.globalScaleFactor = windowInfo->globalScaleFactor;
3747 }
3748 target.inputChannel = connection->inputChannel;
3749 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3750
hongzuo liu95785e22022-09-06 02:51:35 +00003751 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003752 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003753 switch (downEventEntry->type) {
3754 case EventEntry::Type::MOTION: {
3755 logOutboundMotionDetails("down - ",
3756 static_cast<const MotionEntry&>(*downEventEntry));
3757 break;
3758 }
3759
3760 case EventEntry::Type::KEY:
3761 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003762 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003763 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003764 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003765 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003766 case EventEntry::Type::SENSOR:
3767 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003768 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003769 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003770 break;
3771 }
3772 }
3773
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003774 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3775 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003776 }
3777
hongzuo liu95785e22022-09-06 02:51:35 +00003778 // If the outbound queue was previously empty, start the dispatch cycle going.
3779 if (wasEmpty && !connection->outboundQueue.empty()) {
3780 startDispatchCycleLocked(downTime, connection);
3781 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003782}
3783
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003784std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003785 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 ALOG_ASSERT(pointerIds.value != 0);
3787
3788 uint32_t splitPointerIndexMap[MAX_POINTERS];
3789 PointerProperties splitPointerProperties[MAX_POINTERS];
3790 PointerCoords splitPointerCoords[MAX_POINTERS];
3791
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003792 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 uint32_t splitPointerCount = 0;
3794
3795 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003796 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003798 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 uint32_t pointerId = uint32_t(pointerProperties.id);
3800 if (pointerIds.hasBit(pointerId)) {
3801 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3802 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3803 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003804 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 splitPointerCount += 1;
3806 }
3807 }
3808
3809 if (splitPointerCount != pointerIds.count()) {
3810 // This is bad. We are missing some of the pointers that we expected to deliver.
3811 // Most likely this indicates that we received an ACTION_MOVE events that has
3812 // different pointer ids than we expected based on the previous ACTION_DOWN
3813 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3814 // in this way.
3815 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003816 "we expected there to be %d pointers. This probably means we received "
3817 "a broken sequence of pointer ids from the input device.",
3818 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003819 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 }
3821
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003822 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003824 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3825 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3827 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003828 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829 uint32_t pointerId = uint32_t(pointerProperties.id);
3830 if (pointerIds.hasBit(pointerId)) {
3831 if (pointerIds.count() == 1) {
3832 // The first/last pointer went down/up.
3833 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003834 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003835 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3836 ? AMOTION_EVENT_ACTION_CANCEL
3837 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 } else {
3839 // A secondary pointer went down/up.
3840 uint32_t splitPointerIndex = 0;
3841 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3842 splitPointerIndex += 1;
3843 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003844 action = maskedAction |
3845 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846 }
3847 } else {
3848 // An unrelated pointer changed.
3849 action = AMOTION_EVENT_ACTION_MOVE;
3850 }
3851 }
3852
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003853 if (action == AMOTION_EVENT_ACTION_DOWN) {
3854 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3855 "Split motion event has mismatching downTime and eventTime for "
3856 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3857 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3858 }
3859
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003860 int32_t newId = mIdGenerator.nextId();
3861 if (ATRACE_ENABLED()) {
3862 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3863 ") to MotionEvent(id=0x%" PRIx32 ").",
3864 originalMotionEntry.id, newId);
3865 ATRACE_NAME(message.c_str());
3866 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003867 std::unique_ptr<MotionEntry> splitMotionEntry =
3868 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3869 originalMotionEntry.deviceId, originalMotionEntry.source,
3870 originalMotionEntry.displayId,
3871 originalMotionEntry.policyFlags, action,
3872 originalMotionEntry.actionButton,
3873 originalMotionEntry.flags, originalMotionEntry.metaState,
3874 originalMotionEntry.buttonState,
3875 originalMotionEntry.classification,
3876 originalMotionEntry.edgeFlags,
3877 originalMotionEntry.xPrecision,
3878 originalMotionEntry.yPrecision,
3879 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003880 originalMotionEntry.yCursorPosition, splitDownTime,
3881 splitPointerCount, splitPointerProperties,
3882 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003884 if (originalMotionEntry.injectionState) {
3885 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886 splitMotionEntry->injectionState->refCount += 1;
3887 }
3888
3889 return splitMotionEntry;
3890}
3891
3892void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003893 if (DEBUG_INBOUND_EVENT_DETAILS) {
3894 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896
Antonio Kantekf16f2832021-09-28 04:39:20 +00003897 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003899 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003901 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3902 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3903 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 } // release lock
3905
3906 if (needWake) {
3907 mLooper->wake();
3908 }
3909}
3910
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003911/**
3912 * If one of the meta shortcuts is detected, process them here:
3913 * Meta + Backspace -> generate BACK
3914 * Meta + Enter -> generate HOME
3915 * This will potentially overwrite keyCode and metaState.
3916 */
3917void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003918 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003919 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3920 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3921 if (keyCode == AKEYCODE_DEL) {
3922 newKeyCode = AKEYCODE_BACK;
3923 } else if (keyCode == AKEYCODE_ENTER) {
3924 newKeyCode = AKEYCODE_HOME;
3925 }
3926 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003927 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003928 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003929 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003930 keyCode = newKeyCode;
3931 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3932 }
3933 } else if (action == AKEY_EVENT_ACTION_UP) {
3934 // In order to maintain a consistent stream of up and down events, check to see if the key
3935 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3936 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003937 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003938 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003939 auto replacementIt = mReplacedKeys.find(replacement);
3940 if (replacementIt != mReplacedKeys.end()) {
3941 keyCode = replacementIt->second;
3942 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003943 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3944 }
3945 }
3946}
3947
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003949 if (DEBUG_INBOUND_EVENT_DETAILS) {
3950 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3951 "policyFlags=0x%x, action=0x%x, "
3952 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3953 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3954 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3955 args->downTime);
3956 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 if (!validateKeyEvent(args->action)) {
3958 return;
3959 }
3960
3961 uint32_t policyFlags = args->policyFlags;
3962 int32_t flags = args->flags;
3963 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003964 // InputDispatcher tracks and generates key repeats on behalf of
3965 // whatever notifies it, so repeatCount should always be set to 0
3966 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3968 policyFlags |= POLICY_FLAG_VIRTUAL;
3969 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 if (policyFlags & POLICY_FLAG_FUNCTION) {
3972 metaState |= AMETA_FUNCTION_ON;
3973 }
3974
3975 policyFlags |= POLICY_FLAG_TRUSTED;
3976
Michael Wright78f24442014-08-06 15:55:28 -07003977 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003978 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003979
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003981 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003982 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3983 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984
Michael Wright2b3c3302018-03-02 17:19:13 +00003985 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003987 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3988 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003989 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003990 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991
Antonio Kantekf16f2832021-09-28 04:39:20 +00003992 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 { // acquire lock
3994 mLock.lock();
3995
3996 if (shouldSendKeyToInputFilterLocked(args)) {
3997 mLock.unlock();
3998
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003999 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4001 return; // event was consumed by the filter
4002 }
4003
4004 mLock.lock();
4005 }
4006
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004007 std::unique_ptr<KeyEntry> newEntry =
4008 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
4009 args->displayId, policyFlags, args->action, flags,
4010 keyCode, args->scanCode, metaState, repeatCount,
4011 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004012
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004013 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004014 mLock.unlock();
4015 } // release lock
4016
4017 if (needWake) {
4018 mLooper->wake();
4019 }
4020}
4021
4022bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4023 return mInputFilterEnabled;
4024}
4025
4026void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004027 if (DEBUG_INBOUND_EVENT_DETAILS) {
4028 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4029 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004030 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004031 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4032 "yCursorPosition=%f, downTime=%" PRId64,
4033 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004034 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4035 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4036 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4037 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004038 for (uint32_t i = 0; i < args->pointerCount; i++) {
4039 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4040 "x=%f, y=%f, pressure=%f, size=%f, "
4041 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4042 "orientation=%f",
4043 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4044 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4045 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4046 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4047 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4048 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4049 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4050 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4051 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4052 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004055 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4056 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057 return;
4058 }
4059
4060 uint32_t policyFlags = args->policyFlags;
4061 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004062
4063 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004064 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004065 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4066 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004067 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069
Antonio Kantekf16f2832021-09-28 04:39:20 +00004070 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 { // acquire lock
4072 mLock.lock();
4073
4074 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004075 ui::Transform displayTransform;
4076 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4077 displayTransform = it->second.transform;
4078 }
4079
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080 mLock.unlock();
4081
4082 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004083 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4084 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004085 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004086 displayTransform, args->xPrecision, args->yPrecision,
4087 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004088 args->downTime, args->eventTime, args->pointerCount,
4089 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090
4091 policyFlags |= POLICY_FLAG_FILTERED;
4092 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4093 return; // event was consumed by the filter
4094 }
4095
4096 mLock.lock();
4097 }
4098
4099 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004100 std::unique_ptr<MotionEntry> newEntry =
4101 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4102 args->source, args->displayId, policyFlags,
4103 args->action, args->actionButton, args->flags,
4104 args->metaState, args->buttonState,
4105 args->classification, args->edgeFlags,
4106 args->xPrecision, args->yPrecision,
4107 args->xCursorPosition, args->yCursorPosition,
4108 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004109 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004111 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4112 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4113 !mInputFilterEnabled) {
4114 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4115 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4116 }
4117
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004118 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 mLock.unlock();
4120 } // release lock
4121
4122 if (needWake) {
4123 mLooper->wake();
4124 }
4125}
4126
Chris Yef59a2f42020-10-16 12:55:26 -07004127void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004128 if (DEBUG_INBOUND_EVENT_DETAILS) {
4129 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4130 " sensorType=%s",
4131 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004132 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004133 }
Chris Yef59a2f42020-10-16 12:55:26 -07004134
Antonio Kantekf16f2832021-09-28 04:39:20 +00004135 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004136 { // acquire lock
4137 mLock.lock();
4138
4139 // Just enqueue a new sensor event.
4140 std::unique_ptr<SensorEntry> newEntry =
4141 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4142 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4143 args->sensorType, args->accuracy,
4144 args->accuracyChanged, args->values);
4145
4146 needWake = enqueueInboundEventLocked(std::move(newEntry));
4147 mLock.unlock();
4148 } // release lock
4149
4150 if (needWake) {
4151 mLooper->wake();
4152 }
4153}
4154
Chris Yefb552902021-02-03 17:18:37 -08004155void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004156 if (DEBUG_INBOUND_EVENT_DETAILS) {
4157 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4158 args->deviceId, args->isOn);
4159 }
Chris Yefb552902021-02-03 17:18:37 -08004160 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4161}
4162
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004164 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165}
4166
4167void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004168 if (DEBUG_INBOUND_EVENT_DETAILS) {
4169 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4170 "switchMask=0x%08x",
4171 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4172 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173
4174 uint32_t policyFlags = args->policyFlags;
4175 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004176 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177}
4178
4179void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004180 if (DEBUG_INBOUND_EVENT_DETAILS) {
4181 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4182 args->deviceId);
4183 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184
Antonio Kantekf16f2832021-09-28 04:39:20 +00004185 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004187 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004189 std::unique_ptr<DeviceResetEntry> newEntry =
4190 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4191 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 } // release lock
4193
4194 if (needWake) {
4195 mLooper->wake();
4196 }
4197}
4198
Prabir Pradhan7e186182020-11-10 13:56:45 -08004199void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004200 if (DEBUG_INBOUND_EVENT_DETAILS) {
4201 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004202 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004203 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004204
Antonio Kantekf16f2832021-09-28 04:39:20 +00004205 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004206 { // acquire lock
4207 std::scoped_lock _l(mLock);
4208 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004209 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004210 needWake = enqueueInboundEventLocked(std::move(entry));
4211 } // release lock
4212
4213 if (needWake) {
4214 mLooper->wake();
4215 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004216}
4217
Prabir Pradhan5735a322022-04-11 17:23:34 +00004218InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4219 std::optional<int32_t> targetUid,
4220 InputEventInjectionSync syncMode,
4221 std::chrono::milliseconds timeout,
4222 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004223 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004224 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4225 "policyFlags=0x%08x",
4226 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4227 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004228 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004229 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230
Prabir Pradhan5735a322022-04-11 17:23:34 +00004231 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004233 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004234 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4235 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4236 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4237 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4238 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004239 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004240 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004241 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004242 }
4243
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004244 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004247 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4248 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004249 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004250 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004251 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004253 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004254 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4255 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4256 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004257 int32_t keyCode = incomingKey.getKeyCode();
4258 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004259 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004260 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004261 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004262 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004263 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4264 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4265 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004267 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4268 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004269 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004270
4271 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4272 android::base::Timer t;
4273 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4274 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4275 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4276 std::to_string(t.duration().count()).c_str());
4277 }
4278 }
4279
4280 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004281 std::unique_ptr<KeyEntry> injectedEntry =
4282 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004283 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004284 incomingKey.getDisplayId(), policyFlags, action,
4285 flags, keyCode, incomingKey.getScanCode(), metaState,
4286 incomingKey.getRepeatCount(),
4287 incomingKey.getDownTime());
4288 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004289 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 }
4291
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004292 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004293 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004294 const int32_t action = motionEvent.getAction();
4295 const bool isPointerEvent =
4296 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4297 // If a pointer event has no displayId specified, inject it to the default display.
4298 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4299 ? ADISPLAY_ID_DEFAULT
4300 : event->getDisplayId();
4301 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004302 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004303 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004304 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004305 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004306 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004307 }
4308
4309 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004310 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004311 android::base::Timer t;
4312 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4313 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4314 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4315 std::to_string(t.duration().count()).c_str());
4316 }
4317 }
4318
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004319 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4320 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4321 }
4322
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004323 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004324 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4325 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004326 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004327 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4328 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004329 displayId, policyFlags, action, actionButton,
4330 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004331 motionEvent.getButtonState(),
4332 motionEvent.getClassification(),
4333 motionEvent.getEdgeFlags(),
4334 motionEvent.getXPrecision(),
4335 motionEvent.getYPrecision(),
4336 motionEvent.getRawXCursorPosition(),
4337 motionEvent.getRawYCursorPosition(),
4338 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004339 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004340 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004341 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004342 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004343 sampleEventTimes += 1;
4344 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004345 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004346 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4347 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004348 displayId, policyFlags, action, actionButton,
4349 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004350 motionEvent.getButtonState(),
4351 motionEvent.getClassification(),
4352 motionEvent.getEdgeFlags(),
4353 motionEvent.getXPrecision(),
4354 motionEvent.getYPrecision(),
4355 motionEvent.getRawXCursorPosition(),
4356 motionEvent.getRawYCursorPosition(),
4357 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004358 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004359 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004360 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4361 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004362 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004363 }
4364 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004367 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004368 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004369 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370 }
4371
Prabir Pradhan5735a322022-04-11 17:23:34 +00004372 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004373 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 injectionState->injectionIsAsync = true;
4375 }
4376
4377 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004378 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379
4380 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004381 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004382 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004383 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 }
4385
4386 mLock.unlock();
4387
4388 if (needWake) {
4389 mLooper->wake();
4390 }
4391
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004392 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004394 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004396 if (syncMode == InputEventInjectionSync::NONE) {
4397 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398 } else {
4399 for (;;) {
4400 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004401 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402 break;
4403 }
4404
4405 nsecs_t remainingTimeout = endTime - now();
4406 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004407 if (DEBUG_INJECTION) {
4408 ALOGD("injectInputEvent - Timed out waiting for injection result "
4409 "to become available.");
4410 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004411 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412 break;
4413 }
4414
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004415 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416 }
4417
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004418 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4419 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004421 if (DEBUG_INJECTION) {
4422 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4423 injectionState->pendingForegroundDispatches);
4424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 nsecs_t remainingTimeout = endTime - now();
4426 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004427 if (DEBUG_INJECTION) {
4428 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4429 "dispatches to finish.");
4430 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004431 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432 break;
4433 }
4434
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004435 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 }
4437 }
4438 }
4439
4440 injectionState->release();
4441 } // release lock
4442
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004443 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004444 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004446
4447 return injectionResult;
4448}
4449
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004450std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004451 std::array<uint8_t, 32> calculatedHmac;
4452 std::unique_ptr<VerifiedInputEvent> result;
4453 switch (event.getType()) {
4454 case AINPUT_EVENT_TYPE_KEY: {
4455 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4456 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4457 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004458 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004459 break;
4460 }
4461 case AINPUT_EVENT_TYPE_MOTION: {
4462 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4463 VerifiedMotionEvent verifiedMotionEvent =
4464 verifiedMotionEventFromMotionEvent(motionEvent);
4465 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004466 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004467 break;
4468 }
4469 default: {
4470 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4471 return nullptr;
4472 }
4473 }
4474 if (calculatedHmac == INVALID_HMAC) {
4475 return nullptr;
4476 }
4477 if (calculatedHmac != event.getHmac()) {
4478 return nullptr;
4479 }
4480 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004481}
4482
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004483void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004484 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004485 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004487 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004488 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004491 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492 // Log the outcome since the injector did not wait for the injection result.
4493 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004494 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004495 ALOGV("Asynchronous input event injection succeeded.");
4496 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004497 case InputEventInjectionResult::TARGET_MISMATCH:
4498 ALOGV("Asynchronous input event injection target mismatch.");
4499 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004500 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004501 ALOGW("Asynchronous input event injection failed.");
4502 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004503 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004504 ALOGW("Asynchronous input event injection timed out.");
4505 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004506 case InputEventInjectionResult::PENDING:
4507 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4508 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004509 }
4510 }
4511
4512 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004513 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514 }
4515}
4516
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004517void InputDispatcher::transformMotionEntryForInjectionLocked(
4518 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004519 // Input injection works in the logical display coordinate space, but the input pipeline works
4520 // display space, so we need to transform the injected events accordingly.
4521 const auto it = mDisplayInfos.find(entry.displayId);
4522 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004523 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004524
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004525 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4526 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4527 const vec2 cursor =
4528 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4529 {entry.xCursorPosition, entry.yCursorPosition});
4530 entry.xCursorPosition = cursor.x;
4531 entry.yCursorPosition = cursor.y;
4532 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004533 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004534 entry.pointerCoords[i] =
4535 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4536 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004537 }
4538}
4539
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004540void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4541 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542 if (injectionState) {
4543 injectionState->pendingForegroundDispatches += 1;
4544 }
4545}
4546
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004547void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4548 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549 if (injectionState) {
4550 injectionState->pendingForegroundDispatches -= 1;
4551
4552 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004553 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554 }
4555 }
4556}
4557
chaviw98318de2021-05-19 16:45:23 -05004558const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004559 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004560 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004561 auto it = mWindowHandlesByDisplay.find(displayId);
4562 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004563}
4564
chaviw98318de2021-05-19 16:45:23 -05004565sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004566 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004567 if (windowHandleToken == nullptr) {
4568 return nullptr;
4569 }
4570
Arthur Hungb92218b2018-08-14 12:00:21 +08004571 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004572 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4573 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004574 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004575 return windowHandle;
4576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577 }
4578 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004579 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580}
4581
chaviw98318de2021-05-19 16:45:23 -05004582sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4583 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004584 if (windowHandleToken == nullptr) {
4585 return nullptr;
4586 }
4587
chaviw98318de2021-05-19 16:45:23 -05004588 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004589 if (windowHandle->getToken() == windowHandleToken) {
4590 return windowHandle;
4591 }
4592 }
4593 return nullptr;
4594}
4595
chaviw98318de2021-05-19 16:45:23 -05004596sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4597 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004598 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004599 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4600 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004601 if (handle->getId() == windowHandle->getId() &&
4602 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004603 if (windowHandle->getInfo()->displayId != it.first) {
4604 ALOGE("Found window %s in display %" PRId32
4605 ", but it should belong to display %" PRId32,
4606 windowHandle->getName().c_str(), it.first,
4607 windowHandle->getInfo()->displayId);
4608 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004609 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004610 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 }
4612 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004613 return nullptr;
4614}
4615
chaviw98318de2021-05-19 16:45:23 -05004616sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004617 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4618 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619}
4620
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004621bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4622 const MotionEntry& motionEntry) const {
4623 const WindowInfo& info = *window->getInfo();
4624
4625 // Skip spy window targets that are not valid for targeted injection.
4626 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004627 return false;
4628 }
4629
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004630 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4631 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4632 return false;
4633 }
4634
4635 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4636 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4637 window->getName().c_str());
4638 return false;
4639 }
4640
4641 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004642 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004643 ALOGW("Not sending touch to %s because there's no corresponding connection",
4644 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004645 return false;
4646 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004647
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004648 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004649 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004650 return false;
4651 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004652
4653 // Drop events that can't be trusted due to occlusion
4654 const auto [x, y] = resolveTouchedPosition(motionEntry);
4655 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4656 if (!isTouchTrustedLocked(occlusionInfo)) {
4657 if (DEBUG_TOUCH_OCCLUSION) {
4658 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4659 for (const auto& log : occlusionInfo.debugInfo) {
4660 ALOGD("%s", log.c_str());
4661 }
4662 }
4663 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4664 occlusionInfo.obscuringUid);
4665 return false;
4666 }
4667
4668 // Drop touch events if requested by input feature
4669 if (shouldDropInput(motionEntry, window)) {
4670 return false;
4671 }
4672
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004673 return true;
4674}
4675
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004676std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4677 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004678 auto connectionIt = mConnectionsByToken.find(token);
4679 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004680 return nullptr;
4681 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004682 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004683}
4684
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004685void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004686 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4687 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004688 // Remove all handles on a display if there are no windows left.
4689 mWindowHandlesByDisplay.erase(displayId);
4690 return;
4691 }
4692
4693 // Since we compare the pointer of input window handles across window updates, we need
4694 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004695 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4696 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4697 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004698 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004699 }
4700
chaviw98318de2021-05-19 16:45:23 -05004701 std::vector<sp<WindowInfoHandle>> newHandles;
4702 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004703 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004704 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004705 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004706 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004707 const bool canReceiveInput =
4708 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4709 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004710 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004711 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004712 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004713 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004714 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004715 }
4716
4717 if (info->displayId != displayId) {
4718 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4719 handle->getName().c_str(), displayId, info->displayId);
4720 continue;
4721 }
4722
Robert Carredd13602020-04-13 17:24:34 -07004723 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4724 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004725 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004726 oldHandle->updateFrom(handle);
4727 newHandles.push_back(oldHandle);
4728 } else {
4729 newHandles.push_back(handle);
4730 }
4731 }
4732
4733 // Insert or replace
4734 mWindowHandlesByDisplay[displayId] = newHandles;
4735}
4736
Arthur Hung72d8dc32020-03-28 00:48:39 +00004737void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004738 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004739 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004740 { // acquire lock
4741 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004742 for (const auto& [displayId, handles] : handlesPerDisplay) {
4743 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004744 }
4745 }
4746 // Wake up poll loop since it may need to make new input dispatching choices.
4747 mLooper->wake();
4748}
4749
Arthur Hungb92218b2018-08-14 12:00:21 +08004750/**
4751 * Called from InputManagerService, update window handle list by displayId that can receive input.
4752 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4753 * If set an empty list, remove all handles from the specific display.
4754 * For focused handle, check if need to change and send a cancel event to previous one.
4755 * For removed handle, check if need to send a cancel event if already in touch.
4756 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004757void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004758 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004759 if (DEBUG_FOCUS) {
4760 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004761 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004762 windowList += iwh->getName() + " ";
4763 }
4764 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766
Prabir Pradhand65552b2021-10-07 11:23:50 -07004767 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004768 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004769 const WindowInfo& info = *window->getInfo();
4770
4771 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004772 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004773 if (noInputWindow && window->getToken() != nullptr) {
4774 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4775 window->getName().c_str());
4776 window->releaseChannel();
4777 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004778
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004779 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004780 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4781 !info.inputConfig.test(
4782 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004783 "%s has feature SPY, but is not a trusted overlay.",
4784 window->getName().c_str());
4785
Prabir Pradhand65552b2021-10-07 11:23:50 -07004786 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004787 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4788 !info.inputConfig.test(
4789 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004790 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4791 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004792 }
4793
Arthur Hung72d8dc32020-03-28 00:48:39 +00004794 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004795 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004797 // Save the old windows' orientation by ID before it gets updated.
4798 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004799 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004800 oldWindowOrientations.emplace(handle->getId(),
4801 handle->getInfo()->transform.getOrientation());
4802 }
4803
chaviw98318de2021-05-19 16:45:23 -05004804 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004805
chaviw98318de2021-05-19 16:45:23 -05004806 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004807 if (mLastHoverWindowHandle &&
4808 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4809 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004810 mLastHoverWindowHandle = nullptr;
4811 }
4812
Vishnu Nairc519ff72021-01-21 08:23:08 -08004813 std::optional<FocusResolver::FocusChanges> changes =
4814 mFocusResolver.setInputWindows(displayId, windowHandles);
4815 if (changes) {
4816 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004819 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4820 mTouchStatesByDisplay.find(displayId);
4821 if (stateIt != mTouchStatesByDisplay.end()) {
4822 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004823 for (size_t i = 0; i < state.windows.size();) {
4824 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004825 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004826 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004827 ALOGD("Touched window was removed: %s in display %" PRId32,
4828 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004829 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004830 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004831 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4832 if (touchedInputChannel != nullptr) {
4833 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4834 "touched window was removed");
4835 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004836 // Since we are about to drop the touch, cancel the events for the wallpaper as
4837 // well.
4838 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004839 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4840 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004841 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4842 if (wallpaper != nullptr) {
4843 sp<Connection> wallpaperConnection =
4844 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004845 if (wallpaperConnection != nullptr) {
4846 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4847 options);
4848 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004849 }
4850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004852 state.windows.erase(state.windows.begin() + i);
4853 } else {
4854 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 }
4856 }
arthurhungb89ccb02020-12-30 16:19:01 +08004857
arthurhung6d4bed92021-03-17 11:59:33 +08004858 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004859 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004860 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004861 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004862 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004863 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4864 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004865 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004866 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004867 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004868
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004869 // Determine if the orientation of any of the input windows have changed, and cancel all
4870 // pointer events if necessary.
4871 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4872 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4873 if (newWindowHandle != nullptr &&
4874 newWindowHandle->getInfo()->transform.getOrientation() !=
4875 oldWindowOrientations[oldWindowHandle->getId()]) {
4876 std::shared_ptr<InputChannel> inputChannel =
4877 getInputChannelLocked(newWindowHandle->getToken());
4878 if (inputChannel != nullptr) {
4879 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4880 "touched window's orientation changed");
4881 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004882 }
4883 }
4884 }
4885
Arthur Hung72d8dc32020-03-28 00:48:39 +00004886 // Release information for windows that are no longer present.
4887 // This ensures that unused input channels are released promptly.
4888 // Otherwise, they might stick around until the window handle is destroyed
4889 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004890 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004891 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004892 if (DEBUG_FOCUS) {
4893 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004894 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004895 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004896 }
chaviw291d88a2019-02-14 10:33:58 -08004897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898}
4899
4900void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004901 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004902 if (DEBUG_FOCUS) {
4903 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4904 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4905 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004906 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004907 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004908 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909 } // release lock
4910
4911 // Wake up poll loop since it may need to make new input dispatching choices.
4912 mLooper->wake();
4913}
4914
Vishnu Nair599f1412021-06-21 10:39:58 -07004915void InputDispatcher::setFocusedApplicationLocked(
4916 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4917 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4918 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4919
4920 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4921 return; // This application is already focused. No need to wake up or change anything.
4922 }
4923
4924 // Set the new application handle.
4925 if (inputApplicationHandle != nullptr) {
4926 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4927 } else {
4928 mFocusedApplicationHandlesByDisplay.erase(displayId);
4929 }
4930
4931 // No matter what the old focused application was, stop waiting on it because it is
4932 // no longer focused.
4933 resetNoFocusedWindowTimeoutLocked();
4934}
4935
Tiger Huang721e26f2018-07-24 22:26:19 +08004936/**
4937 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4938 * the display not specified.
4939 *
4940 * We track any unreleased events for each window. If a window loses the ability to receive the
4941 * released event, we will send a cancel event to it. So when the focused display is changed, we
4942 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4943 * display. The display-specified events won't be affected.
4944 */
4945void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004946 if (DEBUG_FOCUS) {
4947 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4948 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004949 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004950 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004951
4952 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004953 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004954 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004955 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004956 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004957 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004958 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004959 CancelationOptions
4960 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4961 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004962 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004963 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4964 }
4965 }
4966 mFocusedDisplayId = displayId;
4967
Chris Ye3c2d6f52020-08-09 10:39:48 -07004968 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004969 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004970 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004971
Vishnu Nairad321cd2020-08-20 16:40:21 -07004972 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004973 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004974 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004975 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004976 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004977 }
4978 }
4979 }
4980
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004981 if (DEBUG_FOCUS) {
4982 logDispatchStateLocked();
4983 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004984 } // release lock
4985
4986 // Wake up poll loop since it may need to make new input dispatching choices.
4987 mLooper->wake();
4988}
4989
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004991 if (DEBUG_FOCUS) {
4992 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4993 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994
4995 bool changed;
4996 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004997 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998
4999 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
5000 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005001 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002 }
5003
5004 if (mDispatchEnabled && !enabled) {
5005 resetAndDropEverythingLocked("dispatcher is being disabled");
5006 }
5007
5008 mDispatchEnabled = enabled;
5009 mDispatchFrozen = frozen;
5010 changed = true;
5011 } else {
5012 changed = false;
5013 }
5014
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005015 if (DEBUG_FOCUS) {
5016 logDispatchStateLocked();
5017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018 } // release lock
5019
5020 if (changed) {
5021 // Wake up poll loop since it may need to make new input dispatching choices.
5022 mLooper->wake();
5023 }
5024}
5025
5026void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005027 if (DEBUG_FOCUS) {
5028 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005030
5031 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005032 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005033
5034 if (mInputFilterEnabled == enabled) {
5035 return;
5036 }
5037
5038 mInputFilterEnabled = enabled;
5039 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5040 } // release lock
5041
5042 // Wake up poll loop since there might be work to do to drop everything.
5043 mLooper->wake();
5044}
5045
Antonio Kanteka042c022022-07-06 16:51:07 -07005046bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5047 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005048 bool needWake = false;
5049 {
5050 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005051 ALOGD_IF(DEBUG_TOUCH_MODE,
5052 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5053 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5054 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5055 mTouchModePerDisplay.count(displayId) == 0
5056 ? "not set"
5057 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5058
Antonio Kantek15beb512022-06-13 22:35:41 +00005059 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5060 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005061 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005062 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005063 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005064 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5065 !recentWindowsAreOwnedByLocked(pid, uid)) {
5066 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5067 "window nor none of the previously interacted window",
5068 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005069 return false;
5070 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005071 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005072 mTouchModePerDisplay[displayId] = inTouchMode;
5073 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5074 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005075 needWake = enqueueInboundEventLocked(std::move(entry));
5076 } // release lock
5077
5078 if (needWake) {
5079 mLooper->wake();
5080 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005081 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005082}
5083
Antonio Kantek48710e42022-03-24 14:19:30 -07005084bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5085 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5086 if (focusedToken == nullptr) {
5087 return false;
5088 }
5089 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5090 return isWindowOwnedBy(windowHandle, pid, uid);
5091}
5092
5093bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5094 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5095 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5096 const sp<WindowInfoHandle> windowHandle =
5097 getWindowHandleLocked(connectionToken);
5098 return isWindowOwnedBy(windowHandle, pid, uid);
5099 }) != mInteractionConnectionTokens.end();
5100}
5101
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005102void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5103 if (opacity < 0 || opacity > 1) {
5104 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5105 return;
5106 }
5107
5108 std::scoped_lock lock(mLock);
5109 mMaximumObscuringOpacityForTouch = opacity;
5110}
5111
Arthur Hungabbb9d82021-09-01 14:52:30 +00005112std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5113 const sp<IBinder>& token) {
5114 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5115 for (TouchedWindow& w : state.windows) {
5116 if (w.windowHandle->getToken() == token) {
5117 return std::make_pair(&state, &w);
5118 }
5119 }
5120 }
5121 return std::make_pair(nullptr, nullptr);
5122}
5123
arthurhungb89ccb02020-12-30 16:19:01 +08005124bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5125 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005126 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005127 if (DEBUG_FOCUS) {
5128 ALOGD("Trivial transfer to same window.");
5129 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005130 return true;
5131 }
5132
Michael Wrightd02c5b62014-02-10 15:10:22 -08005133 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005134 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135
Arthur Hungabbb9d82021-09-01 14:52:30 +00005136 // Find the target touch state and touched window by fromToken.
5137 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5138 if (state == nullptr || touchedWindow == nullptr) {
5139 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 return false;
5141 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005142
5143 const int32_t displayId = state->displayId;
5144 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5145 if (toWindowHandle == nullptr) {
5146 ALOGW("Cannot transfer focus because to window not found.");
5147 return false;
5148 }
5149
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005150 if (DEBUG_FOCUS) {
5151 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005152 touchedWindow->windowHandle->getName().c_str(),
5153 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 }
5155
Arthur Hungabbb9d82021-09-01 14:52:30 +00005156 // Erase old window.
5157 int32_t oldTargetFlags = touchedWindow->targetFlags;
5158 BitSet32 pointerIds = touchedWindow->pointerIds;
5159 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160
Arthur Hungabbb9d82021-09-01 14:52:30 +00005161 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005162 nsecs_t downTimeInTarget = now();
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005163 int32_t newTargetFlags =
5164 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5165 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5166 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5167 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005168 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169
Arthur Hungabbb9d82021-09-01 14:52:30 +00005170 // Store the dragging window.
5171 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005172 if (pointerIds.count() != 1) {
5173 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5174 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005175 return false;
5176 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005177 // Track the pointer id for drag window and generate the drag state.
5178 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005179 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180 }
5181
Arthur Hungabbb9d82021-09-01 14:52:30 +00005182 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005183 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5184 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005185 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005186 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005187 CancelationOptions
5188 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5189 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005190 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005191 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005192 }
5193
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005194 if (DEBUG_FOCUS) {
5195 logDispatchStateLocked();
5196 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005197 } // release lock
5198
5199 // Wake up poll loop since it may need to make new input dispatching choices.
5200 mLooper->wake();
5201 return true;
5202}
5203
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005204/**
5205 * Get the touched foreground window on the given display.
5206 * Return null if there are no windows touched on that display, or if more than one foreground
5207 * window is being touched.
5208 */
5209sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5210 auto stateIt = mTouchStatesByDisplay.find(displayId);
5211 if (stateIt == mTouchStatesByDisplay.end()) {
5212 ALOGI("No touch state on display %" PRId32, displayId);
5213 return nullptr;
5214 }
5215
5216 const TouchState& state = stateIt->second;
5217 sp<WindowInfoHandle> touchedForegroundWindow;
5218 // If multiple foreground windows are touched, return nullptr
5219 for (const TouchedWindow& window : state.windows) {
5220 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5221 if (touchedForegroundWindow != nullptr) {
5222 ALOGI("Two or more foreground windows: %s and %s",
5223 touchedForegroundWindow->getName().c_str(),
5224 window.windowHandle->getName().c_str());
5225 return nullptr;
5226 }
5227 touchedForegroundWindow = window.windowHandle;
5228 }
5229 }
5230 return touchedForegroundWindow;
5231}
5232
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005233// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005234bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005235 sp<IBinder> fromToken;
5236 { // acquire lock
5237 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005238 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005239 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005240 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5241 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005242 return false;
5243 }
5244
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005245 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5246 if (from == nullptr) {
5247 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5248 return false;
5249 }
5250
5251 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005252 } // release lock
5253
5254 return transferTouchFocus(fromToken, destChannelToken);
5255}
5256
Michael Wrightd02c5b62014-02-10 15:10:22 -08005257void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005258 if (DEBUG_FOCUS) {
5259 ALOGD("Resetting and dropping all events (%s).", reason);
5260 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261
5262 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5263 synthesizeCancelationEventsForAllConnectionsLocked(options);
5264
5265 resetKeyRepeatLocked();
5266 releasePendingEventLocked();
5267 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005268 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005270 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005271 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005273 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274}
5275
5276void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005277 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 dumpDispatchStateLocked(dump);
5279
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005280 std::istringstream stream(dump);
5281 std::string line;
5282
5283 while (std::getline(stream, line, '\n')) {
5284 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005285 }
5286}
5287
Prabir Pradhan99987712020-11-10 18:43:05 -08005288std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5289 std::string dump;
5290
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005291 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5292 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005293
5294 std::string windowName = "None";
5295 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005296 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005297 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5298 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5299 : "token has capture without window";
5300 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005301 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005302
5303 return dump;
5304}
5305
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005306void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005307 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5308 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5309 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005310 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311
Tiger Huang721e26f2018-07-24 22:26:19 +08005312 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5313 dump += StringPrintf(INDENT "FocusedApplications:\n");
5314 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5315 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005316 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005317 const std::chrono::duration timeout =
5318 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005319 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005320 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005321 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005324 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005325 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005326
Vishnu Nairc519ff72021-01-21 08:23:08 -08005327 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005328 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005330 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005331 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005332 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5333 const TouchState& state = pair.second;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005334 dump += StringPrintf(INDENT2 "%d: down=%s, deviceId=%d, source=0x%08x\n",
5335 state.displayId, toString(state.down), state.deviceId,
5336 state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005337 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005338 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005339 for (size_t i = 0; i < state.windows.size(); i++) {
5340 const TouchedWindow& touchedWindow = state.windows[i];
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005341 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, "
5342 "targetFlags=0x%x, firstDownTimeInTarget=%" PRId64
5343 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005344 i, touchedWindow.windowHandle->getName().c_str(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005345 touchedWindow.pointerIds.value, touchedWindow.targetFlags,
5346 ns2ms(touchedWindow.firstDownTimeInTarget.value_or(0)));
Jeff Brownf086ddb2014-02-11 14:28:48 -08005347 }
5348 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005349 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005350 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351 }
5352 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005353 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005354 }
5355
arthurhung6d4bed92021-03-17 11:59:33 +08005356 if (mDragState) {
5357 dump += StringPrintf(INDENT "DragState:\n");
5358 mDragState->dump(dump, INDENT2);
5359 }
5360
Arthur Hungb92218b2018-08-14 12:00:21 +08005361 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005362 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5363 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5364 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5365 const auto& displayInfo = it->second;
5366 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5367 displayInfo.logicalHeight);
5368 displayInfo.transform.dump(dump, "transform", INDENT4);
5369 } else {
5370 dump += INDENT2 "No DisplayInfo found!\n";
5371 }
5372
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005373 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005374 dump += INDENT2 "Windows:\n";
5375 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005376 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5377 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005379 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005380 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005381 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005382 "applicationInfo.name=%s, "
5383 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005384 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005385 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005386 windowInfo->displayId,
5387 windowInfo->inputConfig.string().c_str(),
5388 windowInfo->alpha, windowInfo->frameLeft,
5389 windowInfo->frameTop, windowInfo->frameRight,
5390 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005391 windowInfo->applicationInfo.name.c_str(),
5392 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005393 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005394 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005395 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005396 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005397 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005398 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005399 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005400 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005401 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005402 }
5403 } else {
5404 dump += INDENT2 "Windows: <none>\n";
5405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406 }
5407 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005408 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005409 }
5410
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005411 if (!mGlobalMonitorsByDisplay.empty()) {
5412 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5413 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005414 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005417 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005418 }
5419
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005420 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005421
5422 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005423 if (!mRecentQueue.empty()) {
5424 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005425 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005426 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005427 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005428 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429 }
5430 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005431 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005432 }
5433
5434 // Dump event currently being dispatched.
5435 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005436 dump += INDENT "PendingEvent:\n";
5437 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005438 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005439 dump += StringPrintf(", age=%" PRId64 "ms\n",
5440 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005441 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005442 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005443 }
5444
5445 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005446 if (!mInboundQueue.empty()) {
5447 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005448 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005449 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005450 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005451 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005452 }
5453 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005454 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455 }
5456
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005457 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005458 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005459 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5460 const KeyReplacement& replacement = pair.first;
5461 int32_t newKeyCode = pair.second;
5462 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005463 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005464 }
5465 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005466 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005467 }
5468
Prabir Pradhancef936d2021-07-21 16:17:52 +00005469 if (!mCommandQueue.empty()) {
5470 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5471 } else {
5472 dump += INDENT "CommandQueue: <empty>\n";
5473 }
5474
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005475 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005476 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005477 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005478 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005479 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005480 connection->inputChannel->getFd().get(),
5481 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005482 connection->getWindowName().c_str(),
5483 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005484 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005486 if (!connection->outboundQueue.empty()) {
5487 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5488 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005489 dump += dumpQueue(connection->outboundQueue, currentTime);
5490
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005492 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493 }
5494
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005495 if (!connection->waitQueue.empty()) {
5496 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5497 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005498 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005500 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005501 }
5502 }
5503 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005504 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 }
5506
5507 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005508 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5509 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005510 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005511 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512 }
5513
Antonio Kantek15beb512022-06-13 22:35:41 +00005514 if (!mTouchModePerDisplay.empty()) {
5515 dump += INDENT "TouchModePerDisplay:\n";
5516 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5517 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5518 std::to_string(touchMode).c_str());
5519 }
5520 } else {
5521 dump += INDENT "TouchModePerDisplay: <none>\n";
5522 }
5523
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005524 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005525 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5526 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5527 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005528 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005529 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530}
5531
Michael Wright3dd60e22019-03-27 22:06:44 +00005532void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5533 const size_t numMonitors = monitors.size();
5534 for (size_t i = 0; i < numMonitors; i++) {
5535 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005536 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005537 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5538 dump += "\n";
5539 }
5540}
5541
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005542class LooperEventCallback : public LooperCallback {
5543public:
5544 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5545 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5546
5547private:
5548 std::function<int(int events)> mCallback;
5549};
5550
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005551Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005552 if (DEBUG_CHANNEL_CREATION) {
5553 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5554 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005556 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005557 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005558 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005559
5560 if (result) {
5561 return base::Error(result) << "Failed to open input channel pair with name " << name;
5562 }
5563
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005565 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005566 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005567 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005568 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005569 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005571 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5572 ALOGE("Created a new connection, but the token %p is already known", token.get());
5573 }
5574 mConnectionsByToken.emplace(token, connection);
5575
5576 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5577 this, std::placeholders::_1, token);
5578
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005579 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5580 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581 } // release lock
5582
5583 // Wake the looper because some connections have changed.
5584 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005585 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586}
5587
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005588Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005589 const std::string& name,
5590 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005591 std::shared_ptr<InputChannel> serverChannel;
5592 std::unique_ptr<InputChannel> clientChannel;
5593 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5594 if (result) {
5595 return base::Error(result) << "Failed to open input channel pair with name " << name;
5596 }
5597
Michael Wright3dd60e22019-03-27 22:06:44 +00005598 { // acquire lock
5599 std::scoped_lock _l(mLock);
5600
5601 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005602 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5603 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005604 }
5605
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005606 sp<Connection> connection =
5607 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005608 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005609 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005610
5611 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5612 ALOGE("Created a new connection, but the token %p is already known", token.get());
5613 }
5614 mConnectionsByToken.emplace(token, connection);
5615 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5616 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005617
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005618 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005619
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005620 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5621 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005622 }
Garfield Tan15601662020-09-22 15:32:38 -07005623
Michael Wright3dd60e22019-03-27 22:06:44 +00005624 // Wake the looper because some connections have changed.
5625 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005626 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005627}
5628
Garfield Tan15601662020-09-22 15:32:38 -07005629status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005631 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632
Garfield Tan15601662020-09-22 15:32:38 -07005633 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634 if (status) {
5635 return status;
5636 }
5637 } // release lock
5638
5639 // Wake the poll loop because removing the connection may have changed the current
5640 // synchronization state.
5641 mLooper->wake();
5642 return OK;
5643}
5644
Garfield Tan15601662020-09-22 15:32:38 -07005645status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5646 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005647 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005648 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005649 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650 return BAD_VALUE;
5651 }
5652
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005653 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005654
Michael Wrightd02c5b62014-02-10 15:10:22 -08005655 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005656 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657 }
5658
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005659 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005660
5661 nsecs_t currentTime = now();
5662 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5663
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005664 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005665 return OK;
5666}
5667
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005668void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005669 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5670 auto& [displayId, monitors] = *it;
5671 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5672 return monitor.inputChannel->getConnectionToken() == connectionToken;
5673 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005674
Michael Wright3dd60e22019-03-27 22:06:44 +00005675 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005676 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005677 } else {
5678 ++it;
5679 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005680 }
5681}
5682
Michael Wright3dd60e22019-03-27 22:06:44 +00005683status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005684 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005685 return pilferPointersLocked(token);
5686}
Michael Wright3dd60e22019-03-27 22:06:44 +00005687
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005688status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005689 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5690 if (!requestingChannel) {
5691 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5692 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005693 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005694
5695 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5696 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5697 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5698 " Ignoring.");
5699 return BAD_VALUE;
5700 }
5701
5702 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005703 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005704 // Send cancel events to all the input channels we're stealing from.
5705 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5706 "input channel stole pointer stream");
5707 options.deviceId = state.deviceId;
5708 options.displayId = state.displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005709 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005710 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005711 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005712 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005713 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005714 if (channel != nullptr && channel->getConnectionToken() != token) {
5715 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5716 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5717 canceledWindows += channel->getName();
5718 }
5719 }
5720 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5721 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5722 canceledWindows.c_str());
5723
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005724 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005725 // This only blocks relevant pointers to be sent to other windows
5726 window.isPilferingPointers = true;
5727
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005728 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005729 return OK;
5730}
5731
Prabir Pradhan99987712020-11-10 18:43:05 -08005732void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5733 { // acquire lock
5734 std::scoped_lock _l(mLock);
5735 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005736 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005737 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5738 windowHandle != nullptr ? windowHandle->getName().c_str()
5739 : "token without window");
5740 }
5741
Vishnu Nairc519ff72021-01-21 08:23:08 -08005742 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005743 if (focusedToken != windowToken) {
5744 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5745 enabled ? "enable" : "disable");
5746 return;
5747 }
5748
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005749 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005750 ALOGW("Ignoring request to %s Pointer Capture: "
5751 "window has %s requested pointer capture.",
5752 enabled ? "enable" : "disable", enabled ? "already" : "not");
5753 return;
5754 }
5755
Christine Franksb768bb42021-11-29 12:11:31 -08005756 if (enabled) {
5757 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5758 mIneligibleDisplaysForPointerCapture.end(),
5759 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5760 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5761 return;
5762 }
5763 }
5764
Prabir Pradhan99987712020-11-10 18:43:05 -08005765 setPointerCaptureLocked(enabled);
5766 } // release lock
5767
5768 // Wake the thread to process command entries.
5769 mLooper->wake();
5770}
5771
Christine Franksb768bb42021-11-29 12:11:31 -08005772void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5773 { // acquire lock
5774 std::scoped_lock _l(mLock);
5775 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5776 if (!isEligible) {
5777 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5778 }
5779 } // release lock
5780}
5781
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005782std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5783 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005784 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005785 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005786 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005787 }
5788 }
5789 }
5790 return std::nullopt;
5791}
5792
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005793sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005794 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005795 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005796 }
5797
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005798 for (const auto& [token, connection] : mConnectionsByToken) {
5799 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005800 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005801 }
5802 }
Robert Carr4e670e52018-08-15 13:26:12 -07005803
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005804 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005805}
5806
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005807std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5808 sp<Connection> connection = getConnectionLocked(connectionToken);
5809 if (connection == nullptr) {
5810 return "<nullptr>";
5811 }
5812 return connection->getInputChannelName();
5813}
5814
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005815void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005816 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005817 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005818}
5819
Prabir Pradhancef936d2021-07-21 16:17:52 +00005820void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5821 const sp<Connection>& connection, uint32_t seq,
5822 bool handled, nsecs_t consumeTime) {
5823 // Handle post-event policy actions.
5824 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5825 if (dispatchEntryIt == connection->waitQueue.end()) {
5826 return;
5827 }
5828 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5829 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5830 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5831 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5832 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5833 }
5834 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5835 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5836 connection->inputChannel->getConnectionToken(),
5837 dispatchEntry->deliveryTime, consumeTime, finishTime);
5838 }
5839
5840 bool restartEvent;
5841 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5842 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5843 restartEvent =
5844 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5845 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5846 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5847 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5848 handled);
5849 } else {
5850 restartEvent = false;
5851 }
5852
5853 // Dequeue the event and start the next cycle.
5854 // Because the lock might have been released, it is possible that the
5855 // contents of the wait queue to have been drained, so we need to double-check
5856 // a few things.
5857 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5858 if (dispatchEntryIt != connection->waitQueue.end()) {
5859 dispatchEntry = *dispatchEntryIt;
5860 connection->waitQueue.erase(dispatchEntryIt);
5861 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5862 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5863 if (!connection->responsive) {
5864 connection->responsive = isConnectionResponsive(*connection);
5865 if (connection->responsive) {
5866 // The connection was unresponsive, and now it's responsive.
5867 processConnectionResponsiveLocked(*connection);
5868 }
5869 }
5870 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005871 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005872 connection->outboundQueue.push_front(dispatchEntry);
5873 traceOutboundQueueLength(*connection);
5874 } else {
5875 releaseDispatchEntry(dispatchEntry);
5876 }
5877 }
5878
5879 // Start the next dispatch cycle for this connection.
5880 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881}
5882
Prabir Pradhancef936d2021-07-21 16:17:52 +00005883void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5884 const sp<IBinder>& newToken) {
5885 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5886 scoped_unlock unlock(mLock);
5887 mPolicy->notifyFocusChanged(oldToken, newToken);
5888 };
5889 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005890}
5891
Prabir Pradhancef936d2021-07-21 16:17:52 +00005892void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5893 auto command = [this, token, x, y]() REQUIRES(mLock) {
5894 scoped_unlock unlock(mLock);
5895 mPolicy->notifyDropWindow(token, x, y);
5896 };
5897 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005898}
5899
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005900void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5901 if (connection == nullptr) {
5902 LOG_ALWAYS_FATAL("Caller must check for nullness");
5903 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005904 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5905 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005906 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005907 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005908 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005909 return;
5910 }
5911 /**
5912 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5913 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5914 * has changed. This could cause newer entries to time out before the already dispatched
5915 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5916 * processes the events linearly. So providing information about the oldest entry seems to be
5917 * most useful.
5918 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005919 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005920 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5921 std::string reason =
5922 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005923 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005924 ns2ms(currentWait),
5925 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005926 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005927 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005928
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005929 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5930
5931 // Stop waking up for events on this connection, it is already unresponsive
5932 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005933}
5934
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005935void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5936 std::string reason =
5937 StringPrintf("%s does not have a focused window", application->getName().c_str());
5938 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005939
Prabir Pradhancef936d2021-07-21 16:17:52 +00005940 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5941 scoped_unlock unlock(mLock);
5942 mPolicy->notifyNoFocusedWindowAnr(application);
5943 };
5944 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005945}
5946
chaviw98318de2021-05-19 16:45:23 -05005947void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005948 const std::string& reason) {
5949 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5950 updateLastAnrStateLocked(windowLabel, reason);
5951}
5952
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005953void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5954 const std::string& reason) {
5955 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005956 updateLastAnrStateLocked(windowLabel, reason);
5957}
5958
5959void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5960 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005962 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005963 struct tm tm;
5964 localtime_r(&t, &tm);
5965 char timestr[64];
5966 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005967 mLastAnrState.clear();
5968 mLastAnrState += INDENT "ANR:\n";
5969 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005970 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5971 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005972 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005973}
5974
Prabir Pradhancef936d2021-07-21 16:17:52 +00005975void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5976 KeyEntry& entry) {
5977 const KeyEvent event = createKeyEvent(entry);
5978 nsecs_t delay = 0;
5979 { // release lock
5980 scoped_unlock unlock(mLock);
5981 android::base::Timer t;
5982 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5983 entry.policyFlags);
5984 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5985 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5986 std::to_string(t.duration().count()).c_str());
5987 }
5988 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005989
5990 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005991 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005992 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005993 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005994 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005995 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5996 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005998}
5999
Prabir Pradhancef936d2021-07-21 16:17:52 +00006000void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08006001 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006002 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006003 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006004 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006005 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006006 };
6007 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006008}
6009
Prabir Pradhanedd96402022-02-15 01:46:16 -08006010void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
6011 std::optional<int32_t> pid) {
6012 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006013 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006014 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006015 };
6016 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006017}
6018
6019/**
6020 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6021 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6022 * command entry to the command queue.
6023 */
6024void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6025 std::string reason) {
6026 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006027 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006028 if (connection.monitor) {
6029 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6030 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006031 pid = findMonitorPidByTokenLocked(connectionToken);
6032 } else {
6033 // The connection is a window
6034 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6035 reason.c_str());
6036 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6037 if (handle != nullptr) {
6038 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006039 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006040 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006041 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006042}
6043
6044/**
6045 * Tell the policy that a connection has become responsive so that it can stop ANR.
6046 */
6047void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6048 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006049 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006050 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006051 pid = findMonitorPidByTokenLocked(connectionToken);
6052 } else {
6053 // The connection is a window
6054 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6055 if (handle != nullptr) {
6056 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006057 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006058 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006059 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006060}
6061
Prabir Pradhancef936d2021-07-21 16:17:52 +00006062bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006063 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006064 KeyEntry& keyEntry, bool handled) {
6065 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006066 if (!handled) {
6067 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006068 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006069 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006070 return false;
6071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006072
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006073 // Get the fallback key state.
6074 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006075 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006076 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006077 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006078 connection->inputState.removeFallbackKey(originalKeyCode);
6079 }
6080
6081 if (handled || !dispatchEntry->hasForegroundTarget()) {
6082 // If the application handles the original key for which we previously
6083 // generated a fallback or if the window is not a foreground window,
6084 // then cancel the associated fallback key, if any.
6085 if (fallbackKeyCode != -1) {
6086 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006087 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6088 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6089 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6090 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6091 keyEntry.policyFlags);
6092 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006093 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006094 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006095
6096 mLock.unlock();
6097
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006098 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006099 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006100
6101 mLock.lock();
6102
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006103 // Cancel the fallback key.
6104 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006105 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006106 "application handled the original non-fallback key "
6107 "or is no longer a foreground target, "
6108 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006109 options.keyCode = fallbackKeyCode;
6110 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006111 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006112 connection->inputState.removeFallbackKey(originalKeyCode);
6113 }
6114 } else {
6115 // If the application did not handle a non-fallback key, first check
6116 // that we are in a good state to perform unhandled key event processing
6117 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006118 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006119 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006120 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6121 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6122 "since this is not an initial down. "
6123 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6124 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6125 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006126 return false;
6127 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006128
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006129 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006130 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6131 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6132 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6133 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6134 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006135 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006136
6137 mLock.unlock();
6138
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006139 bool fallback =
6140 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006141 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006142
6143 mLock.lock();
6144
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006145 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006146 connection->inputState.removeFallbackKey(originalKeyCode);
6147 return false;
6148 }
6149
6150 // Latch the fallback keycode for this key on an initial down.
6151 // The fallback keycode cannot change at any other point in the lifecycle.
6152 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006153 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006154 fallbackKeyCode = event.getKeyCode();
6155 } else {
6156 fallbackKeyCode = AKEYCODE_UNKNOWN;
6157 }
6158 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6159 }
6160
6161 ALOG_ASSERT(fallbackKeyCode != -1);
6162
6163 // Cancel the fallback key if the policy decides not to send it anymore.
6164 // We will continue to dispatch the key to the policy but we will no
6165 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006166 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6167 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006168 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6169 if (fallback) {
6170 ALOGD("Unhandled key event: Policy requested to send key %d"
6171 "as a fallback for %d, but on the DOWN it had requested "
6172 "to send %d instead. Fallback canceled.",
6173 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6174 } else {
6175 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6176 "but on the DOWN it had requested to send %d. "
6177 "Fallback canceled.",
6178 originalKeyCode, fallbackKeyCode);
6179 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006180 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006181
6182 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6183 "canceling fallback, policy no longer desires it");
6184 options.keyCode = fallbackKeyCode;
6185 synthesizeCancelationEventsForConnectionLocked(connection, options);
6186
6187 fallback = false;
6188 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006189 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006190 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006191 }
6192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006193
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006194 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6195 {
6196 std::string msg;
6197 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6198 connection->inputState.getFallbackKeys();
6199 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6200 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6201 }
6202 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6203 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006204 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006205 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006206
6207 if (fallback) {
6208 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006209 keyEntry.eventTime = event.getEventTime();
6210 keyEntry.deviceId = event.getDeviceId();
6211 keyEntry.source = event.getSource();
6212 keyEntry.displayId = event.getDisplayId();
6213 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6214 keyEntry.keyCode = fallbackKeyCode;
6215 keyEntry.scanCode = event.getScanCode();
6216 keyEntry.metaState = event.getMetaState();
6217 keyEntry.repeatCount = event.getRepeatCount();
6218 keyEntry.downTime = event.getDownTime();
6219 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006220
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006221 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6222 ALOGD("Unhandled key event: Dispatching fallback key. "
6223 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6224 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6225 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006226 return true; // restart the event
6227 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006228 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6229 ALOGD("Unhandled key event: No fallback key.");
6230 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006231
6232 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006233 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006234 }
6235 }
6236 return false;
6237}
6238
Prabir Pradhancef936d2021-07-21 16:17:52 +00006239bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006240 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006241 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006242 return false;
6243}
6244
Michael Wrightd02c5b62014-02-10 15:10:22 -08006245void InputDispatcher::traceInboundQueueLengthLocked() {
6246 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006247 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248 }
6249}
6250
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006251void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006252 if (ATRACE_ENABLED()) {
6253 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006254 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6255 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256 }
6257}
6258
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006259void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006260 if (ATRACE_ENABLED()) {
6261 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006262 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6263 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006264 }
6265}
6266
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006267void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006268 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006269
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006270 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006271 dumpDispatchStateLocked(dump);
6272
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006273 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006274 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006275 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006276 }
6277}
6278
6279void InputDispatcher::monitor() {
6280 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006281 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006282 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006283 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006284}
6285
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006286/**
6287 * Wake up the dispatcher and wait until it processes all events and commands.
6288 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6289 * this method can be safely called from any thread, as long as you've ensured that
6290 * the work you are interested in completing has already been queued.
6291 */
6292bool InputDispatcher::waitForIdle() {
6293 /**
6294 * Timeout should represent the longest possible time that a device might spend processing
6295 * events and commands.
6296 */
6297 constexpr std::chrono::duration TIMEOUT = 100ms;
6298 std::unique_lock lock(mLock);
6299 mLooper->wake();
6300 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6301 return result == std::cv_status::no_timeout;
6302}
6303
Vishnu Naire798b472020-07-23 13:52:21 -07006304/**
6305 * Sets focus to the window identified by the token. This must be called
6306 * after updating any input window handles.
6307 *
6308 * Params:
6309 * request.token - input channel token used to identify the window that should gain focus.
6310 * request.focusedToken - the token that the caller expects currently to be focused. If the
6311 * specified token does not match the currently focused window, this request will be dropped.
6312 * If the specified focused token matches the currently focused window, the call will succeed.
6313 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6314 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6315 * when requesting the focus change. This determines which request gets
6316 * precedence if there is a focus change request from another source such as pointer down.
6317 */
Vishnu Nair958da932020-08-21 17:12:37 -07006318void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6319 { // acquire lock
6320 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006321 std::optional<FocusResolver::FocusChanges> changes =
6322 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6323 if (changes) {
6324 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006325 }
6326 } // release lock
6327 // Wake up poll loop since it may need to make new input dispatching choices.
6328 mLooper->wake();
6329}
6330
Vishnu Nairc519ff72021-01-21 08:23:08 -08006331void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6332 if (changes.oldFocus) {
6333 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006334 if (focusedInputChannel) {
6335 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6336 "focus left window");
6337 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006338 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006339 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006340 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006341 if (changes.newFocus) {
6342 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006343 }
6344
Prabir Pradhan99987712020-11-10 18:43:05 -08006345 // If a window has pointer capture, then it must have focus. We need to ensure that this
6346 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6347 // If the window loses focus before it loses pointer capture, then the window can be in a state
6348 // where it has pointer capture but not focus, violating the contract. Therefore we must
6349 // dispatch the pointer capture event before the focus event. Since focus events are added to
6350 // the front of the queue (above), we add the pointer capture event to the front of the queue
6351 // after the focus events are added. This ensures the pointer capture event ends up at the
6352 // front.
6353 disablePointerCaptureForcedLocked();
6354
Vishnu Nairc519ff72021-01-21 08:23:08 -08006355 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006356 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006357 }
6358}
Vishnu Nair958da932020-08-21 17:12:37 -07006359
Prabir Pradhan99987712020-11-10 18:43:05 -08006360void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006361 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006362 return;
6363 }
6364
6365 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6366
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006367 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006368 setPointerCaptureLocked(false);
6369 }
6370
6371 if (!mWindowTokenWithPointerCapture) {
6372 // No need to send capture changes because no window has capture.
6373 return;
6374 }
6375
6376 if (mPendingEvent != nullptr) {
6377 // Move the pending event to the front of the queue. This will give the chance
6378 // for the pending event to be dropped if it is a captured event.
6379 mInboundQueue.push_front(mPendingEvent);
6380 mPendingEvent = nullptr;
6381 }
6382
6383 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006384 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006385 mInboundQueue.push_front(std::move(entry));
6386}
6387
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006388void InputDispatcher::setPointerCaptureLocked(bool enable) {
6389 mCurrentPointerCaptureRequest.enable = enable;
6390 mCurrentPointerCaptureRequest.seq++;
6391 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006392 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006393 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006394 };
6395 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006396}
6397
Vishnu Nair599f1412021-06-21 10:39:58 -07006398void InputDispatcher::displayRemoved(int32_t displayId) {
6399 { // acquire lock
6400 std::scoped_lock _l(mLock);
6401 // Set an empty list to remove all handles from the specific display.
6402 setInputWindowsLocked(/* window handles */ {}, displayId);
6403 setFocusedApplicationLocked(displayId, nullptr);
6404 // Call focus resolver to clean up stale requests. This must be called after input windows
6405 // have been removed for the removed display.
6406 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006407 // Reset pointer capture eligibility, regardless of previous state.
6408 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006409 // Remove the associated touch mode state.
6410 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006411 } // release lock
6412
6413 // Wake up poll loop since it may need to make new input dispatching choices.
6414 mLooper->wake();
6415}
6416
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006417void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6418 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006419 // The listener sends the windows as a flattened array. Separate the windows by display for
6420 // more convenient parsing.
6421 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006422 for (const auto& info : windowInfos) {
6423 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006424 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006425 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006426
6427 { // acquire lock
6428 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006429
6430 // Ensure that we have an entry created for all existing displays so that if a displayId has
6431 // no windows, we can tell that the windows were removed from the display.
6432 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6433 handlesPerDisplay[displayId];
6434 }
6435
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006436 mDisplayInfos.clear();
6437 for (const auto& displayInfo : displayInfos) {
6438 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6439 }
6440
6441 for (const auto& [displayId, handles] : handlesPerDisplay) {
6442 setInputWindowsLocked(handles, displayId);
6443 }
6444 }
6445 // Wake up poll loop since it may need to make new input dispatching choices.
6446 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006447}
6448
Vishnu Nair062a8672021-09-03 16:07:44 -07006449bool InputDispatcher::shouldDropInput(
6450 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006451 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6452 (windowHandle->getInfo()->inputConfig.test(
6453 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006454 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006455 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6456 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006457 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006458 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006459 windowHandle->getInfo()->displayId);
6460 return true;
6461 }
6462 return false;
6463}
6464
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006465void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6466 const std::vector<gui::WindowInfo>& windowInfos,
6467 const std::vector<DisplayInfo>& displayInfos) {
6468 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6469}
6470
Arthur Hungdfd528e2021-12-08 13:23:04 +00006471void InputDispatcher::cancelCurrentTouch() {
6472 {
6473 std::scoped_lock _l(mLock);
6474 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6475 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6476 "cancel current touch");
6477 synthesizeCancelationEventsForAllConnectionsLocked(options);
6478
6479 mTouchStatesByDisplay.clear();
6480 mLastHoverWindowHandle.clear();
6481 }
6482 // Wake up poll loop since there might be work to do.
6483 mLooper->wake();
6484}
6485
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006486void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6487 std::scoped_lock _l(mLock);
6488 mMonitorDispatchingTimeout = timeout;
6489}
6490
Garfield Tane84e6f92019-08-29 17:28:41 -07006491} // namespace android::inputdispatcher