blob: 4091310193c41ace6be353014e12006716c9ee96 [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) &&
Prabir Pradhane5626962022-10-27 20:30:53 +0000482 isStylusToolType(entry.pointerProperties[pointerIndex].toolType);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700483}
484
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000485// Determines if the given window can be targeted as InputTarget::FLAG_FOREGROUND.
486// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
487// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
488// be sent to such a window, but it is not a foreground event and doesn't use
489// InputTarget::FLAG_FOREGROUND.
490bool canReceiveForegroundTouches(const WindowInfo& info) {
491 // A non-touchable window can still receive touch events (e.g. in the case of
492 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
493 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
494}
495
Antonio Kantek48710e42022-03-24 14:19:30 -0700496bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
497 if (windowHandle == nullptr) {
498 return false;
499 }
500 const WindowInfo* windowInfo = windowHandle->getInfo();
501 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
502 return true;
503 }
504 return false;
505}
506
Prabir Pradhan5735a322022-04-11 17:23:34 +0000507// Checks targeted injection using the window's owner's uid.
508// Returns an empty string if an entry can be sent to the given window, or an error message if the
509// entry is a targeted injection whose uid target doesn't match the window owner.
510std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
511 const EventEntry& entry) {
512 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
513 // The event was not injected, or the injected event does not target a window.
514 return {};
515 }
516 const int32_t uid = *entry.injectionState->targetUid;
517 if (window == nullptr) {
518 return StringPrintf("No valid window target for injection into uid %d.", uid);
519 }
520 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
521 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
522 "owned by uid %d.",
523 uid, window->getName().c_str(), window->getInfo()->ownerUid);
524 }
525 return {};
526}
527
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700528Point resolveTouchedPosition(const MotionEntry& entry) {
529 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
530 // Always dispatch mouse events to cursor position.
531 if (isFromMouse) {
532 return Point(static_cast<int32_t>(entry.xCursorPosition),
533 static_cast<int32_t>(entry.yCursorPosition));
534 }
535
536 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
537 return Point(static_cast<int32_t>(
538 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X)),
539 static_cast<int32_t>(
540 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)));
541}
542
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700543std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
544 if (eventEntry.type == EventEntry::Type::KEY) {
545 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
546 return keyEntry.downTime;
547 } else if (eventEntry.type == EventEntry::Type::MOTION) {
548 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
549 return motionEntry.downTime;
550 }
551 return std::nullopt;
552}
553
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000554} // namespace
555
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556// --- InputDispatcher ---
557
Garfield Tan00f511d2019-06-12 16:55:40 -0700558InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800559 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
560
561InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
562 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700563 : mPolicy(policy),
564 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700565 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800566 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700567 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700568 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700569 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800570 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700571 mDispatchEnabled(false),
572 mDispatchFrozen(false),
573 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100574 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000575 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800576 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800577 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000578 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000579 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700580 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800581 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800582
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700583 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700584#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700585 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700586#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700587 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800588 policy->getDispatcherConfiguration(&mConfig);
589}
590
591InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000592 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593
Prabir Pradhancef936d2021-07-21 16:17:52 +0000594 resetKeyRepeatLocked();
595 releasePendingEventLocked();
596 drainInboundQueueLocked();
597 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000599 while (!mConnectionsByToken.empty()) {
600 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000601 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
602 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800603 }
604}
605
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700606status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700607 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700608 return ALREADY_EXISTS;
609 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700610 mThread = std::make_unique<InputThread>(
611 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
612 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700613}
614
615status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700616 if (mThread && mThread->isCallingThread()) {
617 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700618 return INVALID_OPERATION;
619 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700620 mThread.reset();
621 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700622}
623
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700625 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800627 std::scoped_lock _l(mLock);
628 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629
630 // Run a dispatch loop if there are no pending commands.
631 // The dispatch loop might enqueue commands to run afterwards.
632 if (!haveCommandsLocked()) {
633 dispatchOnceInnerLocked(&nextWakeupTime);
634 }
635
636 // Run all pending commands if there are any.
637 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000638 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700639 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800640 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800641
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700642 // If we are still waiting for ack on some events,
643 // we might have to wake up earlier to check if an app is anr'ing.
644 const nsecs_t nextAnrCheck = processAnrsLocked();
645 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
646
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800647 // We are about to enter an infinitely long sleep, because we have no commands or
648 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700649 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800650 mDispatcherEnteredIdle.notify_all();
651 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652 } // release lock
653
654 // Wait for callback or timeout or wake. (make sure we round up, not down)
655 nsecs_t currentTime = now();
656 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
657 mLooper->pollOnce(timeoutMillis);
658}
659
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700660/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500661 * Raise ANR if there is no focused window.
662 * Before the ANR is raised, do a final state check:
663 * 1. The currently focused application must be the same one we are waiting for.
664 * 2. Ensure we still don't have a focused window.
665 */
666void InputDispatcher::processNoFocusedWindowAnrLocked() {
667 // Check if the application that we are waiting for is still focused.
668 std::shared_ptr<InputApplicationHandle> focusedApplication =
669 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
670 if (focusedApplication == nullptr ||
671 focusedApplication->getApplicationToken() !=
672 mAwaitedFocusedApplication->getApplicationToken()) {
673 // Unexpected because we should have reset the ANR timer when focused application changed
674 ALOGE("Waited for a focused window, but focused application has already changed to %s",
675 focusedApplication->getName().c_str());
676 return; // The focused application has changed.
677 }
678
chaviw98318de2021-05-19 16:45:23 -0500679 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500680 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
681 if (focusedWindowHandle != nullptr) {
682 return; // We now have a focused window. No need for ANR.
683 }
684 onAnrLocked(mAwaitedFocusedApplication);
685}
686
687/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700688 * Check if any of the connections' wait queues have events that are too old.
689 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
690 * Return the time at which we should wake up next.
691 */
692nsecs_t InputDispatcher::processAnrsLocked() {
693 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700694 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700695 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
696 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
697 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500698 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700699 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500700 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700701 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700702 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500703 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700704 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
705 }
706 }
707
708 // Check if any connection ANRs are due
709 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
710 if (currentTime < nextAnrCheck) { // most likely scenario
711 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
712 }
713
714 // If we reached here, we have an unresponsive connection.
715 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
716 if (connection == nullptr) {
717 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
718 return nextAnrCheck;
719 }
720 connection->responsive = false;
721 // Stop waking up for this unresponsive connection
722 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000723 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700724 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700725}
726
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800727std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
728 const sp<Connection>& connection) {
729 if (connection->monitor) {
730 return mMonitorDispatchingTimeout;
731 }
732 const sp<WindowInfoHandle> window =
733 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700734 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500735 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700736 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500737 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700738}
739
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
741 nsecs_t currentTime = now();
742
Jeff Browndc5992e2014-04-11 01:27:26 -0700743 // Reset the key repeat timer whenever normal dispatch is suspended while the
744 // device is in a non-interactive state. This is to ensure that we abort a key
745 // repeat if the device is just coming out of sleep.
746 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 resetKeyRepeatLocked();
748 }
749
750 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
751 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100752 if (DEBUG_FOCUS) {
753 ALOGD("Dispatch frozen. Waiting some more.");
754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 return;
756 }
757
758 // Optimize latency of app switches.
759 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
760 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
761 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
762 if (mAppSwitchDueTime < *nextWakeupTime) {
763 *nextWakeupTime = mAppSwitchDueTime;
764 }
765
766 // Ready to start a new event.
767 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700768 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700769 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800770 if (isAppSwitchDue) {
771 // The inbound queue is empty so the app switch key we were waiting
772 // for will never arrive. Stop waiting for it.
773 resetPendingAppSwitchLocked(false);
774 isAppSwitchDue = false;
775 }
776
777 // Synthesize a key repeat if appropriate.
778 if (mKeyRepeatState.lastKeyEntry) {
779 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
780 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
781 } else {
782 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
783 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
784 }
785 }
786 }
787
788 // Nothing to do if there is no pending event.
789 if (!mPendingEvent) {
790 return;
791 }
792 } else {
793 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700794 mPendingEvent = mInboundQueue.front();
795 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800796 traceInboundQueueLengthLocked();
797 }
798
799 // Poke user activity for this event.
800 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700801 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803 }
804
805 // Now we have an event to dispatch.
806 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700807 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700809 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700811 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700813 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 }
815
816 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700817 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 }
819
820 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700821 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700822 const ConfigurationChangedEntry& typedEntry =
823 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700825 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700826 break;
827 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800828
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700829 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700830 const DeviceResetEntry& typedEntry =
831 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700832 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700833 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700834 break;
835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100837 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700838 std::shared_ptr<FocusEntry> typedEntry =
839 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100840 dispatchFocusLocked(currentTime, typedEntry);
841 done = true;
842 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
843 break;
844 }
845
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700846 case EventEntry::Type::TOUCH_MODE_CHANGED: {
847 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
848 dispatchTouchModeChangeLocked(currentTime, typedEntry);
849 done = true;
850 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
851 break;
852 }
853
Prabir Pradhan99987712020-11-10 18:43:05 -0800854 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
855 const auto typedEntry =
856 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
857 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
858 done = true;
859 break;
860 }
861
arthurhungb89ccb02020-12-30 16:19:01 +0800862 case EventEntry::Type::DRAG: {
863 std::shared_ptr<DragEntry> typedEntry =
864 std::static_pointer_cast<DragEntry>(mPendingEvent);
865 dispatchDragLocked(currentTime, typedEntry);
866 done = true;
867 break;
868 }
869
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700870 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700871 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700872 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700873 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700874 resetPendingAppSwitchLocked(true);
875 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700876 } else if (dropReason == DropReason::NOT_DROPPED) {
877 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700878 }
879 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700880 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700881 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700882 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
884 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700885 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700886 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700887 break;
888 }
889
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700890 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700891 std::shared_ptr<MotionEntry> motionEntry =
892 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700893 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
894 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700896 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700897 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700898 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700899 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
900 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700901 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700902 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
Chris Yef59a2f42020-10-16 12:55:26 -0700905
906 case EventEntry::Type::SENSOR: {
907 std::shared_ptr<SensorEntry> sensorEntry =
908 std::static_pointer_cast<SensorEntry>(mPendingEvent);
909 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
910 dropReason = DropReason::APP_SWITCH;
911 }
912 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
913 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
914 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
915 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
916 dropReason = DropReason::STALE;
917 }
918 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
919 done = true;
920 break;
921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 }
923
924 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700925 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700926 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 }
Michael Wright3a981722015-06-10 15:26:13 +0100928 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929
930 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -0700931 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 }
933}
934
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800935bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
936 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
937}
938
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700939/**
940 * Return true if the events preceding this incoming motion event should be dropped
941 * Return false otherwise (the default behaviour)
942 */
943bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700944 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700945 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946
947 // Optimize case where the current application is unresponsive and the user
948 // decides to touch a window in a different application.
949 // If the application takes too long to catch up then we drop all events preceding
950 // the touch into the other window.
951 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700952 const int32_t displayId = motionEntry.displayId;
953 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700954 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700955
chaviw98318de2021-05-19 16:45:23 -0500956 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700957 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700958 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700959 touchedWindowHandle->getApplicationToken() !=
960 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700961 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700962 ALOGI("Pruning input queue because user touched a different application while waiting "
963 "for %s",
964 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700965 return true;
966 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700967
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800968 // Alternatively, maybe there's a spy window that could handle this event.
969 const std::vector<sp<WindowInfoHandle>> touchedSpies =
970 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
971 for (const auto& windowHandle : touchedSpies) {
972 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000973 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800974 // This spy window could take more input. Drop all events preceding this
975 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700976 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800977 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700978 mAwaitedFocusedApplication->getName().c_str());
979 return true;
980 }
981 }
982 }
983
984 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
985 // yet been processed by some connections, the dispatcher will wait for these motion
986 // events to be processed before dispatching the key event. This is because these motion events
987 // may cause a new window to be launched, which the user might expect to receive focus.
988 // To prevent waiting forever for such events, just send the key to the currently focused window
989 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
990 ALOGD("Received a new pointer down event, stop waiting for events to process and "
991 "just send the pending key event to the focused window.");
992 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700993 }
994 return false;
995}
996
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700997bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700998 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700999 mInboundQueue.push_back(std::move(newEntry));
1000 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 traceInboundQueueLengthLocked();
1002
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001003 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001004 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001005 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1006 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001007 // Optimize app switch latency.
1008 // If the application takes too long to catch up then we drop all events preceding
1009 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001010 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001011 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001012 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001013 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001014 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001015 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001016 if (DEBUG_APP_SWITCH) {
1017 ALOGD("App switch is pending!");
1018 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001019 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020 mAppSwitchSawKeyDown = false;
1021 needWake = true;
1022 }
1023 }
1024 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001025
1026 // If a new up event comes in, and the pending event with same key code has been asked
1027 // to try again later because of the policy. We have to reset the intercept key wake up
1028 // time for it may have been handled in the policy and could be dropped.
1029 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1030 mPendingEvent->type == EventEntry::Type::KEY) {
1031 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1032 if (pendingKey.keyCode == keyEntry.keyCode &&
1033 pendingKey.interceptKeyResult ==
1034 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1035 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1036 pendingKey.interceptKeyWakeupTime = 0;
1037 needWake = true;
1038 }
1039 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001040 break;
1041 }
1042
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001043 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001044 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1045 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001046 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1047 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001048 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001050 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001052 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001053 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1054 break;
1055 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001056 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001057 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001058 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001059 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001060 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1061 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001062 // nothing to do
1063 break;
1064 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 }
1066
1067 return needWake;
1068}
1069
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001070void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001071 // Do not store sensor event in recent queue to avoid flooding the queue.
1072 if (entry->type != EventEntry::Type::SENSOR) {
1073 mRecentQueue.push_back(entry);
1074 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001075 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001076 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077 }
1078}
1079
chaviw98318de2021-05-19 16:45:23 -05001080sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1081 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001082 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001083 bool addOutsideTargets,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07001084 bool ignoreDragWindow) const {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001085 if (addOutsideTargets && touchState == nullptr) {
1086 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001089 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001090 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001091 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001092 continue;
1093 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001095 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001096 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001097 return windowHandle;
1098 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001099
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001100 if (addOutsideTargets &&
1101 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001102 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1103 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104 }
1105 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001106 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001107}
1108
Prabir Pradhand65552b2021-10-07 11:23:50 -07001109std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1110 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001111 // Traverse windows from front to back and gather the touched spy windows.
1112 std::vector<sp<WindowInfoHandle>> spyWindows;
1113 const auto& windowHandles = getWindowHandlesLocked(displayId);
1114 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1115 const WindowInfo& info = *windowHandle->getInfo();
1116
Prabir Pradhand65552b2021-10-07 11:23:50 -07001117 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001118 continue;
1119 }
1120 if (!info.isSpy()) {
1121 // The first touched non-spy window was found, so return the spy windows touched so far.
1122 return spyWindows;
1123 }
1124 spyWindows.push_back(windowHandle);
1125 }
1126 return spyWindows;
1127}
1128
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001129void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 const char* reason;
1131 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001132 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001133 if (DEBUG_INBOUND_EVENT_DETAILS) {
1134 ALOGD("Dropped event because policy consumed it.");
1135 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001136 reason = "inbound event was dropped because the policy consumed it";
1137 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001138 case DropReason::DISABLED:
1139 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001140 ALOGI("Dropped event because input dispatch is disabled.");
1141 }
1142 reason = "inbound event was dropped because input dispatch is disabled";
1143 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001144 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001145 ALOGI("Dropped event because of pending overdue app switch.");
1146 reason = "inbound event was dropped because of pending overdue app switch";
1147 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001148 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001149 ALOGI("Dropped event because the current application is not responding and the user "
1150 "has started interacting with a different application.");
1151 reason = "inbound event was dropped because the current application is not responding "
1152 "and the user has started interacting with a different application";
1153 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001154 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001155 ALOGI("Dropped event because it is stale.");
1156 reason = "inbound event was dropped because it is stale";
1157 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001158 case DropReason::NO_POINTER_CAPTURE:
1159 ALOGI("Dropped event because there is no window with Pointer Capture.");
1160 reason = "inbound event was dropped because there is no window with Pointer Capture";
1161 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001162 case DropReason::NOT_DROPPED: {
1163 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001164 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 }
1167
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001168 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001169 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1171 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001172 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001174 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001175 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1176 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001177 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1178 synthesizeCancelationEventsForAllConnectionsLocked(options);
1179 } else {
1180 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1181 synthesizeCancelationEventsForAllConnectionsLocked(options);
1182 }
1183 break;
1184 }
Chris Yef59a2f42020-10-16 12:55:26 -07001185 case EventEntry::Type::SENSOR: {
1186 break;
1187 }
arthurhungb89ccb02020-12-30 16:19:01 +08001188 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1189 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001190 break;
1191 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001192 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001193 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001194 case EventEntry::Type::CONFIGURATION_CHANGED:
1195 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001196 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001197 break;
1198 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 }
1200}
1201
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001202static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001203 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1204 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205}
1206
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001207bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1208 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1209 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1210 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211}
1212
1213bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001214 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001215}
1216
1217void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001218 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001220 if (DEBUG_APP_SWITCH) {
1221 if (handled) {
1222 ALOGD("App switch has arrived.");
1223 } else {
1224 ALOGD("App switch was abandoned.");
1225 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227}
1228
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001230 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231}
1232
Prabir Pradhancef936d2021-07-21 16:17:52 +00001233bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001234 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 return false;
1236 }
1237
1238 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001239 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001240 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001241 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1242 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001243 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 return true;
1245}
1246
Prabir Pradhancef936d2021-07-21 16:17:52 +00001247void InputDispatcher::postCommandLocked(Command&& command) {
1248 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249}
1250
1251void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001252 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001253 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001254 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 releaseInboundEventLocked(entry);
1256 }
1257 traceInboundQueueLengthLocked();
1258}
1259
1260void InputDispatcher::releasePendingEventLocked() {
1261 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001263 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 }
1265}
1266
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001267void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001269 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001270 if (DEBUG_DISPATCH_CYCLE) {
1271 ALOGD("Injected inbound event was dropped.");
1272 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001273 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 }
1275 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001276 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 }
1278 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279}
1280
1281void InputDispatcher::resetKeyRepeatLocked() {
1282 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001283 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 }
1285}
1286
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001287std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1288 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289
Michael Wright2e732952014-09-24 13:26:59 -07001290 uint32_t policyFlags = entry->policyFlags &
1291 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001293 std::shared_ptr<KeyEntry> newEntry =
1294 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1295 entry->source, entry->displayId, policyFlags, entry->action,
1296 entry->flags, entry->keyCode, entry->scanCode,
1297 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001299 newEntry->syntheticRepeat = true;
1300 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001302 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303}
1304
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001305bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001306 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001307 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1308 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1309 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310
1311 // Reset key repeating in case a keyboard device was added or removed or something.
1312 resetKeyRepeatLocked();
1313
1314 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001315 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1316 scoped_unlock unlock(mLock);
1317 mPolicy->notifyConfigurationChanged(eventTime);
1318 };
1319 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 return true;
1321}
1322
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001323bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1324 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001325 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1326 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1327 entry.deviceId);
1328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329
liushenxiang42232912021-05-21 20:24:09 +08001330 // Reset key repeating in case a keyboard device was disabled or enabled.
1331 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1332 resetKeyRepeatLocked();
1333 }
1334
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001335 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001336 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 synthesizeCancelationEventsForAllConnectionsLocked(options);
1338 return true;
1339}
1340
Vishnu Nairad321cd2020-08-20 16:40:21 -07001341void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001342 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001343 if (mPendingEvent != nullptr) {
1344 // Move the pending event to the front of the queue. This will give the chance
1345 // for the pending event to get dispatched to the newly focused window
1346 mInboundQueue.push_front(mPendingEvent);
1347 mPendingEvent = nullptr;
1348 }
1349
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001350 std::unique_ptr<FocusEntry> focusEntry =
1351 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1352 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001353
1354 // This event should go to the front of the queue, but behind all other focus events
1355 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001356 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001357 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001358 [](const std::shared_ptr<EventEntry>& event) {
1359 return event->type == EventEntry::Type::FOCUS;
1360 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001361
1362 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001363 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001364}
1365
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001366void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001367 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001368 if (channel == nullptr) {
1369 return; // Window has gone away
1370 }
1371 InputTarget target;
1372 target.inputChannel = channel;
1373 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1374 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001375 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1376 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001377 std::string reason = std::string("reason=").append(entry->reason);
1378 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001379 dispatchEventLocked(currentTime, entry, {target});
1380}
1381
Prabir Pradhan99987712020-11-10 18:43:05 -08001382void InputDispatcher::dispatchPointerCaptureChangedLocked(
1383 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1384 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001385 dropReason = DropReason::NOT_DROPPED;
1386
Prabir Pradhan99987712020-11-10 18:43:05 -08001387 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001388 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001389
1390 if (entry->pointerCaptureRequest.enable) {
1391 // Enable Pointer Capture.
1392 if (haveWindowWithPointerCapture &&
1393 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001394 // This can happen if pointer capture is disabled and re-enabled before we notify the
1395 // app of the state change, so there is no need to notify the app.
1396 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1397 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001398 }
1399 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001400 // This can happen if a window requests capture and immediately releases capture.
1401 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001402 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001403 return;
1404 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001405 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1406 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1407 return;
1408 }
1409
Vishnu Nairc519ff72021-01-21 08:23:08 -08001410 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001411 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1412 mWindowTokenWithPointerCapture = token;
1413 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001414 // Disable Pointer Capture.
1415 // We do not check if the sequence number matches for requests to disable Pointer Capture
1416 // for two reasons:
1417 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1418 // to disable capture with the same sequence number: one generated by
1419 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1420 // Capture being disabled in InputReader.
1421 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1422 // actual Pointer Capture state that affects events being generated by input devices is
1423 // in InputReader.
1424 if (!haveWindowWithPointerCapture) {
1425 // Pointer capture was already forcefully disabled because of focus change.
1426 dropReason = DropReason::NOT_DROPPED;
1427 return;
1428 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001429 token = mWindowTokenWithPointerCapture;
1430 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001431 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001432 setPointerCaptureLocked(false);
1433 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001434 }
1435
1436 auto channel = getInputChannelLocked(token);
1437 if (channel == nullptr) {
1438 // Window has gone away, clean up Pointer Capture state.
1439 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001440 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001441 setPointerCaptureLocked(false);
1442 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001443 return;
1444 }
1445 InputTarget target;
1446 target.inputChannel = channel;
1447 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1448 entry->dispatchInProgress = true;
1449 dispatchEventLocked(currentTime, entry, {target});
1450
1451 dropReason = DropReason::NOT_DROPPED;
1452}
1453
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001454void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1455 const std::shared_ptr<TouchModeEntry>& entry) {
1456 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001457 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001458 if (windowHandles.empty()) {
1459 return;
1460 }
1461 const std::vector<InputTarget> inputTargets =
1462 getInputTargetsFromWindowHandlesLocked(windowHandles);
1463 if (inputTargets.empty()) {
1464 return;
1465 }
1466 entry->dispatchInProgress = true;
1467 dispatchEventLocked(currentTime, entry, inputTargets);
1468}
1469
1470std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1471 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1472 std::vector<InputTarget> inputTargets;
1473 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001474 const sp<IBinder>& token = handle->getToken();
1475 if (token == nullptr) {
1476 continue;
1477 }
1478 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1479 if (channel == nullptr) {
1480 continue; // Window has gone away
1481 }
1482 InputTarget target;
1483 target.inputChannel = channel;
1484 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1485 inputTargets.push_back(target);
1486 }
1487 return inputTargets;
1488}
1489
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001490bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001491 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001493 if (!entry->dispatchInProgress) {
1494 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1495 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1496 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1497 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001498 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 // We have seen two identical key downs in a row which indicates that the device
1500 // driver is automatically generating key repeats itself. We take note of the
1501 // repeat here, but we disable our own next key repeat timer since it is clear that
1502 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001503 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1504 // Make sure we don't get key down from a different device. If a different
1505 // device Id has same key pressed down, the new device Id will replace the
1506 // current one to hold the key repeat with repeat count reset.
1507 // In the future when got a KEY_UP on the device id, drop it and do not
1508 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1510 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001511 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 } else {
1513 // Not a repeat. Save key down state in case we do see a repeat later.
1514 resetKeyRepeatLocked();
1515 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1516 }
1517 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001518 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1519 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001520 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001521 if (DEBUG_INBOUND_EVENT_DETAILS) {
1522 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1523 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001524 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 resetKeyRepeatLocked();
1526 }
1527
1528 if (entry->repeatCount == 1) {
1529 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1530 } else {
1531 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1532 }
1533
1534 entry->dispatchInProgress = true;
1535
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001536 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 }
1538
1539 // Handle case where the policy asked us to try again later last time.
1540 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1541 if (currentTime < entry->interceptKeyWakeupTime) {
1542 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1543 *nextWakeupTime = entry->interceptKeyWakeupTime;
1544 }
1545 return false; // wait until next wakeup
1546 }
1547 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1548 entry->interceptKeyWakeupTime = 0;
1549 }
1550
1551 // Give the policy a chance to intercept the key.
1552 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1553 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001554 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001555 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001556
1557 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1558 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1559 };
1560 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 return false; // wait for the command to run
1562 } else {
1563 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1564 }
1565 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001566 if (*dropReason == DropReason::NOT_DROPPED) {
1567 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 }
1569 }
1570
1571 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001572 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001573 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001574 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1575 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001576 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 return true;
1578 }
1579
1580 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001581 InputEventInjectionResult injectionResult;
1582 sp<WindowInfoHandle> focusedWindow =
1583 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1584 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001585 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 return false;
1587 }
1588
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001589 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001590 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 return true;
1592 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001593 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1594
1595 std::vector<InputTarget> inputTargets;
1596 addWindowTargetLocked(focusedWindow,
1597 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1598 BitSet32(0), getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001600 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001601 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001602
1603 // Dispatch the key.
1604 dispatchEventLocked(currentTime, entry, inputTargets);
1605 return true;
1606}
1607
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001608void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001609 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1610 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1611 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1612 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1613 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1614 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1615 entry.metaState, entry.repeatCount, entry.downTime);
1616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617}
1618
Prabir Pradhancef936d2021-07-21 16:17:52 +00001619void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1620 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001621 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001622 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1623 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1624 "source=0x%x, sensorType=%s",
1625 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001626 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001627 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001628 auto command = [this, entry]() REQUIRES(mLock) {
1629 scoped_unlock unlock(mLock);
1630
1631 if (entry->accuracyChanged) {
1632 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1633 }
1634 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1635 entry->hwTimestamp, entry->values);
1636 };
1637 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001638}
1639
1640bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001641 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1642 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001643 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001644 }
Chris Yef59a2f42020-10-16 12:55:26 -07001645 { // acquire lock
1646 std::scoped_lock _l(mLock);
1647
1648 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1649 std::shared_ptr<EventEntry> entry = *it;
1650 if (entry->type == EventEntry::Type::SENSOR) {
1651 it = mInboundQueue.erase(it);
1652 releaseInboundEventLocked(entry);
1653 }
1654 }
1655 }
1656 return true;
1657}
1658
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001659bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001660 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001661 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001662 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001663 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 entry->dispatchInProgress = true;
1665
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001666 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 }
1668
1669 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001670 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001671 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001672 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1673 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 return true;
1675 }
1676
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001677 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678
1679 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001680 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681
1682 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001683 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684 if (isPointerEvent) {
1685 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001686
1687 if (mDragState &&
1688 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1689 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1690 pilferPointersLocked(mDragState->dragWindow->getToken());
1691 }
1692
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001693 std::vector<TouchedWindow> touchedWindows =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001694 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001695 /*byref*/ injectionResult);
1696 for (const TouchedWindow& touchedWindow : touchedWindows) {
1697 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED,
1698 "Shouldn't be adding window if the injection didn't succeed.");
1699 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1700 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
1701 inputTargets);
1702 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 } else {
1704 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001705 sp<WindowInfoHandle> focusedWindow =
1706 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1707 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1708 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1709 addWindowTargetLocked(focusedWindow,
1710 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1711 BitSet32(0), getDownTime(*entry), inputTargets);
1712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001714 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 return false;
1716 }
1717
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001718 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001719 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001720 return true;
1721 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001722 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001723 CancelationOptions::Mode mode(isPointerEvent
1724 ? CancelationOptions::CANCEL_POINTER_EVENTS
1725 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1726 CancelationOptions options(mode, "input event injection failed");
1727 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 return true;
1729 }
1730
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001731 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001732 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733
1734 // Dispatch the motion.
1735 if (conflictingPointerActions) {
1736 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001737 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 synthesizeCancelationEventsForAllConnectionsLocked(options);
1739 }
1740 dispatchEventLocked(currentTime, entry, inputTargets);
1741 return true;
1742}
1743
chaviw98318de2021-05-19 16:45:23 -05001744void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001745 bool isExiting, const int32_t rawX,
1746 const int32_t rawY) {
1747 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001748 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001749 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1750 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001751
1752 enqueueInboundEventLocked(std::move(dragEntry));
1753}
1754
1755void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1756 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1757 if (channel == nullptr) {
1758 return; // Window has gone away
1759 }
1760 InputTarget target;
1761 target.inputChannel = channel;
1762 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1763 entry->dispatchInProgress = true;
1764 dispatchEventLocked(currentTime, entry, {target});
1765}
1766
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001767void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001768 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1769 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1770 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001771 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001772 "metaState=0x%x, buttonState=0x%x,"
1773 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1774 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001775 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1776 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1777 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001779 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1780 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1781 "x=%f, y=%f, pressure=%f, size=%f, "
1782 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1783 "orientation=%f",
1784 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1785 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1786 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1787 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1788 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1789 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1790 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1791 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1792 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1793 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1794 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796}
1797
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001798void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1799 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001800 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001801 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001802 if (DEBUG_DISPATCH_CYCLE) {
1803 ALOGD("dispatchEventToCurrentInputTargets");
1804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001806 updateInteractionTokensLocked(*eventEntry, inputTargets);
1807
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1809
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001810 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001811
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001812 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001813 sp<Connection> connection =
1814 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001815 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001816 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001818 if (DEBUG_FOCUS) {
1819 ALOGD("Dropping event delivery to target with channel '%s' because it "
1820 "is no longer registered with the input dispatcher.",
1821 inputTarget.inputChannel->getName().c_str());
1822 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 }
1824 }
1825}
1826
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001827void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1828 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1829 // If the policy decides to close the app, we will get a channel removal event via
1830 // unregisterInputChannel, and will clean up the connection that way. We are already not
1831 // sending new pointers to the connection when it blocked, but focused events will continue to
1832 // pile up.
1833 ALOGW("Canceling events for %s because it is unresponsive",
1834 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001835 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001836 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1837 "application not responding");
1838 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 }
1840}
1841
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001842void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001843 if (DEBUG_FOCUS) {
1844 ALOGD("Resetting ANR timeouts.");
1845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846
1847 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001848 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001849 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850}
1851
Tiger Huang721e26f2018-07-24 22:26:19 +08001852/**
1853 * Get the display id that the given event should go to. If this event specifies a valid display id,
1854 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1855 * Focused display is the display that the user most recently interacted with.
1856 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001857int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001858 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001859 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001860 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001861 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1862 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001863 break;
1864 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001865 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001866 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1867 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001868 break;
1869 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001870 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001871 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001872 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001873 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001874 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001875 case EventEntry::Type::SENSOR:
1876 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001877 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001878 return ADISPLAY_ID_NONE;
1879 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001880 }
1881 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1882}
1883
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001884bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1885 const char* focusedWindowName) {
1886 if (mAnrTracker.empty()) {
1887 // already processed all events that we waited for
1888 mKeyIsWaitingForEventsTimeout = std::nullopt;
1889 return false;
1890 }
1891
1892 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1893 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001894 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001895 mKeyIsWaitingForEventsTimeout = currentTime +
1896 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1897 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001898 return true;
1899 }
1900
1901 // We still have pending events, and already started the timer
1902 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1903 return true; // Still waiting
1904 }
1905
1906 // Waited too long, and some connection still hasn't processed all motions
1907 // Just send the key to the focused window
1908 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1909 focusedWindowName);
1910 mKeyIsWaitingForEventsTimeout = std::nullopt;
1911 return false;
1912}
1913
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001914sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1915 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1916 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001917 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001918 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919
Tiger Huang721e26f2018-07-24 22:26:19 +08001920 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001921 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001922 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001923 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1924
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925 // If there is no currently focused window and no focused application
1926 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001927 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1928 ALOGI("Dropping %s event because there is no focused window or focused application in "
1929 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001930 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001931 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 }
1933
Vishnu Nair062a8672021-09-03 16:07:44 -07001934 // Drop key events if requested by input feature
1935 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001936 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07001937 }
1938
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001939 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1940 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1941 // start interacting with another application via touch (app switch). This code can be removed
1942 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1943 // an app is expected to have a focused window.
1944 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1945 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1946 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001947 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1948 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1949 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001950 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001951 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001952 ALOGW("Waiting because no window has focus but %s may eventually add a "
1953 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001954 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001955 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001956 outInjectionResult = InputEventInjectionResult::PENDING;
1957 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001958 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1959 // Already raised ANR. Drop the event
1960 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001961 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001962 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001963 } else {
1964 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001965 outInjectionResult = InputEventInjectionResult::PENDING;
1966 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001967 }
1968 }
1969
1970 // we have a valid, non-null focused window
1971 resetNoFocusedWindowTimeoutLocked();
1972
Prabir Pradhan5735a322022-04-11 17:23:34 +00001973 // Verify targeted injection.
1974 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1975 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001976 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
1977 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978 }
1979
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001980 if (focusedWindowHandle->getInfo()->inputConfig.test(
1981 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001982 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001983 outInjectionResult = InputEventInjectionResult::PENDING;
1984 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001985 }
1986
1987 // If the event is a key event, then we must wait for all previous events to
1988 // complete before delivering it because previous events may have the
1989 // side-effect of transferring focus to a different window and we want to
1990 // ensure that the following keys are sent to the new window.
1991 //
1992 // Suppose the user touches a button in a window then immediately presses "A".
1993 // If the button causes a pop-up window to appear then we want to ensure that
1994 // the "A" key is delivered to the new pop-up window. This is because users
1995 // often anticipate pending UI changes when typing on a keyboard.
1996 // To obtain this behavior, we must serialize key events with respect to all
1997 // prior input events.
1998 if (entry.type == EventEntry::Type::KEY) {
1999 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2000 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002001 outInjectionResult = InputEventInjectionResult::PENDING;
2002 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002003 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 }
2005
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002006 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2007 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008}
2009
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002010/**
2011 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2012 * that are currently unresponsive.
2013 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002014std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2015 const std::vector<Monitor>& monitors) const {
2016 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002017 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002018 [this](const Monitor& monitor) REQUIRES(mLock) {
2019 sp<Connection> connection =
2020 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002021 if (connection == nullptr) {
2022 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002023 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002024 return false;
2025 }
2026 if (!connection->responsive) {
2027 ALOGW("Unresponsive monitor %s will not get the new gesture",
2028 connection->inputChannel->getName().c_str());
2029 return false;
2030 }
2031 return true;
2032 });
2033 return responsiveMonitors;
2034}
2035
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002036/**
2037 * In general, touch should be always split between windows. Some exceptions:
2038 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2039 * from the same device, *and* the window that's receiving the current pointer does not support
2040 * split touch.
2041 * 2. Don't split mouse events
2042 */
2043bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2044 const MotionEntry& entry) const {
2045 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2046 // We should never split mouse events
2047 return false;
2048 }
2049 for (const TouchedWindow& touchedWindow : touchState.windows) {
2050 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2051 // Spy windows should not affect whether or not touch is split.
2052 continue;
2053 }
2054 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2055 continue;
2056 }
2057 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2058 // being sent there. For now, use deviceId from touch state.
2059 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2060 return false;
2061 }
2062 }
2063 return true;
2064}
2065
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002066std::vector<TouchedWindow> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002067 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2068 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002069 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002071 std::vector<TouchedWindow> touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 // For security reasons, we defer updating the touch state until we are sure that
2073 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002074 const int32_t displayId = entry.displayId;
2075 const int32_t action = entry.action;
2076 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077
2078 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002079 outInjectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002080 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2081 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002082
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002083 // Copy current touch state into tempTouchState.
2084 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2085 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002086 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002087 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002088 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2089 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002090 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002091 }
2092
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002093 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002094 const bool switchedDevice = (oldState != nullptr) &&
2095 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002096
2097 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2098 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2099 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2100 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2101 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002102 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103 if (newGesture) {
2104 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002105 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002106 ALOGI("Dropping event because a pointer for a different device is already down "
2107 "in display %" PRId32,
2108 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002109 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002110 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002111 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002113 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002114 tempTouchState.deviceId = entry.deviceId;
2115 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002117 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002118 ALOGI("Dropping move event because a pointer for a different device is already active "
2119 "in display %" PRId32,
2120 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002121 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002122 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002123 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 }
2125
2126 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2127 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002128 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002129 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002130 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002131 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002132 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002133 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002134
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002136 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002137 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2138 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002140 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002141 }
2142
Prabir Pradhan5735a322022-04-11 17:23:34 +00002143 // Verify targeted injection.
2144 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2145 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002146 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002147 newTouchedWindowHandle = nullptr;
2148 goto Failed;
2149 }
2150
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002151 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002152 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002153 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2154 // New window supports splitting, but we should never split mouse events.
2155 isSplit = !isFromMouse;
2156 } else if (isSplit) {
2157 // New window does not support splitting but we have already split events.
2158 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002159 newTouchedWindowHandle = nullptr;
2160 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002161 } else {
2162 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002163 // be delivered to a new window which supports split touch. Pointers from a mouse device
2164 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002165 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002166 }
2167
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002168 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002169 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002170 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2171 newHoverWindowHandle = nullptr;
2172 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002173 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002174 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002175 }
2176
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002177 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002178 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002179 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002180 // Process the foreground window first so that it is the first to receive the event.
2181 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002182 }
2183
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002184 if (newTouchedWindows.empty()) {
2185 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2186 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002187 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002188 goto Failed;
2189 }
2190
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002191 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002192 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002193 continue;
2194 }
2195
2196 // Set target flags.
2197 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2198
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002199 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2200 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002201 targetFlags |= InputTarget::FLAG_FOREGROUND;
2202 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002203
2204 if (isSplit) {
2205 targetFlags |= InputTarget::FLAG_SPLIT;
2206 }
2207 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2208 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2209 } else if (isWindowObscuredLocked(windowHandle)) {
2210 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2211 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002212
2213 // Update the temporary touch state.
2214 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002215 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002216
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002217 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2218 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002220
2221 // If any existing window is pilfering pointers from newly added window, remove it
2222 BitSet32 canceledPointers = BitSet32(0);
2223 for (const TouchedWindow& window : tempTouchState.windows) {
2224 if (window.isPilferingPointers) {
2225 canceledPointers |= window.pointerIds;
2226 }
2227 }
2228 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 } else {
2230 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2231
2232 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002233 if (!tempTouchState.isDown()) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002234 if (DEBUG_FOCUS) {
2235 ALOGD("Dropping event because the pointer is not down or we previously "
2236 "dropped the pointer down event in display %" PRId32,
2237 displayId);
2238 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002239 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 goto Failed;
2241 }
2242
arthurhung6d4bed92021-03-17 11:59:33 +08002243 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002244
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002246 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002247 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002248 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002249 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002250 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002251 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002252 newTouchedWindowHandle =
2253 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002254
Prabir Pradhan5735a322022-04-11 17:23:34 +00002255 // Verify targeted injection.
2256 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2257 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002258 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002259 newTouchedWindowHandle = nullptr;
2260 goto Failed;
2261 }
2262
Vishnu Nair062a8672021-09-03 16:07:44 -07002263 // Drop touch events if requested by input feature
2264 if (newTouchedWindowHandle != nullptr &&
2265 shouldDropInput(entry, newTouchedWindowHandle)) {
2266 newTouchedWindowHandle = nullptr;
2267 }
2268
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002269 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2270 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002271 if (DEBUG_FOCUS) {
2272 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2273 oldTouchedWindowHandle->getName().c_str(),
2274 newTouchedWindowHandle->getName().c_str(), displayId);
2275 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002277 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2278 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2279 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280
2281 // Make a slippery entrance into the new window.
2282 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002283 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 }
2285
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002286 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2287 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2288 targetFlags |= InputTarget::FLAG_FOREGROUND;
2289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 if (isSplit) {
2291 targetFlags |= InputTarget::FLAG_SPLIT;
2292 }
2293 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2294 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002295 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2296 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 }
2298
2299 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002300 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002301 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2302 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 }
2304 }
2305 }
2306
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002307 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002309 // Let the previous window know that the hover sequence is over, unless we already did
2310 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002311 if (mLastHoverWindowHandle != nullptr &&
2312 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2313 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002314 if (DEBUG_HOVER) {
2315 ALOGD("Sending hover exit event to window %s.",
2316 mLastHoverWindowHandle->getName().c_str());
2317 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002318 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2319 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 }
2321
Garfield Tandf26e862020-07-01 20:18:19 -07002322 // Let the new window know that the hover sequence is starting, unless we already did it
2323 // when dispatching it as is to newTouchedWindowHandle.
2324 if (newHoverWindowHandle != nullptr &&
2325 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2326 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002327 if (DEBUG_HOVER) {
2328 ALOGD("Sending hover enter event to window %s.",
2329 newHoverWindowHandle->getName().c_str());
2330 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002331 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2332 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2333 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 }
2335 }
2336
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002337 // Ensure that we have at least one foreground window or at least one window that cannot be a
2338 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2339 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2340 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002341 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2342 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002343 return !canReceiveForegroundTouches(
2344 *touchedWindow.windowHandle->getInfo()) ||
2345 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002346 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002347 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2348 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002349 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002350 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 }
2352
Prabir Pradhan5735a322022-04-11 17:23:34 +00002353 // Ensure that all touched windows are valid for injection.
2354 if (entry.injectionState != nullptr) {
2355 std::string errs;
2356 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2357 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2358 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2359 // dispatched to any uid, since the coords will be zeroed out later.
2360 continue;
2361 }
2362 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2363 if (err) errs += "\n - " + *err;
2364 }
2365 if (!errs.empty()) {
2366 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2367 "%d:%s",
2368 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002369 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002370 goto Failed;
2371 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002372 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002373
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 // Check whether windows listening for outside touches are owned by the same UID. If it is
2375 // set the policy flag that we will not reveal coordinate information to this window.
2376 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002377 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002378 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002379 if (foregroundWindowHandle) {
2380 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002381 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002382 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002383 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2384 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2385 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002386 InputTarget::FLAG_ZERO_COORDS,
2387 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 }
2390 }
2391 }
2392 }
2393
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 // If this is the first pointer going down and the touched window has a wallpaper
2395 // then also add the touched wallpaper windows so they are locked in for the duration
2396 // of the touch gesture.
2397 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2398 // engine only supports touch events. We would need to add a mechanism similar
2399 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2400 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002401 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002402 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002403 if (foregroundWindowHandle &&
2404 foregroundWindowHandle->getInfo()->inputConfig.test(
2405 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002406 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002407 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002408 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2409 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002410 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002411 windowHandle->getInfo()->inputConfig.test(
2412 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002413 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002414 .addOrUpdateWindow(windowHandle,
2415 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2416 InputTarget::
2417 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2418 InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002419 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 }
2421 }
2422 }
2423 }
2424
2425 // Success! Output targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002426 touchedWindows = tempTouchState.windows;
2427 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428
2429 // Drop the outside or hover touch windows since we will not care about them
2430 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002431 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432
2433Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002435 if (switchedDevice) {
2436 if (DEBUG_FOCUS) {
2437 ALOGD("Conflicting pointer actions: Switched to a different device.");
2438 }
2439 *outConflictingPointerActions = true;
2440 }
2441
2442 if (isHoverAction) {
2443 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002444 if (oldState && oldState->isDown()) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002445 if (DEBUG_FOCUS) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002446 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2447 "down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002448 }
2449 *outConflictingPointerActions = true;
2450 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002451 tempTouchState.reset();
2452 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2453 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2454 tempTouchState.deviceId = entry.deviceId;
2455 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002456 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002457 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2458 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2459 // All pointers up or canceled.
2460 tempTouchState.reset();
2461 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2462 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002463 if (oldState && oldState->isDown()) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002464 if (DEBUG_FOCUS) {
2465 ALOGD("Conflicting pointer actions: Down received while already down.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002467 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002468 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002469 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2470 // One pointer went up.
2471 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2472 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002474 for (size_t i = 0; i < tempTouchState.windows.size();) {
2475 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2476 touchedWindow.pointerIds.clearBit(pointerId);
2477 if (touchedWindow.pointerIds.isEmpty()) {
2478 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2479 continue;
2480 }
2481 i += 1;
2482 }
2483 } else if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2484 // If no split, we suppose all touched windows should receive pointer down.
2485 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2486 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2487 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2488 // Ignore drag window for it should just track one pointer.
2489 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2490 continue;
2491 }
2492 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 }
2495
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002496 // Save changes unless the action was scroll in which case the temporary touch
2497 // state was only valid for this one action.
2498 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002499 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002500 mTouchStatesByDisplay[displayId] = tempTouchState;
2501 } else {
2502 mTouchStatesByDisplay.erase(displayId);
2503 }
2504 }
2505
2506 // Update hover state.
2507 mLastHoverWindowHandle = newHoverWindowHandle;
2508
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002509 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510}
2511
arthurhung6d4bed92021-03-17 11:59:33 +08002512void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002513 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2514 // have an explicit reason to support it.
2515 constexpr bool isStylus = false;
2516
chaviw98318de2021-05-19 16:45:23 -05002517 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002518 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002519 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002520 if (dropWindow) {
2521 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002522 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002523 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002524 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002525 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002526 }
2527 mDragState.reset();
2528}
2529
2530void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002531 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002532 return;
2533 }
2534
arthurhung6d4bed92021-03-17 11:59:33 +08002535 if (!mDragState->isStartDrag) {
2536 mDragState->isStartDrag = true;
2537 mDragState->isStylusButtonDownAtStart =
2538 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2539 }
2540
Arthur Hung54745652022-04-20 07:17:41 +00002541 // Find the pointer index by id.
2542 int32_t pointerIndex = 0;
2543 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2544 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2545 if (pointerProperties.id == mDragState->pointerId) {
2546 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002547 }
Arthur Hung54745652022-04-20 07:17:41 +00002548 }
arthurhung6d4bed92021-03-17 11:59:33 +08002549
Arthur Hung54745652022-04-20 07:17:41 +00002550 if (uint32_t(pointerIndex) == entry.pointerCount) {
2551 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002552 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002553 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002554 return;
2555 }
2556
2557 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2558 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2559 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2560
2561 switch (maskedAction) {
2562 case AMOTION_EVENT_ACTION_MOVE: {
2563 // Handle the special case : stylus button no longer pressed.
2564 bool isStylusButtonDown =
2565 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2566 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2567 finishDragAndDrop(entry.displayId, x, y);
2568 return;
2569 }
2570
2571 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2572 // until we have an explicit reason to support it.
2573 constexpr bool isStylus = false;
2574
2575 const sp<WindowInfoHandle> hoverWindowHandle =
2576 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2577 isStylus, false /*addOutsideTargets*/,
2578 true /*ignoreDragWindow*/);
2579 // enqueue drag exit if needed.
2580 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2581 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2582 if (mDragState->dragHoverWindowHandle != nullptr) {
2583 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2584 y);
2585 }
2586 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2587 }
2588 // enqueue drag location if needed.
2589 if (hoverWindowHandle != nullptr) {
2590 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2591 }
2592 break;
2593 }
2594
2595 case AMOTION_EVENT_ACTION_POINTER_UP:
2596 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2597 break;
2598 }
2599 // The drag pointer is up.
2600 [[fallthrough]];
2601 case AMOTION_EVENT_ACTION_UP:
2602 finishDragAndDrop(entry.displayId, x, y);
2603 break;
2604 case AMOTION_EVENT_ACTION_CANCEL: {
2605 ALOGD("Receiving cancel when drag and drop.");
2606 sendDropWindowCommandLocked(nullptr, 0, 0);
2607 mDragState.reset();
2608 break;
2609 }
arthurhungb89ccb02020-12-30 16:19:01 +08002610 }
2611}
2612
chaviw98318de2021-05-19 16:45:23 -05002613void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002614 int32_t targetFlags, BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002615 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002616 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002617 std::vector<InputTarget>::iterator it =
2618 std::find_if(inputTargets.begin(), inputTargets.end(),
2619 [&windowHandle](const InputTarget& inputTarget) {
2620 return inputTarget.inputChannel->getConnectionToken() ==
2621 windowHandle->getToken();
2622 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002623
chaviw98318de2021-05-19 16:45:23 -05002624 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002625
2626 if (it == inputTargets.end()) {
2627 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002628 std::shared_ptr<InputChannel> inputChannel =
2629 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002630 if (inputChannel == nullptr) {
2631 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2632 return;
2633 }
2634 inputTarget.inputChannel = inputChannel;
2635 inputTarget.flags = targetFlags;
2636 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002637 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002638 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2639 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002640 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002641 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002642 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002643 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002644 inputTargets.push_back(inputTarget);
2645 it = inputTargets.end() - 1;
2646 }
2647
2648 ALOG_ASSERT(it->flags == targetFlags);
2649 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2650
chaviw1ff3d1e2020-07-01 15:53:47 -07002651 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652}
2653
Michael Wright3dd60e22019-03-27 22:06:44 +00002654void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002655 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002656 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2657 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002658
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002659 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2660 InputTarget target;
2661 target.inputChannel = monitor.inputChannel;
2662 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002663 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2664 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002665 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2666 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002667 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002668 target.setDefaultPointerTransform(target.displayTransform);
2669 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 }
2671}
2672
Robert Carrc9bf1d32020-04-13 17:21:08 -07002673/**
2674 * Indicate whether one window handle should be considered as obscuring
2675 * another window handle. We only check a few preconditions. Actually
2676 * checking the bounds is left to the caller.
2677 */
chaviw98318de2021-05-19 16:45:23 -05002678static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2679 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002680 // Compare by token so cloned layers aren't counted
2681 if (haveSameToken(windowHandle, otherHandle)) {
2682 return false;
2683 }
2684 auto info = windowHandle->getInfo();
2685 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002686 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002687 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002688 } else if (otherInfo->alpha == 0 &&
2689 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002690 // Those act as if they were invisible, so we don't need to flag them.
2691 // We do want to potentially flag touchable windows even if they have 0
2692 // opacity, since they can consume touches and alter the effects of the
2693 // user interaction (eg. apps that rely on
2694 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2695 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2696 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002697 } else if (info->ownerUid == otherInfo->ownerUid) {
2698 // If ownerUid is the same we don't generate occlusion events as there
2699 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002700 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002701 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002702 return false;
2703 } else if (otherInfo->displayId != info->displayId) {
2704 return false;
2705 }
2706 return true;
2707}
2708
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002709/**
2710 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2711 * untrusted, one should check:
2712 *
2713 * 1. If result.hasBlockingOcclusion is true.
2714 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2715 * BLOCK_UNTRUSTED.
2716 *
2717 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2718 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2719 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2720 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2721 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2722 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2723 *
2724 * If neither of those is true, then it means the touch can be allowed.
2725 */
2726InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002727 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2728 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002729 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002730 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002731 TouchOcclusionInfo info;
2732 info.hasBlockingOcclusion = false;
2733 info.obscuringOpacity = 0;
2734 info.obscuringUid = -1;
2735 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002736 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002737 if (windowHandle == otherHandle) {
2738 break; // All future windows are below us. Exit early.
2739 }
chaviw98318de2021-05-19 16:45:23 -05002740 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002741 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2742 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002743 if (DEBUG_TOUCH_OCCLUSION) {
2744 info.debugInfo.push_back(
2745 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2746 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002747 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2748 // we perform the checks below to see if the touch can be propagated or not based on the
2749 // window's touch occlusion mode
2750 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2751 info.hasBlockingOcclusion = true;
2752 info.obscuringUid = otherInfo->ownerUid;
2753 info.obscuringPackage = otherInfo->packageName;
2754 break;
2755 }
2756 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2757 uint32_t uid = otherInfo->ownerUid;
2758 float opacity =
2759 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2760 // Given windows A and B:
2761 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2762 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2763 opacityByUid[uid] = opacity;
2764 if (opacity > info.obscuringOpacity) {
2765 info.obscuringOpacity = opacity;
2766 info.obscuringUid = uid;
2767 info.obscuringPackage = otherInfo->packageName;
2768 }
2769 }
2770 }
2771 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002772 if (DEBUG_TOUCH_OCCLUSION) {
2773 info.debugInfo.push_back(
2774 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2775 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002776 return info;
2777}
2778
chaviw98318de2021-05-19 16:45:23 -05002779std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002780 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002781 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2782 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2783 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2784 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002785 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2786 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2787 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2788 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2789 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002790 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002791 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002792}
2793
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002794bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2795 if (occlusionInfo.hasBlockingOcclusion) {
2796 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2797 occlusionInfo.obscuringUid);
2798 return false;
2799 }
2800 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2801 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2802 "%.2f, maximum allowed = %.2f)",
2803 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2804 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2805 return false;
2806 }
2807 return true;
2808}
2809
chaviw98318de2021-05-19 16:45:23 -05002810bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002811 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002813 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2814 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002815 if (windowHandle == otherHandle) {
2816 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 }
chaviw98318de2021-05-19 16:45:23 -05002818 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002819 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002820 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 return true;
2822 }
2823 }
2824 return false;
2825}
2826
chaviw98318de2021-05-19 16:45:23 -05002827bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002828 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002829 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2830 const WindowInfo* windowInfo = windowHandle->getInfo();
2831 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002832 if (windowHandle == otherHandle) {
2833 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002834 }
chaviw98318de2021-05-19 16:45:23 -05002835 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002836 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002837 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002838 return true;
2839 }
2840 }
2841 return false;
2842}
2843
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002844std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002845 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002846 if (applicationHandle != nullptr) {
2847 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002848 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849 } else {
2850 return applicationHandle->getName();
2851 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002852 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002853 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002855 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856 }
2857}
2858
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002859void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002860 if (!isUserActivityEvent(eventEntry)) {
2861 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002862 return;
2863 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002864 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002865 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002866 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002867 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002868 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002869 if (DEBUG_DISPATCH_CYCLE) {
2870 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2871 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872 return;
2873 }
2874 }
2875
2876 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002877 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002878 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002879 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2880 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002881 return;
2882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002884 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002885 eventType = USER_ACTIVITY_EVENT_TOUCH;
2886 }
2887 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002889 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002890 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2891 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002892 return;
2893 }
2894 eventType = USER_ACTIVITY_EVENT_BUTTON;
2895 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002896 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002897 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002898 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002899 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002900 break;
2901 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902 }
2903
Prabir Pradhancef936d2021-07-21 16:17:52 +00002904 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2905 REQUIRES(mLock) {
2906 scoped_unlock unlock(mLock);
2907 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2908 };
2909 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910}
2911
2912void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002913 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002914 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002915 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002916 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002917 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002918 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002919 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002920 ATRACE_NAME(message.c_str());
2921 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002922 if (DEBUG_DISPATCH_CYCLE) {
2923 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2924 "globalScaleFactor=%f, pointerIds=0x%x %s",
2925 connection->getInputChannelName().c_str(), inputTarget.flags,
2926 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2927 inputTarget.getPointerInfoString().c_str());
2928 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929
2930 // Skip this event if the connection status is not normal.
2931 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002932 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002933 if (DEBUG_DISPATCH_CYCLE) {
2934 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002935 connection->getInputChannelName().c_str(),
2936 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 return;
2939 }
2940
2941 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002942 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2943 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2944 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002945 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002947 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002948 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002949 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2950 "Splitting motion events requires a down time to be set for the "
2951 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002952 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002953 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2954 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955 if (!splitMotionEntry) {
2956 return; // split event was dropped
2957 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002958 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2959 std::string reason = std::string("reason=pointer cancel on split window");
2960 android_log_event_list(LOGTAG_INPUT_CANCEL)
2961 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2962 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002963 if (DEBUG_FOCUS) {
2964 ALOGD("channel '%s' ~ Split motion event.",
2965 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002966 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002967 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002968 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2969 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970 return;
2971 }
2972 }
2973
2974 // Not splitting. Enqueue dispatch entries for the event as is.
2975 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2976}
2977
2978void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002979 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002980 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002981 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002982 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002984 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002985 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002986 ATRACE_NAME(message.c_str());
2987 }
2988
hongzuo liu95785e22022-09-06 02:51:35 +00002989 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990
2991 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002992 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002993 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002994 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002995 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002996 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002997 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002998 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002999 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07003000 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07003002 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003003 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004
3005 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003006 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007 startDispatchCycleLocked(currentTime, connection);
3008 }
3009}
3010
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003012 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003013 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003014 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003015 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003016 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3017 connection->getInputChannelName().c_str(),
3018 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003019 ATRACE_NAME(message.c_str());
3020 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003021 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022 if (!(inputTargetFlags & dispatchMode)) {
3023 return;
3024 }
3025 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
3026
3027 // This is a new event.
3028 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003029 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003030 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003032 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3033 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003034 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003035 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003036 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003037 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003038 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003039 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003040 dispatchEntry->resolvedAction = keyEntry.action;
3041 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003043 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3044 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003045 if (DEBUG_DISPATCH_CYCLE) {
3046 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3047 "event",
3048 connection->getInputChannelName().c_str());
3049 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003050 return; // skip the inconsistent event
3051 }
3052 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003055 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003056 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003057 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3058 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3059 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3060 static_cast<int32_t>(IdGenerator::Source::OTHER);
3061 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003062 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3063 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3064 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3065 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3066 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3067 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3068 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3069 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3070 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3071 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3072 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003073 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003074 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003075 }
3076 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003077 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3078 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003079 if (DEBUG_DISPATCH_CYCLE) {
3080 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3081 "enter event",
3082 connection->getInputChannelName().c_str());
3083 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003084 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3085 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003086 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003089 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003090 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3091 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3092 }
3093 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3094 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003097 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3098 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003099 if (DEBUG_DISPATCH_CYCLE) {
3100 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3101 "event",
3102 connection->getInputChannelName().c_str());
3103 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003104 return; // skip the inconsistent event
3105 }
3106
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003107 dispatchEntry->resolvedEventId =
3108 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3109 ? mIdGenerator.nextId()
3110 : motionEntry.id;
3111 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3112 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3113 ") to MotionEvent(id=0x%" PRIx32 ").",
3114 motionEntry.id, dispatchEntry->resolvedEventId);
3115 ATRACE_NAME(message.c_str());
3116 }
3117
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003118 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3119 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3120 // Skip reporting pointer down outside focus to the policy.
3121 break;
3122 }
3123
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003124 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003125 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003126
3127 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003129 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003130 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003131 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3132 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003133 break;
3134 }
Chris Yef59a2f42020-10-16 12:55:26 -07003135 case EventEntry::Type::SENSOR: {
3136 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3137 break;
3138 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003139 case EventEntry::Type::CONFIGURATION_CHANGED:
3140 case EventEntry::Type::DEVICE_RESET: {
3141 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003142 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003143 break;
3144 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145 }
3146
3147 // Remember that we are waiting for this dispatch to complete.
3148 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003149 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 }
3151
3152 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003153 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003154 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003155}
3156
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003157/**
3158 * This function is purely for debugging. It helps us understand where the user interaction
3159 * was taking place. For example, if user is touching launcher, we will see a log that user
3160 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3161 * We will see both launcher and wallpaper in that list.
3162 * Once the interaction with a particular set of connections starts, no new logs will be printed
3163 * until the set of interacted connections changes.
3164 *
3165 * The following items are skipped, to reduce the logspam:
3166 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3167 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3168 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3169 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3170 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003171 */
3172void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3173 const std::vector<InputTarget>& targets) {
3174 // Skip ACTION_UP events, and all events other than keys and motions
3175 if (entry.type == EventEntry::Type::KEY) {
3176 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3177 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3178 return;
3179 }
3180 } else if (entry.type == EventEntry::Type::MOTION) {
3181 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3182 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3183 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3184 return;
3185 }
3186 } else {
3187 return; // Not a key or a motion
3188 }
3189
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003190 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003191 std::vector<sp<Connection>> newConnections;
3192 for (const InputTarget& target : targets) {
3193 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3194 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3195 continue; // Skip windows that receive ACTION_OUTSIDE
3196 }
3197
3198 sp<IBinder> token = target.inputChannel->getConnectionToken();
3199 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003200 if (connection == nullptr) {
3201 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003202 }
3203 newConnectionTokens.insert(std::move(token));
3204 newConnections.emplace_back(connection);
3205 }
3206 if (newConnectionTokens == mInteractionConnectionTokens) {
3207 return; // no change
3208 }
3209 mInteractionConnectionTokens = newConnectionTokens;
3210
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003211 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003212 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003213 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003214 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003215 std::string message = "Interaction with: " + targetList;
3216 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003217 message += "<none>";
3218 }
3219 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3220}
3221
chaviwfd6d3512019-03-25 13:23:49 -07003222void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003223 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003224 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003225 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3226 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003227 return;
3228 }
3229
Vishnu Nairc519ff72021-01-21 08:23:08 -08003230 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003231 if (focusedToken == token) {
3232 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003233 return;
3234 }
3235
Prabir Pradhancef936d2021-07-21 16:17:52 +00003236 auto command = [this, token]() REQUIRES(mLock) {
3237 scoped_unlock unlock(mLock);
3238 mPolicy->onPointerDownOutsideFocus(token);
3239 };
3240 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241}
3242
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003243status_t InputDispatcher::publishMotionEvent(Connection& connection,
3244 DispatchEntry& dispatchEntry) const {
3245 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3246 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3247
3248 PointerCoords scaledCoords[MAX_POINTERS];
3249 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3250
3251 // Set the X and Y offset and X and Y scale depending on the input source.
3252 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
3253 !(dispatchEntry.targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3254 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3255 if (globalScaleFactor != 1.0f) {
3256 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3257 scaledCoords[i] = motionEntry.pointerCoords[i];
3258 // Don't apply window scale here since we don't want scale to affect raw
3259 // coordinates. The scale will be sent back to the client and applied
3260 // later when requesting relative coordinates.
3261 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3262 1 /* windowYScale */);
3263 }
3264 usingCoords = scaledCoords;
3265 }
3266 } else if (dispatchEntry.targetFlags & InputTarget::FLAG_ZERO_COORDS) {
3267 // We don't want the dispatch target to know the coordinates
3268 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3269 scaledCoords[i].clear();
3270 }
3271 usingCoords = scaledCoords;
3272 }
3273
3274 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3275
3276 // Publish the motion event.
3277 return connection.inputPublisher
3278 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3279 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3280 std::move(hmac), dispatchEntry.resolvedAction,
3281 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3282 motionEntry.edgeFlags, motionEntry.metaState,
3283 motionEntry.buttonState, motionEntry.classification,
3284 dispatchEntry.transform, motionEntry.xPrecision,
3285 motionEntry.yPrecision, motionEntry.xCursorPosition,
3286 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3287 motionEntry.downTime, motionEntry.eventTime,
3288 motionEntry.pointerCount, motionEntry.pointerProperties,
3289 usingCoords);
3290}
3291
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003293 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003294 if (ATRACE_ENABLED()) {
3295 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003296 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003297 ATRACE_NAME(message.c_str());
3298 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003299 if (DEBUG_DISPATCH_CYCLE) {
3300 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003303 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003304 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003306 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003307 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308
3309 // Publish the event.
3310 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003311 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3312 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003313 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003314 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3315 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003317 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003318 status = connection->inputPublisher
3319 .publishKeyEvent(dispatchEntry->seq,
3320 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3321 keyEntry.source, keyEntry.displayId,
3322 std::move(hmac), dispatchEntry->resolvedAction,
3323 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3324 keyEntry.scanCode, keyEntry.metaState,
3325 keyEntry.repeatCount, keyEntry.downTime,
3326 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003327 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328 }
3329
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003330 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003331 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003332 break;
3333 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003334
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003335 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003336 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003337 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003338 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003339 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003340 break;
3341 }
3342
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003343 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3344 const TouchModeEntry& touchModeEntry =
3345 static_cast<const TouchModeEntry&>(eventEntry);
3346 status = connection->inputPublisher
3347 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3348 touchModeEntry.inTouchMode);
3349
3350 break;
3351 }
3352
Prabir Pradhan99987712020-11-10 18:43:05 -08003353 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3354 const auto& captureEntry =
3355 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3356 status = connection->inputPublisher
3357 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003358 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003359 break;
3360 }
3361
arthurhungb89ccb02020-12-30 16:19:01 +08003362 case EventEntry::Type::DRAG: {
3363 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3364 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3365 dragEntry.id, dragEntry.x,
3366 dragEntry.y,
3367 dragEntry.isExiting);
3368 break;
3369 }
3370
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003371 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003372 case EventEntry::Type::DEVICE_RESET:
3373 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003374 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003375 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003376 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378 }
3379
3380 // Check the result.
3381 if (status) {
3382 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003383 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003385 "This is unexpected because the wait queue is empty, so the pipe "
3386 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003387 "event to it, status=%s(%d)",
3388 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3389 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3391 } else {
3392 // Pipe is full and we are waiting for the app to finish process some events
3393 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003394 if (DEBUG_DISPATCH_CYCLE) {
3395 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3396 "waiting for the application to catch up",
3397 connection->getInputChannelName().c_str());
3398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 }
3400 } else {
3401 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003402 "status=%s(%d)",
3403 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3404 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3406 }
3407 return;
3408 }
3409
3410 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003411 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3412 connection->outboundQueue.end(),
3413 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003414 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003415 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003416 if (connection->responsive) {
3417 mAnrTracker.insert(dispatchEntry->timeoutTime,
3418 connection->inputChannel->getConnectionToken());
3419 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003420 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421 }
3422}
3423
chaviw09c8d2d2020-08-24 15:48:26 -07003424std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3425 size_t size;
3426 switch (event.type) {
3427 case VerifiedInputEvent::Type::KEY: {
3428 size = sizeof(VerifiedKeyEvent);
3429 break;
3430 }
3431 case VerifiedInputEvent::Type::MOTION: {
3432 size = sizeof(VerifiedMotionEvent);
3433 break;
3434 }
3435 }
3436 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3437 return mHmacKeyManager.sign(start, size);
3438}
3439
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003440const std::array<uint8_t, 32> InputDispatcher::getSignature(
3441 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003442 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3443 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003444 // Only sign events up and down events as the purely move events
3445 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003446 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003447 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003448
3449 VerifiedMotionEvent verifiedEvent =
3450 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3451 verifiedEvent.actionMasked = actionMasked;
3452 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3453 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003454}
3455
3456const std::array<uint8_t, 32> InputDispatcher::getSignature(
3457 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3458 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3459 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3460 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003461 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003462}
3463
Michael Wrightd02c5b62014-02-10 15:10:22 -08003464void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003465 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003466 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003467 if (DEBUG_DISPATCH_CYCLE) {
3468 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3469 connection->getInputChannelName().c_str(), seq, toString(handled));
3470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003472 if (connection->status == Connection::Status::BROKEN ||
3473 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 return;
3475 }
3476
3477 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003478 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3479 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3480 };
3481 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482}
3483
3484void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003485 const sp<Connection>& connection,
3486 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003487 if (DEBUG_DISPATCH_CYCLE) {
3488 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3489 connection->getInputChannelName().c_str(), toString(notify));
3490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491
3492 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003493 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003494 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003495 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003496 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497
3498 // The connection appears to be unrecoverably broken.
3499 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003500 if (connection->status == Connection::Status::NORMAL) {
3501 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502
3503 if (notify) {
3504 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003505 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3506 connection->getInputChannelName().c_str());
3507
3508 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003509 scoped_unlock unlock(mLock);
3510 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3511 };
3512 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 }
3514 }
3515}
3516
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003517void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3518 while (!queue.empty()) {
3519 DispatchEntry* dispatchEntry = queue.front();
3520 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003521 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522 }
3523}
3524
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003525void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003527 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 }
3529 delete dispatchEntry;
3530}
3531
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003532int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3533 std::scoped_lock _l(mLock);
3534 sp<Connection> connection = getConnectionLocked(connectionToken);
3535 if (connection == nullptr) {
3536 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3537 connectionToken.get(), events);
3538 return 0; // remove the callback
3539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003541 bool notify;
3542 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3543 if (!(events & ALOOPER_EVENT_INPUT)) {
3544 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3545 "events=0x%x",
3546 connection->getInputChannelName().c_str(), events);
3547 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548 }
3549
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003550 nsecs_t currentTime = now();
3551 bool gotOne = false;
3552 status_t status = OK;
3553 for (;;) {
3554 Result<InputPublisher::ConsumerResponse> result =
3555 connection->inputPublisher.receiveConsumerResponse();
3556 if (!result.ok()) {
3557 status = result.error().code();
3558 break;
3559 }
3560
3561 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3562 const InputPublisher::Finished& finish =
3563 std::get<InputPublisher::Finished>(*result);
3564 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3565 finish.consumeTime);
3566 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003567 if (shouldReportMetricsForConnection(*connection)) {
3568 const InputPublisher::Timeline& timeline =
3569 std::get<InputPublisher::Timeline>(*result);
3570 mLatencyTracker
3571 .trackGraphicsLatency(timeline.inputEventId,
3572 connection->inputChannel->getConnectionToken(),
3573 std::move(timeline.graphicsTimeline));
3574 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003575 }
3576 gotOne = true;
3577 }
3578 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003579 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003580 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581 return 1;
3582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 }
3584
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003585 notify = status != DEAD_OBJECT || !connection->monitor;
3586 if (notify) {
3587 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3588 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3589 status);
3590 }
3591 } else {
3592 // Monitor channels are never explicitly unregistered.
3593 // We do it automatically when the remote endpoint is closed so don't warn about them.
3594 const bool stillHaveWindowHandle =
3595 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3596 notify = !connection->monitor && stillHaveWindowHandle;
3597 if (notify) {
3598 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3599 connection->getInputChannelName().c_str(), events);
3600 }
3601 }
3602
3603 // Remove the channel.
3604 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3605 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606}
3607
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003608void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003610 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003611 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 }
3613}
3614
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003615void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003616 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003617 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003618 for (const Monitor& monitor : monitors) {
3619 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003620 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003621 }
3622}
3623
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003625 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003626 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003627 if (connection == nullptr) {
3628 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003630
3631 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632}
3633
3634void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3635 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003636 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 return;
3638 }
3639
3640 nsecs_t currentTime = now();
3641
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003642 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003643 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003645 if (cancelationEvents.empty()) {
3646 return;
3647 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003648 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3649 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3650 "with reality: %s, mode=%d.",
3651 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3652 options.mode);
3653 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003654
Arthur Hungb3307ee2021-10-14 10:57:37 +00003655 std::string reason = std::string("reason=").append(options.reason);
3656 android_log_event_list(LOGTAG_INPUT_CANCEL)
3657 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3658
Svet Ganov5d3bc372020-01-26 23:11:07 -08003659 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003660 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003661 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3662 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003663 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003664 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003665 target.globalScaleFactor = windowInfo->globalScaleFactor;
3666 }
3667 target.inputChannel = connection->inputChannel;
3668 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3669
hongzuo liu95785e22022-09-06 02:51:35 +00003670 const bool wasEmpty = connection->outboundQueue.empty();
3671
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003672 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003673 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003674 switch (cancelationEventEntry->type) {
3675 case EventEntry::Type::KEY: {
3676 logOutboundKeyDetails("cancel - ",
3677 static_cast<const KeyEntry&>(*cancelationEventEntry));
3678 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003680 case EventEntry::Type::MOTION: {
3681 logOutboundMotionDetails("cancel - ",
3682 static_cast<const MotionEntry&>(*cancelationEventEntry));
3683 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003685 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003686 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003687 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3688 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003689 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003690 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003691 break;
3692 }
3693 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003694 case EventEntry::Type::DEVICE_RESET:
3695 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003696 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003697 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003698 break;
3699 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 }
3701
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003702 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3703 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003705
hongzuo liu95785e22022-09-06 02:51:35 +00003706 // If the outbound queue was previously empty, start the dispatch cycle going.
3707 if (wasEmpty && !connection->outboundQueue.empty()) {
3708 startDispatchCycleLocked(currentTime, connection);
3709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710}
3711
Svet Ganov5d3bc372020-01-26 23:11:07 -08003712void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003713 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003714 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003715 return;
3716 }
3717
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003718 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003719 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003720
3721 if (downEvents.empty()) {
3722 return;
3723 }
3724
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003725 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003726 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3727 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003728 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003729
3730 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003731 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003732 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3733 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003734 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003735 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003736 target.globalScaleFactor = windowInfo->globalScaleFactor;
3737 }
3738 target.inputChannel = connection->inputChannel;
3739 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3740
hongzuo liu95785e22022-09-06 02:51:35 +00003741 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003742 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003743 switch (downEventEntry->type) {
3744 case EventEntry::Type::MOTION: {
3745 logOutboundMotionDetails("down - ",
3746 static_cast<const MotionEntry&>(*downEventEntry));
3747 break;
3748 }
3749
3750 case EventEntry::Type::KEY:
3751 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003752 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003753 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003754 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003755 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003756 case EventEntry::Type::SENSOR:
3757 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003758 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003759 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003760 break;
3761 }
3762 }
3763
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003764 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3765 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003766 }
3767
hongzuo liu95785e22022-09-06 02:51:35 +00003768 // If the outbound queue was previously empty, start the dispatch cycle going.
3769 if (wasEmpty && !connection->outboundQueue.empty()) {
3770 startDispatchCycleLocked(downTime, connection);
3771 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003772}
3773
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003774std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003775 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 ALOG_ASSERT(pointerIds.value != 0);
3777
3778 uint32_t splitPointerIndexMap[MAX_POINTERS];
3779 PointerProperties splitPointerProperties[MAX_POINTERS];
3780 PointerCoords splitPointerCoords[MAX_POINTERS];
3781
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003782 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 uint32_t splitPointerCount = 0;
3784
3785 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003786 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003788 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 uint32_t pointerId = uint32_t(pointerProperties.id);
3790 if (pointerIds.hasBit(pointerId)) {
3791 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3792 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3793 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003794 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 splitPointerCount += 1;
3796 }
3797 }
3798
3799 if (splitPointerCount != pointerIds.count()) {
3800 // This is bad. We are missing some of the pointers that we expected to deliver.
3801 // Most likely this indicates that we received an ACTION_MOVE events that has
3802 // different pointer ids than we expected based on the previous ACTION_DOWN
3803 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3804 // in this way.
3805 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003806 "we expected there to be %d pointers. This probably means we received "
3807 "a broken sequence of pointer ids from the input device.",
3808 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003809 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 }
3811
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003812 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003814 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3815 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3817 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003818 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003819 uint32_t pointerId = uint32_t(pointerProperties.id);
3820 if (pointerIds.hasBit(pointerId)) {
3821 if (pointerIds.count() == 1) {
3822 // The first/last pointer went down/up.
3823 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003824 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003825 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3826 ? AMOTION_EVENT_ACTION_CANCEL
3827 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 } else {
3829 // A secondary pointer went down/up.
3830 uint32_t splitPointerIndex = 0;
3831 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3832 splitPointerIndex += 1;
3833 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003834 action = maskedAction |
3835 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836 }
3837 } else {
3838 // An unrelated pointer changed.
3839 action = AMOTION_EVENT_ACTION_MOVE;
3840 }
3841 }
3842
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003843 if (action == AMOTION_EVENT_ACTION_DOWN) {
3844 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3845 "Split motion event has mismatching downTime and eventTime for "
3846 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3847 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3848 }
3849
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003850 int32_t newId = mIdGenerator.nextId();
3851 if (ATRACE_ENABLED()) {
3852 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3853 ") to MotionEvent(id=0x%" PRIx32 ").",
3854 originalMotionEntry.id, newId);
3855 ATRACE_NAME(message.c_str());
3856 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003857 std::unique_ptr<MotionEntry> splitMotionEntry =
3858 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3859 originalMotionEntry.deviceId, originalMotionEntry.source,
3860 originalMotionEntry.displayId,
3861 originalMotionEntry.policyFlags, action,
3862 originalMotionEntry.actionButton,
3863 originalMotionEntry.flags, originalMotionEntry.metaState,
3864 originalMotionEntry.buttonState,
3865 originalMotionEntry.classification,
3866 originalMotionEntry.edgeFlags,
3867 originalMotionEntry.xPrecision,
3868 originalMotionEntry.yPrecision,
3869 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003870 originalMotionEntry.yCursorPosition, splitDownTime,
3871 splitPointerCount, splitPointerProperties,
3872 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003874 if (originalMotionEntry.injectionState) {
3875 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 splitMotionEntry->injectionState->refCount += 1;
3877 }
3878
3879 return splitMotionEntry;
3880}
3881
3882void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003883 if (DEBUG_INBOUND_EVENT_DETAILS) {
3884 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3885 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886
Antonio Kantekf16f2832021-09-28 04:39:20 +00003887 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003889 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003891 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3892 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3893 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894 } // release lock
3895
3896 if (needWake) {
3897 mLooper->wake();
3898 }
3899}
3900
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003901/**
3902 * If one of the meta shortcuts is detected, process them here:
3903 * Meta + Backspace -> generate BACK
3904 * Meta + Enter -> generate HOME
3905 * This will potentially overwrite keyCode and metaState.
3906 */
3907void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003908 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003909 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3910 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3911 if (keyCode == AKEYCODE_DEL) {
3912 newKeyCode = AKEYCODE_BACK;
3913 } else if (keyCode == AKEYCODE_ENTER) {
3914 newKeyCode = AKEYCODE_HOME;
3915 }
3916 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003917 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003918 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003919 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003920 keyCode = newKeyCode;
3921 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3922 }
3923 } else if (action == AKEY_EVENT_ACTION_UP) {
3924 // In order to maintain a consistent stream of up and down events, check to see if the key
3925 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3926 // even if the modifier was released between the down and the up events.
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 auto replacementIt = mReplacedKeys.find(replacement);
3930 if (replacementIt != mReplacedKeys.end()) {
3931 keyCode = replacementIt->second;
3932 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003933 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3934 }
3935 }
3936}
3937
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003939 if (DEBUG_INBOUND_EVENT_DETAILS) {
3940 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3941 "policyFlags=0x%x, action=0x%x, "
3942 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3943 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3944 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3945 args->downTime);
3946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 if (!validateKeyEvent(args->action)) {
3948 return;
3949 }
3950
3951 uint32_t policyFlags = args->policyFlags;
3952 int32_t flags = args->flags;
3953 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003954 // InputDispatcher tracks and generates key repeats on behalf of
3955 // whatever notifies it, so repeatCount should always be set to 0
3956 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3958 policyFlags |= POLICY_FLAG_VIRTUAL;
3959 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961 if (policyFlags & POLICY_FLAG_FUNCTION) {
3962 metaState |= AMETA_FUNCTION_ON;
3963 }
3964
3965 policyFlags |= POLICY_FLAG_TRUSTED;
3966
Michael Wright78f24442014-08-06 15:55:28 -07003967 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003968 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003969
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003971 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003972 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3973 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974
Michael Wright2b3c3302018-03-02 17:19:13 +00003975 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003977 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3978 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003979 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981
Antonio Kantekf16f2832021-09-28 04:39:20 +00003982 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 { // acquire lock
3984 mLock.lock();
3985
3986 if (shouldSendKeyToInputFilterLocked(args)) {
3987 mLock.unlock();
3988
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003989 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3991 return; // event was consumed by the filter
3992 }
3993
3994 mLock.lock();
3995 }
3996
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003997 std::unique_ptr<KeyEntry> newEntry =
3998 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3999 args->displayId, policyFlags, args->action, flags,
4000 keyCode, args->scanCode, metaState, repeatCount,
4001 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004003 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004 mLock.unlock();
4005 } // release lock
4006
4007 if (needWake) {
4008 mLooper->wake();
4009 }
4010}
4011
4012bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4013 return mInputFilterEnabled;
4014}
4015
4016void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004017 if (DEBUG_INBOUND_EVENT_DETAILS) {
4018 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4019 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004020 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004021 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4022 "yCursorPosition=%f, downTime=%" PRId64,
4023 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004024 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4025 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4026 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4027 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004028 for (uint32_t i = 0; i < args->pointerCount; i++) {
4029 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4030 "x=%f, y=%f, pressure=%f, size=%f, "
4031 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4032 "orientation=%f",
4033 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4034 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4035 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4036 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4037 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4038 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4039 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4040 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4041 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4042 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004045 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4046 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047 return;
4048 }
4049
4050 uint32_t policyFlags = args->policyFlags;
4051 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004052
4053 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004054 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004055 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4056 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004057 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059
Antonio Kantekf16f2832021-09-28 04:39:20 +00004060 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061 { // acquire lock
4062 mLock.lock();
4063
4064 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004065 ui::Transform displayTransform;
4066 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4067 displayTransform = it->second.transform;
4068 }
4069
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 mLock.unlock();
4071
4072 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004073 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4074 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004075 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004076 displayTransform, args->xPrecision, args->yPrecision,
4077 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004078 args->downTime, args->eventTime, args->pointerCount,
4079 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080
4081 policyFlags |= POLICY_FLAG_FILTERED;
4082 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4083 return; // event was consumed by the filter
4084 }
4085
4086 mLock.lock();
4087 }
4088
4089 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004090 std::unique_ptr<MotionEntry> newEntry =
4091 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4092 args->source, args->displayId, policyFlags,
4093 args->action, args->actionButton, args->flags,
4094 args->metaState, args->buttonState,
4095 args->classification, args->edgeFlags,
4096 args->xPrecision, args->yPrecision,
4097 args->xCursorPosition, args->yCursorPosition,
4098 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004099 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004101 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4102 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4103 !mInputFilterEnabled) {
4104 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4105 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4106 }
4107
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004108 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 mLock.unlock();
4110 } // release lock
4111
4112 if (needWake) {
4113 mLooper->wake();
4114 }
4115}
4116
Chris Yef59a2f42020-10-16 12:55:26 -07004117void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004118 if (DEBUG_INBOUND_EVENT_DETAILS) {
4119 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4120 " sensorType=%s",
4121 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004122 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004123 }
Chris Yef59a2f42020-10-16 12:55:26 -07004124
Antonio Kantekf16f2832021-09-28 04:39:20 +00004125 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004126 { // acquire lock
4127 mLock.lock();
4128
4129 // Just enqueue a new sensor event.
4130 std::unique_ptr<SensorEntry> newEntry =
4131 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4132 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4133 args->sensorType, args->accuracy,
4134 args->accuracyChanged, args->values);
4135
4136 needWake = enqueueInboundEventLocked(std::move(newEntry));
4137 mLock.unlock();
4138 } // release lock
4139
4140 if (needWake) {
4141 mLooper->wake();
4142 }
4143}
4144
Chris Yefb552902021-02-03 17:18:37 -08004145void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004146 if (DEBUG_INBOUND_EVENT_DETAILS) {
4147 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4148 args->deviceId, args->isOn);
4149 }
Chris Yefb552902021-02-03 17:18:37 -08004150 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4151}
4152
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004154 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155}
4156
4157void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004158 if (DEBUG_INBOUND_EVENT_DETAILS) {
4159 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4160 "switchMask=0x%08x",
4161 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163
4164 uint32_t policyFlags = args->policyFlags;
4165 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004166 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167}
4168
4169void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004170 if (DEBUG_INBOUND_EVENT_DETAILS) {
4171 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4172 args->deviceId);
4173 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174
Antonio Kantekf16f2832021-09-28 04:39:20 +00004175 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004177 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004179 std::unique_ptr<DeviceResetEntry> newEntry =
4180 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4181 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 } // release lock
4183
4184 if (needWake) {
4185 mLooper->wake();
4186 }
4187}
4188
Prabir Pradhan7e186182020-11-10 13:56:45 -08004189void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004190 if (DEBUG_INBOUND_EVENT_DETAILS) {
4191 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004192 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004193 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004194
Antonio Kantekf16f2832021-09-28 04:39:20 +00004195 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004196 { // acquire lock
4197 std::scoped_lock _l(mLock);
4198 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004199 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004200 needWake = enqueueInboundEventLocked(std::move(entry));
4201 } // release lock
4202
4203 if (needWake) {
4204 mLooper->wake();
4205 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004206}
4207
Prabir Pradhan5735a322022-04-11 17:23:34 +00004208InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4209 std::optional<int32_t> targetUid,
4210 InputEventInjectionSync syncMode,
4211 std::chrono::milliseconds timeout,
4212 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004213 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004214 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4215 "policyFlags=0x%08x",
4216 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4217 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004218 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004219 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220
Prabir Pradhan5735a322022-04-11 17:23:34 +00004221 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004223 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004224 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4225 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4226 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4227 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4228 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004229 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004230 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004231 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004232 }
4233
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004234 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004236 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004237 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4238 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004239 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004240 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004241 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004243 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004244 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4245 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4246 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004247 int32_t keyCode = incomingKey.getKeyCode();
4248 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004249 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004250 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004251 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004252 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004253 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4254 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4255 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004257 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4258 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004259 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004260
4261 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4262 android::base::Timer t;
4263 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4264 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4265 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4266 std::to_string(t.duration().count()).c_str());
4267 }
4268 }
4269
4270 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004271 std::unique_ptr<KeyEntry> injectedEntry =
4272 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004273 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004274 incomingKey.getDisplayId(), policyFlags, action,
4275 flags, keyCode, incomingKey.getScanCode(), metaState,
4276 incomingKey.getRepeatCount(),
4277 incomingKey.getDownTime());
4278 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004279 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 }
4281
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004282 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004283 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004284 const int32_t action = motionEvent.getAction();
4285 const bool isPointerEvent =
4286 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4287 // If a pointer event has no displayId specified, inject it to the default display.
4288 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4289 ? ADISPLAY_ID_DEFAULT
4290 : event->getDisplayId();
4291 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004292 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004293 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004294 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004295 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004296 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004297 }
4298
4299 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004300 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004301 android::base::Timer t;
4302 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4303 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4304 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4305 std::to_string(t.duration().count()).c_str());
4306 }
4307 }
4308
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004309 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4310 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4311 }
4312
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004313 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004314 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4315 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004316 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004317 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4318 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004319 displayId, policyFlags, action, actionButton,
4320 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004321 motionEvent.getButtonState(),
4322 motionEvent.getClassification(),
4323 motionEvent.getEdgeFlags(),
4324 motionEvent.getXPrecision(),
4325 motionEvent.getYPrecision(),
4326 motionEvent.getRawXCursorPosition(),
4327 motionEvent.getRawYCursorPosition(),
4328 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004329 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004330 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004331 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004332 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004333 sampleEventTimes += 1;
4334 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004335 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004336 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4337 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004338 displayId, policyFlags, action, actionButton,
4339 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004340 motionEvent.getButtonState(),
4341 motionEvent.getClassification(),
4342 motionEvent.getEdgeFlags(),
4343 motionEvent.getXPrecision(),
4344 motionEvent.getYPrecision(),
4345 motionEvent.getRawXCursorPosition(),
4346 motionEvent.getRawYCursorPosition(),
4347 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004348 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004349 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004350 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4351 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004352 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004353 }
4354 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004357 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004358 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004359 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 }
4361
Prabir Pradhan5735a322022-04-11 17:23:34 +00004362 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004363 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 injectionState->injectionIsAsync = true;
4365 }
4366
4367 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004368 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369
4370 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004371 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004372 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004373 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 }
4375
4376 mLock.unlock();
4377
4378 if (needWake) {
4379 mLooper->wake();
4380 }
4381
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004382 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004384 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004386 if (syncMode == InputEventInjectionSync::NONE) {
4387 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 } else {
4389 for (;;) {
4390 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004391 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 break;
4393 }
4394
4395 nsecs_t remainingTimeout = endTime - now();
4396 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004397 if (DEBUG_INJECTION) {
4398 ALOGD("injectInputEvent - Timed out waiting for injection result "
4399 "to become available.");
4400 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004401 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402 break;
4403 }
4404
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004405 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406 }
4407
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004408 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4409 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004411 if (DEBUG_INJECTION) {
4412 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4413 injectionState->pendingForegroundDispatches);
4414 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415 nsecs_t remainingTimeout = endTime - now();
4416 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004417 if (DEBUG_INJECTION) {
4418 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4419 "dispatches to finish.");
4420 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004421 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422 break;
4423 }
4424
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004425 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426 }
4427 }
4428 }
4429
4430 injectionState->release();
4431 } // release lock
4432
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004433 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004434 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436
4437 return injectionResult;
4438}
4439
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004440std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004441 std::array<uint8_t, 32> calculatedHmac;
4442 std::unique_ptr<VerifiedInputEvent> result;
4443 switch (event.getType()) {
4444 case AINPUT_EVENT_TYPE_KEY: {
4445 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4446 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4447 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004448 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004449 break;
4450 }
4451 case AINPUT_EVENT_TYPE_MOTION: {
4452 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4453 VerifiedMotionEvent verifiedMotionEvent =
4454 verifiedMotionEventFromMotionEvent(motionEvent);
4455 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004456 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004457 break;
4458 }
4459 default: {
4460 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4461 return nullptr;
4462 }
4463 }
4464 if (calculatedHmac == INVALID_HMAC) {
4465 return nullptr;
4466 }
4467 if (calculatedHmac != event.getHmac()) {
4468 return nullptr;
4469 }
4470 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004471}
4472
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004473void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004474 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004475 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004476 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004477 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004478 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004479 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004480
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004481 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 // Log the outcome since the injector did not wait for the injection result.
4483 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004484 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004485 ALOGV("Asynchronous input event injection succeeded.");
4486 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004487 case InputEventInjectionResult::TARGET_MISMATCH:
4488 ALOGV("Asynchronous input event injection target mismatch.");
4489 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004490 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004491 ALOGW("Asynchronous input event injection failed.");
4492 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004493 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004494 ALOGW("Asynchronous input event injection timed out.");
4495 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004496 case InputEventInjectionResult::PENDING:
4497 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4498 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 }
4500 }
4501
4502 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004503 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504 }
4505}
4506
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004507void InputDispatcher::transformMotionEntryForInjectionLocked(
4508 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004509 // Input injection works in the logical display coordinate space, but the input pipeline works
4510 // display space, so we need to transform the injected events accordingly.
4511 const auto it = mDisplayInfos.find(entry.displayId);
4512 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004513 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004514
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004515 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4516 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4517 const vec2 cursor =
4518 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4519 {entry.xCursorPosition, entry.yCursorPosition});
4520 entry.xCursorPosition = cursor.x;
4521 entry.yCursorPosition = cursor.y;
4522 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004523 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004524 entry.pointerCoords[i] =
4525 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4526 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004527 }
4528}
4529
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004530void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4531 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004532 if (injectionState) {
4533 injectionState->pendingForegroundDispatches += 1;
4534 }
4535}
4536
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004537void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4538 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 if (injectionState) {
4540 injectionState->pendingForegroundDispatches -= 1;
4541
4542 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004543 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 }
4545 }
4546}
4547
chaviw98318de2021-05-19 16:45:23 -05004548const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004549 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004550 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004551 auto it = mWindowHandlesByDisplay.find(displayId);
4552 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004553}
4554
chaviw98318de2021-05-19 16:45:23 -05004555sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004556 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004557 if (windowHandleToken == nullptr) {
4558 return nullptr;
4559 }
4560
Arthur Hungb92218b2018-08-14 12:00:21 +08004561 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004562 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4563 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004564 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004565 return windowHandle;
4566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567 }
4568 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004569 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570}
4571
chaviw98318de2021-05-19 16:45:23 -05004572sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4573 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004574 if (windowHandleToken == nullptr) {
4575 return nullptr;
4576 }
4577
chaviw98318de2021-05-19 16:45:23 -05004578 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004579 if (windowHandle->getToken() == windowHandleToken) {
4580 return windowHandle;
4581 }
4582 }
4583 return nullptr;
4584}
4585
chaviw98318de2021-05-19 16:45:23 -05004586sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4587 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004588 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004589 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4590 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004591 if (handle->getId() == windowHandle->getId() &&
4592 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004593 if (windowHandle->getInfo()->displayId != it.first) {
4594 ALOGE("Found window %s in display %" PRId32
4595 ", but it should belong to display %" PRId32,
4596 windowHandle->getName().c_str(), it.first,
4597 windowHandle->getInfo()->displayId);
4598 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004599 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601 }
4602 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004603 return nullptr;
4604}
4605
chaviw98318de2021-05-19 16:45:23 -05004606sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004607 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4608 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609}
4610
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004611bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4612 const MotionEntry& motionEntry) const {
4613 const WindowInfo& info = *window->getInfo();
4614
4615 // Skip spy window targets that are not valid for targeted injection.
4616 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004617 return false;
4618 }
4619
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004620 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4621 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4622 return false;
4623 }
4624
4625 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4626 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4627 window->getName().c_str());
4628 return false;
4629 }
4630
4631 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004632 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004633 ALOGW("Not sending touch to %s because there's no corresponding connection",
4634 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004635 return false;
4636 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004637
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004638 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004639 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004640 return false;
4641 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004642
4643 // Drop events that can't be trusted due to occlusion
4644 const auto [x, y] = resolveTouchedPosition(motionEntry);
4645 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4646 if (!isTouchTrustedLocked(occlusionInfo)) {
4647 if (DEBUG_TOUCH_OCCLUSION) {
4648 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4649 for (const auto& log : occlusionInfo.debugInfo) {
4650 ALOGD("%s", log.c_str());
4651 }
4652 }
4653 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4654 occlusionInfo.obscuringUid);
4655 return false;
4656 }
4657
4658 // Drop touch events if requested by input feature
4659 if (shouldDropInput(motionEntry, window)) {
4660 return false;
4661 }
4662
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004663 return true;
4664}
4665
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004666std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4667 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004668 auto connectionIt = mConnectionsByToken.find(token);
4669 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004670 return nullptr;
4671 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004672 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004673}
4674
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004675void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004676 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4677 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004678 // Remove all handles on a display if there are no windows left.
4679 mWindowHandlesByDisplay.erase(displayId);
4680 return;
4681 }
4682
4683 // Since we compare the pointer of input window handles across window updates, we need
4684 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004685 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4686 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4687 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004688 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004689 }
4690
chaviw98318de2021-05-19 16:45:23 -05004691 std::vector<sp<WindowInfoHandle>> newHandles;
4692 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004693 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004694 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004695 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004696 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004697 const bool canReceiveInput =
4698 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4699 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004700 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004701 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004702 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004703 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004704 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004705 }
4706
4707 if (info->displayId != displayId) {
4708 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4709 handle->getName().c_str(), displayId, info->displayId);
4710 continue;
4711 }
4712
Robert Carredd13602020-04-13 17:24:34 -07004713 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4714 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004715 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004716 oldHandle->updateFrom(handle);
4717 newHandles.push_back(oldHandle);
4718 } else {
4719 newHandles.push_back(handle);
4720 }
4721 }
4722
4723 // Insert or replace
4724 mWindowHandlesByDisplay[displayId] = newHandles;
4725}
4726
Arthur Hung72d8dc32020-03-28 00:48:39 +00004727void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004728 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004729 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004730 { // acquire lock
4731 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004732 for (const auto& [displayId, handles] : handlesPerDisplay) {
4733 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004734 }
4735 }
4736 // Wake up poll loop since it may need to make new input dispatching choices.
4737 mLooper->wake();
4738}
4739
Arthur Hungb92218b2018-08-14 12:00:21 +08004740/**
4741 * Called from InputManagerService, update window handle list by displayId that can receive input.
4742 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4743 * If set an empty list, remove all handles from the specific display.
4744 * For focused handle, check if need to change and send a cancel event to previous one.
4745 * For removed handle, check if need to send a cancel event if already in touch.
4746 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004747void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004748 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004749 if (DEBUG_FOCUS) {
4750 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004751 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004752 windowList += iwh->getName() + " ";
4753 }
4754 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4755 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756
Prabir Pradhand65552b2021-10-07 11:23:50 -07004757 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004758 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004759 const WindowInfo& info = *window->getInfo();
4760
4761 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004762 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004763 if (noInputWindow && window->getToken() != nullptr) {
4764 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4765 window->getName().c_str());
4766 window->releaseChannel();
4767 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004768
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004769 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004770 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4771 !info.inputConfig.test(
4772 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004773 "%s has feature SPY, but is not a trusted overlay.",
4774 window->getName().c_str());
4775
Prabir Pradhand65552b2021-10-07 11:23:50 -07004776 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004777 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4778 !info.inputConfig.test(
4779 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004780 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4781 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004782 }
4783
Arthur Hung72d8dc32020-03-28 00:48:39 +00004784 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004785 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004787 // Save the old windows' orientation by ID before it gets updated.
4788 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004789 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004790 oldWindowOrientations.emplace(handle->getId(),
4791 handle->getInfo()->transform.getOrientation());
4792 }
4793
chaviw98318de2021-05-19 16:45:23 -05004794 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004795
chaviw98318de2021-05-19 16:45:23 -05004796 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004797 if (mLastHoverWindowHandle &&
4798 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4799 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004800 mLastHoverWindowHandle = nullptr;
4801 }
4802
Vishnu Nairc519ff72021-01-21 08:23:08 -08004803 std::optional<FocusResolver::FocusChanges> changes =
4804 mFocusResolver.setInputWindows(displayId, windowHandles);
4805 if (changes) {
4806 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004809 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4810 mTouchStatesByDisplay.find(displayId);
4811 if (stateIt != mTouchStatesByDisplay.end()) {
4812 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004813 for (size_t i = 0; i < state.windows.size();) {
4814 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004815 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004816 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004817 ALOGD("Touched window was removed: %s in display %" PRId32,
4818 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004819 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004820 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004821 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4822 if (touchedInputChannel != nullptr) {
4823 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4824 "touched window was removed");
4825 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004826 // Since we are about to drop the touch, cancel the events for the wallpaper as
4827 // well.
4828 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004829 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4830 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004831 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4832 if (wallpaper != nullptr) {
4833 sp<Connection> wallpaperConnection =
4834 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004835 if (wallpaperConnection != nullptr) {
4836 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4837 options);
4838 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004839 }
4840 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004842 state.windows.erase(state.windows.begin() + i);
4843 } else {
4844 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004845 }
4846 }
arthurhungb89ccb02020-12-30 16:19:01 +08004847
arthurhung6d4bed92021-03-17 11:59:33 +08004848 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004849 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004850 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004851 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004852 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004853 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4854 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004855 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004856 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004857 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004858
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004859 // Determine if the orientation of any of the input windows have changed, and cancel all
4860 // pointer events if necessary.
4861 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4862 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4863 if (newWindowHandle != nullptr &&
4864 newWindowHandle->getInfo()->transform.getOrientation() !=
4865 oldWindowOrientations[oldWindowHandle->getId()]) {
4866 std::shared_ptr<InputChannel> inputChannel =
4867 getInputChannelLocked(newWindowHandle->getToken());
4868 if (inputChannel != nullptr) {
4869 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4870 "touched window's orientation changed");
4871 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004872 }
4873 }
4874 }
4875
Arthur Hung72d8dc32020-03-28 00:48:39 +00004876 // Release information for windows that are no longer present.
4877 // This ensures that unused input channels are released promptly.
4878 // Otherwise, they might stick around until the window handle is destroyed
4879 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004880 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004881 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004882 if (DEBUG_FOCUS) {
4883 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004884 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004885 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004886 }
chaviw291d88a2019-02-14 10:33:58 -08004887 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888}
4889
4890void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004891 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004892 if (DEBUG_FOCUS) {
4893 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4894 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4895 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004896 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004897 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004898 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 } // release lock
4900
4901 // Wake up poll loop since it may need to make new input dispatching choices.
4902 mLooper->wake();
4903}
4904
Vishnu Nair599f1412021-06-21 10:39:58 -07004905void InputDispatcher::setFocusedApplicationLocked(
4906 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4907 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4908 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4909
4910 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4911 return; // This application is already focused. No need to wake up or change anything.
4912 }
4913
4914 // Set the new application handle.
4915 if (inputApplicationHandle != nullptr) {
4916 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4917 } else {
4918 mFocusedApplicationHandlesByDisplay.erase(displayId);
4919 }
4920
4921 // No matter what the old focused application was, stop waiting on it because it is
4922 // no longer focused.
4923 resetNoFocusedWindowTimeoutLocked();
4924}
4925
Tiger Huang721e26f2018-07-24 22:26:19 +08004926/**
4927 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4928 * the display not specified.
4929 *
4930 * We track any unreleased events for each window. If a window loses the ability to receive the
4931 * released event, we will send a cancel event to it. So when the focused display is changed, we
4932 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4933 * display. The display-specified events won't be affected.
4934 */
4935void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004936 if (DEBUG_FOCUS) {
4937 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4938 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004939 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004940 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004941
4942 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004943 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004944 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004945 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004946 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004947 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004948 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004949 CancelationOptions
4950 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4951 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004952 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004953 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4954 }
4955 }
4956 mFocusedDisplayId = displayId;
4957
Chris Ye3c2d6f52020-08-09 10:39:48 -07004958 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004959 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004960 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004961
Vishnu Nairad321cd2020-08-20 16:40:21 -07004962 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004963 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004964 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004965 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004966 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004967 }
4968 }
4969 }
4970
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004971 if (DEBUG_FOCUS) {
4972 logDispatchStateLocked();
4973 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004974 } // release lock
4975
4976 // Wake up poll loop since it may need to make new input dispatching choices.
4977 mLooper->wake();
4978}
4979
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004981 if (DEBUG_FOCUS) {
4982 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004984
4985 bool changed;
4986 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004987 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004988
4989 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4990 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004991 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992 }
4993
4994 if (mDispatchEnabled && !enabled) {
4995 resetAndDropEverythingLocked("dispatcher is being disabled");
4996 }
4997
4998 mDispatchEnabled = enabled;
4999 mDispatchFrozen = frozen;
5000 changed = true;
5001 } else {
5002 changed = false;
5003 }
5004
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005005 if (DEBUG_FOCUS) {
5006 logDispatchStateLocked();
5007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 } // release lock
5009
5010 if (changed) {
5011 // Wake up poll loop since it may need to make new input dispatching choices.
5012 mLooper->wake();
5013 }
5014}
5015
5016void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005017 if (DEBUG_FOCUS) {
5018 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5019 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005020
5021 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005022 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023
5024 if (mInputFilterEnabled == enabled) {
5025 return;
5026 }
5027
5028 mInputFilterEnabled = enabled;
5029 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5030 } // release lock
5031
5032 // Wake up poll loop since there might be work to do to drop everything.
5033 mLooper->wake();
5034}
5035
Antonio Kanteka042c022022-07-06 16:51:07 -07005036bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5037 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005038 bool needWake = false;
5039 {
5040 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005041 ALOGD_IF(DEBUG_TOUCH_MODE,
5042 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5043 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5044 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5045 mTouchModePerDisplay.count(displayId) == 0
5046 ? "not set"
5047 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5048
Antonio Kantek15beb512022-06-13 22:35:41 +00005049 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5050 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005051 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005052 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005053 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005054 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5055 !recentWindowsAreOwnedByLocked(pid, uid)) {
5056 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5057 "window nor none of the previously interacted window",
5058 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005059 return false;
5060 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005061 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005062 mTouchModePerDisplay[displayId] = inTouchMode;
5063 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5064 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005065 needWake = enqueueInboundEventLocked(std::move(entry));
5066 } // release lock
5067
5068 if (needWake) {
5069 mLooper->wake();
5070 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005071 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005072}
5073
Antonio Kantek48710e42022-03-24 14:19:30 -07005074bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5075 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5076 if (focusedToken == nullptr) {
5077 return false;
5078 }
5079 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5080 return isWindowOwnedBy(windowHandle, pid, uid);
5081}
5082
5083bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5084 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5085 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5086 const sp<WindowInfoHandle> windowHandle =
5087 getWindowHandleLocked(connectionToken);
5088 return isWindowOwnedBy(windowHandle, pid, uid);
5089 }) != mInteractionConnectionTokens.end();
5090}
5091
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005092void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5093 if (opacity < 0 || opacity > 1) {
5094 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5095 return;
5096 }
5097
5098 std::scoped_lock lock(mLock);
5099 mMaximumObscuringOpacityForTouch = opacity;
5100}
5101
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005102std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5103InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005104 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5105 for (TouchedWindow& w : state.windows) {
5106 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005107 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005108 }
5109 }
5110 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005111 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005112}
5113
arthurhungb89ccb02020-12-30 16:19:01 +08005114bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5115 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005116 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005117 if (DEBUG_FOCUS) {
5118 ALOGD("Trivial transfer to same window.");
5119 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005120 return true;
5121 }
5122
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005124 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125
Arthur Hungabbb9d82021-09-01 14:52:30 +00005126 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005127 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005128 if (state == nullptr || touchedWindow == nullptr) {
5129 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130 return false;
5131 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005132
Arthur Hungabbb9d82021-09-01 14:52:30 +00005133 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5134 if (toWindowHandle == nullptr) {
5135 ALOGW("Cannot transfer focus because to window not found.");
5136 return false;
5137 }
5138
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005139 if (DEBUG_FOCUS) {
5140 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005141 touchedWindow->windowHandle->getName().c_str(),
5142 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143 }
5144
Arthur Hungabbb9d82021-09-01 14:52:30 +00005145 // Erase old window.
5146 int32_t oldTargetFlags = touchedWindow->targetFlags;
5147 BitSet32 pointerIds = touchedWindow->pointerIds;
5148 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005149
Arthur Hungabbb9d82021-09-01 14:52:30 +00005150 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005151 nsecs_t downTimeInTarget = now();
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005152 int32_t newTargetFlags =
5153 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5154 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5155 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5156 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005157 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158
Arthur Hungabbb9d82021-09-01 14:52:30 +00005159 // Store the dragging window.
5160 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005161 if (pointerIds.count() != 1) {
5162 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5163 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005164 return false;
5165 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005166 // Track the pointer id for drag window and generate the drag state.
5167 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005168 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169 }
5170
Arthur Hungabbb9d82021-09-01 14:52:30 +00005171 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005172 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5173 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005174 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005175 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005176 CancelationOptions
5177 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5178 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005180 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181 }
5182
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005183 if (DEBUG_FOCUS) {
5184 logDispatchStateLocked();
5185 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005186 } // release lock
5187
5188 // Wake up poll loop since it may need to make new input dispatching choices.
5189 mLooper->wake();
5190 return true;
5191}
5192
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005193/**
5194 * Get the touched foreground window on the given display.
5195 * Return null if there are no windows touched on that display, or if more than one foreground
5196 * window is being touched.
5197 */
5198sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5199 auto stateIt = mTouchStatesByDisplay.find(displayId);
5200 if (stateIt == mTouchStatesByDisplay.end()) {
5201 ALOGI("No touch state on display %" PRId32, displayId);
5202 return nullptr;
5203 }
5204
5205 const TouchState& state = stateIt->second;
5206 sp<WindowInfoHandle> touchedForegroundWindow;
5207 // If multiple foreground windows are touched, return nullptr
5208 for (const TouchedWindow& window : state.windows) {
5209 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5210 if (touchedForegroundWindow != nullptr) {
5211 ALOGI("Two or more foreground windows: %s and %s",
5212 touchedForegroundWindow->getName().c_str(),
5213 window.windowHandle->getName().c_str());
5214 return nullptr;
5215 }
5216 touchedForegroundWindow = window.windowHandle;
5217 }
5218 }
5219 return touchedForegroundWindow;
5220}
5221
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005222// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005223bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005224 sp<IBinder> fromToken;
5225 { // acquire lock
5226 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005227 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005228 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005229 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5230 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005231 return false;
5232 }
5233
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005234 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5235 if (from == nullptr) {
5236 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5237 return false;
5238 }
5239
5240 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005241 } // release lock
5242
5243 return transferTouchFocus(fromToken, destChannelToken);
5244}
5245
Michael Wrightd02c5b62014-02-10 15:10:22 -08005246void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005247 if (DEBUG_FOCUS) {
5248 ALOGD("Resetting and dropping all events (%s).", reason);
5249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250
5251 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5252 synthesizeCancelationEventsForAllConnectionsLocked(options);
5253
5254 resetKeyRepeatLocked();
5255 releasePendingEventLocked();
5256 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005257 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005259 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005260 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005262 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263}
5264
5265void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005266 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267 dumpDispatchStateLocked(dump);
5268
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005269 std::istringstream stream(dump);
5270 std::string line;
5271
5272 while (std::getline(stream, line, '\n')) {
5273 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274 }
5275}
5276
Prabir Pradhan99987712020-11-10 18:43:05 -08005277std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5278 std::string dump;
5279
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005280 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5281 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005282
5283 std::string windowName = "None";
5284 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005285 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005286 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5287 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5288 : "token has capture without window";
5289 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005290 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005291
5292 return dump;
5293}
5294
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005295void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005296 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5297 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5298 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005299 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300
Tiger Huang721e26f2018-07-24 22:26:19 +08005301 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5302 dump += StringPrintf(INDENT "FocusedApplications:\n");
5303 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5304 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005305 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005306 const std::chrono::duration timeout =
5307 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005308 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005309 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005310 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005313 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005315
Vishnu Nairc519ff72021-01-21 08:23:08 -08005316 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005317 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005319 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005320 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005321 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
5322 dump += StringPrintf(INDENT2 "%d: deviceId=%d, source=0x%08x\n", displayId,
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005323 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005324 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005325 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005326 for (size_t i = 0; i < state.windows.size(); i++) {
5327 const TouchedWindow& touchedWindow = state.windows[i];
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005328 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, "
5329 "targetFlags=0x%x, firstDownTimeInTarget=%" PRId64
5330 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005331 i, touchedWindow.windowHandle->getName().c_str(),
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005332 touchedWindow.pointerIds.value, touchedWindow.targetFlags,
5333 ns2ms(touchedWindow.firstDownTimeInTarget.value_or(0)));
Jeff Brownf086ddb2014-02-11 14:28:48 -08005334 }
5335 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005336 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338 }
5339 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005340 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 }
5342
arthurhung6d4bed92021-03-17 11:59:33 +08005343 if (mDragState) {
5344 dump += StringPrintf(INDENT "DragState:\n");
5345 mDragState->dump(dump, INDENT2);
5346 }
5347
Arthur Hungb92218b2018-08-14 12:00:21 +08005348 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005349 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5350 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5351 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5352 const auto& displayInfo = it->second;
5353 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5354 displayInfo.logicalHeight);
5355 displayInfo.transform.dump(dump, "transform", INDENT4);
5356 } else {
5357 dump += INDENT2 "No DisplayInfo found!\n";
5358 }
5359
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005360 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005361 dump += INDENT2 "Windows:\n";
5362 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005363 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5364 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005365
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005366 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005367 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005368 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005369 "applicationInfo.name=%s, "
5370 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005371 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005372 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005373 windowInfo->displayId,
5374 windowInfo->inputConfig.string().c_str(),
5375 windowInfo->alpha, windowInfo->frameLeft,
5376 windowInfo->frameTop, windowInfo->frameRight,
5377 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005378 windowInfo->applicationInfo.name.c_str(),
5379 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005380 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005381 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005382 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005383 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005384 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005385 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005386 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005387 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005388 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005389 }
5390 } else {
5391 dump += INDENT2 "Windows: <none>\n";
5392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393 }
5394 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005395 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396 }
5397
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005398 if (!mGlobalMonitorsByDisplay.empty()) {
5399 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5400 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005401 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005403 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005404 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405 }
5406
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005407 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408
5409 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005410 if (!mRecentQueue.empty()) {
5411 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005412 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005413 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005414 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005415 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 }
5417 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005418 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419 }
5420
5421 // Dump event currently being dispatched.
5422 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005423 dump += INDENT "PendingEvent:\n";
5424 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005425 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005426 dump += StringPrintf(", age=%" PRId64 "ms\n",
5427 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005429 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430 }
5431
5432 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005433 if (!mInboundQueue.empty()) {
5434 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005435 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005436 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005437 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005438 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439 }
5440 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005441 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442 }
5443
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005444 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005445 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005446 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5447 const KeyReplacement& replacement = pair.first;
5448 int32_t newKeyCode = pair.second;
5449 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005450 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005451 }
5452 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005453 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005454 }
5455
Prabir Pradhancef936d2021-07-21 16:17:52 +00005456 if (!mCommandQueue.empty()) {
5457 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5458 } else {
5459 dump += INDENT "CommandQueue: <empty>\n";
5460 }
5461
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005462 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005463 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005464 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005465 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005466 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005467 connection->inputChannel->getFd().get(),
5468 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005469 connection->getWindowName().c_str(),
5470 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005471 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005472
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005473 if (!connection->outboundQueue.empty()) {
5474 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5475 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005476 dump += dumpQueue(connection->outboundQueue, currentTime);
5477
Michael Wrightd02c5b62014-02-10 15:10:22 -08005478 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005479 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480 }
5481
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005482 if (!connection->waitQueue.empty()) {
5483 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5484 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005485 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005487 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 }
5489 }
5490 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005491 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005492 }
5493
5494 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005495 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5496 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005498 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499 }
5500
Antonio Kantek15beb512022-06-13 22:35:41 +00005501 if (!mTouchModePerDisplay.empty()) {
5502 dump += INDENT "TouchModePerDisplay:\n";
5503 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5504 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5505 std::to_string(touchMode).c_str());
5506 }
5507 } else {
5508 dump += INDENT "TouchModePerDisplay: <none>\n";
5509 }
5510
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005511 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005512 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5513 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5514 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005515 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005516 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517}
5518
Michael Wright3dd60e22019-03-27 22:06:44 +00005519void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5520 const size_t numMonitors = monitors.size();
5521 for (size_t i = 0; i < numMonitors; i++) {
5522 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005523 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005524 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5525 dump += "\n";
5526 }
5527}
5528
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005529class LooperEventCallback : public LooperCallback {
5530public:
5531 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5532 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5533
5534private:
5535 std::function<int(int events)> mCallback;
5536};
5537
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005538Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005539 if (DEBUG_CHANNEL_CREATION) {
5540 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005543 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005544 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005545 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005546
5547 if (result) {
5548 return base::Error(result) << "Failed to open input channel pair with name " << name;
5549 }
5550
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005552 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005553 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005554 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005555 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005556 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005558 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5559 ALOGE("Created a new connection, but the token %p is already known", token.get());
5560 }
5561 mConnectionsByToken.emplace(token, connection);
5562
5563 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5564 this, std::placeholders::_1, token);
5565
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005566 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5567 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005568 } // release lock
5569
5570 // Wake the looper because some connections have changed.
5571 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005572 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573}
5574
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005575Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005576 const std::string& name,
5577 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005578 std::shared_ptr<InputChannel> serverChannel;
5579 std::unique_ptr<InputChannel> clientChannel;
5580 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5581 if (result) {
5582 return base::Error(result) << "Failed to open input channel pair with name " << name;
5583 }
5584
Michael Wright3dd60e22019-03-27 22:06:44 +00005585 { // acquire lock
5586 std::scoped_lock _l(mLock);
5587
5588 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005589 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5590 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005591 }
5592
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005593 sp<Connection> connection =
5594 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005595 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005596 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005597
5598 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5599 ALOGE("Created a new connection, but the token %p is already known", token.get());
5600 }
5601 mConnectionsByToken.emplace(token, connection);
5602 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5603 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005604
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005605 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005606
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005607 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5608 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005609 }
Garfield Tan15601662020-09-22 15:32:38 -07005610
Michael Wright3dd60e22019-03-27 22:06:44 +00005611 // Wake the looper because some connections have changed.
5612 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005613 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005614}
5615
Garfield Tan15601662020-09-22 15:32:38 -07005616status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005618 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005619
Garfield Tan15601662020-09-22 15:32:38 -07005620 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621 if (status) {
5622 return status;
5623 }
5624 } // release lock
5625
5626 // Wake the poll loop because removing the connection may have changed the current
5627 // synchronization state.
5628 mLooper->wake();
5629 return OK;
5630}
5631
Garfield Tan15601662020-09-22 15:32:38 -07005632status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5633 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005634 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005635 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005636 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005637 return BAD_VALUE;
5638 }
5639
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005640 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005641
Michael Wrightd02c5b62014-02-10 15:10:22 -08005642 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005643 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005644 }
5645
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005646 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647
5648 nsecs_t currentTime = now();
5649 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5650
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005651 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005652 return OK;
5653}
5654
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005655void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005656 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5657 auto& [displayId, monitors] = *it;
5658 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5659 return monitor.inputChannel->getConnectionToken() == connectionToken;
5660 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005661
Michael Wright3dd60e22019-03-27 22:06:44 +00005662 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005663 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005664 } else {
5665 ++it;
5666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005667 }
5668}
5669
Michael Wright3dd60e22019-03-27 22:06:44 +00005670status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005671 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005672 return pilferPointersLocked(token);
5673}
Michael Wright3dd60e22019-03-27 22:06:44 +00005674
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005675status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005676 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5677 if (!requestingChannel) {
5678 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5679 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005680 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005681
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005682 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005683 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005684 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5685 " Ignoring.");
5686 return BAD_VALUE;
5687 }
5688
5689 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005690 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005691 // Send cancel events to all the input channels we're stealing from.
5692 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5693 "input channel stole pointer stream");
5694 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005695 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005696 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005697 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005698 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005699 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005700 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005701 if (channel != nullptr && channel->getConnectionToken() != token) {
5702 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5703 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5704 canceledWindows += channel->getName();
5705 }
5706 }
5707 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5708 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5709 canceledWindows.c_str());
5710
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005711 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005712 // This only blocks relevant pointers to be sent to other windows
5713 window.isPilferingPointers = true;
5714
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005715 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005716 return OK;
5717}
5718
Prabir Pradhan99987712020-11-10 18:43:05 -08005719void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5720 { // acquire lock
5721 std::scoped_lock _l(mLock);
5722 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005723 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005724 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5725 windowHandle != nullptr ? windowHandle->getName().c_str()
5726 : "token without window");
5727 }
5728
Vishnu Nairc519ff72021-01-21 08:23:08 -08005729 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005730 if (focusedToken != windowToken) {
5731 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5732 enabled ? "enable" : "disable");
5733 return;
5734 }
5735
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005736 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005737 ALOGW("Ignoring request to %s Pointer Capture: "
5738 "window has %s requested pointer capture.",
5739 enabled ? "enable" : "disable", enabled ? "already" : "not");
5740 return;
5741 }
5742
Christine Franksb768bb42021-11-29 12:11:31 -08005743 if (enabled) {
5744 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5745 mIneligibleDisplaysForPointerCapture.end(),
5746 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5747 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5748 return;
5749 }
5750 }
5751
Prabir Pradhan99987712020-11-10 18:43:05 -08005752 setPointerCaptureLocked(enabled);
5753 } // release lock
5754
5755 // Wake the thread to process command entries.
5756 mLooper->wake();
5757}
5758
Christine Franksb768bb42021-11-29 12:11:31 -08005759void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5760 { // acquire lock
5761 std::scoped_lock _l(mLock);
5762 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5763 if (!isEligible) {
5764 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5765 }
5766 } // release lock
5767}
5768
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005769std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5770 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005771 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005772 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005773 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005774 }
5775 }
5776 }
5777 return std::nullopt;
5778}
5779
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005780sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005781 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005782 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005783 }
5784
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005785 for (const auto& [token, connection] : mConnectionsByToken) {
5786 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005787 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788 }
5789 }
Robert Carr4e670e52018-08-15 13:26:12 -07005790
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005791 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005792}
5793
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005794std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5795 sp<Connection> connection = getConnectionLocked(connectionToken);
5796 if (connection == nullptr) {
5797 return "<nullptr>";
5798 }
5799 return connection->getInputChannelName();
5800}
5801
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005802void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005803 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005804 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005805}
5806
Prabir Pradhancef936d2021-07-21 16:17:52 +00005807void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5808 const sp<Connection>& connection, uint32_t seq,
5809 bool handled, nsecs_t consumeTime) {
5810 // Handle post-event policy actions.
5811 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5812 if (dispatchEntryIt == connection->waitQueue.end()) {
5813 return;
5814 }
5815 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5816 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5817 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5818 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5819 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5820 }
5821 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5822 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5823 connection->inputChannel->getConnectionToken(),
5824 dispatchEntry->deliveryTime, consumeTime, finishTime);
5825 }
5826
5827 bool restartEvent;
5828 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5829 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5830 restartEvent =
5831 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5832 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5833 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5834 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5835 handled);
5836 } else {
5837 restartEvent = false;
5838 }
5839
5840 // Dequeue the event and start the next cycle.
5841 // Because the lock might have been released, it is possible that the
5842 // contents of the wait queue to have been drained, so we need to double-check
5843 // a few things.
5844 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5845 if (dispatchEntryIt != connection->waitQueue.end()) {
5846 dispatchEntry = *dispatchEntryIt;
5847 connection->waitQueue.erase(dispatchEntryIt);
5848 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5849 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5850 if (!connection->responsive) {
5851 connection->responsive = isConnectionResponsive(*connection);
5852 if (connection->responsive) {
5853 // The connection was unresponsive, and now it's responsive.
5854 processConnectionResponsiveLocked(*connection);
5855 }
5856 }
5857 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005858 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005859 connection->outboundQueue.push_front(dispatchEntry);
5860 traceOutboundQueueLength(*connection);
5861 } else {
5862 releaseDispatchEntry(dispatchEntry);
5863 }
5864 }
5865
5866 // Start the next dispatch cycle for this connection.
5867 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005868}
5869
Prabir Pradhancef936d2021-07-21 16:17:52 +00005870void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5871 const sp<IBinder>& newToken) {
5872 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5873 scoped_unlock unlock(mLock);
5874 mPolicy->notifyFocusChanged(oldToken, newToken);
5875 };
5876 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877}
5878
Prabir Pradhancef936d2021-07-21 16:17:52 +00005879void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5880 auto command = [this, token, x, y]() REQUIRES(mLock) {
5881 scoped_unlock unlock(mLock);
5882 mPolicy->notifyDropWindow(token, x, y);
5883 };
5884 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005885}
5886
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005887void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5888 if (connection == nullptr) {
5889 LOG_ALWAYS_FATAL("Caller must check for nullness");
5890 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005891 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5892 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005893 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005894 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005895 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005896 return;
5897 }
5898 /**
5899 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5900 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5901 * has changed. This could cause newer entries to time out before the already dispatched
5902 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5903 * processes the events linearly. So providing information about the oldest entry seems to be
5904 * most useful.
5905 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005906 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005907 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5908 std::string reason =
5909 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005910 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005911 ns2ms(currentWait),
5912 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005913 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005914 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005915
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005916 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5917
5918 // Stop waking up for events on this connection, it is already unresponsive
5919 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005920}
5921
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005922void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5923 std::string reason =
5924 StringPrintf("%s does not have a focused window", application->getName().c_str());
5925 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005926
Prabir Pradhancef936d2021-07-21 16:17:52 +00005927 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5928 scoped_unlock unlock(mLock);
5929 mPolicy->notifyNoFocusedWindowAnr(application);
5930 };
5931 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005932}
5933
chaviw98318de2021-05-19 16:45:23 -05005934void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005935 const std::string& reason) {
5936 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5937 updateLastAnrStateLocked(windowLabel, reason);
5938}
5939
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005940void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5941 const std::string& reason) {
5942 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005943 updateLastAnrStateLocked(windowLabel, reason);
5944}
5945
5946void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5947 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005949 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005950 struct tm tm;
5951 localtime_r(&t, &tm);
5952 char timestr[64];
5953 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005954 mLastAnrState.clear();
5955 mLastAnrState += INDENT "ANR:\n";
5956 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005957 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5958 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005959 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005960}
5961
Prabir Pradhancef936d2021-07-21 16:17:52 +00005962void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5963 KeyEntry& entry) {
5964 const KeyEvent event = createKeyEvent(entry);
5965 nsecs_t delay = 0;
5966 { // release lock
5967 scoped_unlock unlock(mLock);
5968 android::base::Timer t;
5969 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5970 entry.policyFlags);
5971 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5972 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5973 std::to_string(t.duration().count()).c_str());
5974 }
5975 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005976
5977 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005978 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005979 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005980 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005981 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005982 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5983 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005985}
5986
Prabir Pradhancef936d2021-07-21 16:17:52 +00005987void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005988 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005989 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005990 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005991 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005992 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005993 };
5994 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005995}
5996
Prabir Pradhanedd96402022-02-15 01:46:16 -08005997void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5998 std::optional<int32_t> pid) {
5999 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006000 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08006001 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006002 };
6003 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006004}
6005
6006/**
6007 * Tell the policy that a connection has become unresponsive so that it can start ANR.
6008 * Check whether the connection of interest is a monitor or a window, and add the corresponding
6009 * command entry to the command queue.
6010 */
6011void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
6012 std::string reason) {
6013 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006014 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006015 if (connection.monitor) {
6016 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6017 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006018 pid = findMonitorPidByTokenLocked(connectionToken);
6019 } else {
6020 // The connection is a window
6021 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6022 reason.c_str());
6023 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6024 if (handle != nullptr) {
6025 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006026 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006027 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006028 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006029}
6030
6031/**
6032 * Tell the policy that a connection has become responsive so that it can stop ANR.
6033 */
6034void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6035 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006036 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006037 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006038 pid = findMonitorPidByTokenLocked(connectionToken);
6039 } else {
6040 // The connection is a window
6041 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6042 if (handle != nullptr) {
6043 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006044 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006045 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006046 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006047}
6048
Prabir Pradhancef936d2021-07-21 16:17:52 +00006049bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006050 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006051 KeyEntry& keyEntry, bool handled) {
6052 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006053 if (!handled) {
6054 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006055 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006056 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006057 return false;
6058 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006059
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006060 // Get the fallback key state.
6061 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006062 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006063 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006064 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006065 connection->inputState.removeFallbackKey(originalKeyCode);
6066 }
6067
6068 if (handled || !dispatchEntry->hasForegroundTarget()) {
6069 // If the application handles the original key for which we previously
6070 // generated a fallback or if the window is not a foreground window,
6071 // then cancel the associated fallback key, if any.
6072 if (fallbackKeyCode != -1) {
6073 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006074 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6075 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6076 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6077 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6078 keyEntry.policyFlags);
6079 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006080 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006081 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006082
6083 mLock.unlock();
6084
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006085 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006086 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006087
6088 mLock.lock();
6089
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006090 // Cancel the fallback key.
6091 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006093 "application handled the original non-fallback key "
6094 "or is no longer a foreground target, "
6095 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006096 options.keyCode = fallbackKeyCode;
6097 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006098 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006099 connection->inputState.removeFallbackKey(originalKeyCode);
6100 }
6101 } else {
6102 // If the application did not handle a non-fallback key, first check
6103 // that we are in a good state to perform unhandled key event processing
6104 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006105 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006106 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006107 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6108 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6109 "since this is not an initial down. "
6110 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6111 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6112 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006113 return false;
6114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006115
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006116 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006117 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6118 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6119 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6120 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6121 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006122 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006123
6124 mLock.unlock();
6125
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006126 bool fallback =
6127 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006128 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006129
6130 mLock.lock();
6131
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006132 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006133 connection->inputState.removeFallbackKey(originalKeyCode);
6134 return false;
6135 }
6136
6137 // Latch the fallback keycode for this key on an initial down.
6138 // The fallback keycode cannot change at any other point in the lifecycle.
6139 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006140 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006141 fallbackKeyCode = event.getKeyCode();
6142 } else {
6143 fallbackKeyCode = AKEYCODE_UNKNOWN;
6144 }
6145 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6146 }
6147
6148 ALOG_ASSERT(fallbackKeyCode != -1);
6149
6150 // Cancel the fallback key if the policy decides not to send it anymore.
6151 // We will continue to dispatch the key to the policy but we will no
6152 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006153 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6154 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006155 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6156 if (fallback) {
6157 ALOGD("Unhandled key event: Policy requested to send key %d"
6158 "as a fallback for %d, but on the DOWN it had requested "
6159 "to send %d instead. Fallback canceled.",
6160 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6161 } else {
6162 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6163 "but on the DOWN it had requested to send %d. "
6164 "Fallback canceled.",
6165 originalKeyCode, fallbackKeyCode);
6166 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006167 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006168
6169 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6170 "canceling fallback, policy no longer desires it");
6171 options.keyCode = fallbackKeyCode;
6172 synthesizeCancelationEventsForConnectionLocked(connection, options);
6173
6174 fallback = false;
6175 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006176 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006177 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006178 }
6179 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006181 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6182 {
6183 std::string msg;
6184 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6185 connection->inputState.getFallbackKeys();
6186 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6187 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6188 }
6189 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6190 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006191 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006192 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006193
6194 if (fallback) {
6195 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006196 keyEntry.eventTime = event.getEventTime();
6197 keyEntry.deviceId = event.getDeviceId();
6198 keyEntry.source = event.getSource();
6199 keyEntry.displayId = event.getDisplayId();
6200 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6201 keyEntry.keyCode = fallbackKeyCode;
6202 keyEntry.scanCode = event.getScanCode();
6203 keyEntry.metaState = event.getMetaState();
6204 keyEntry.repeatCount = event.getRepeatCount();
6205 keyEntry.downTime = event.getDownTime();
6206 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006207
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006208 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6209 ALOGD("Unhandled key event: Dispatching fallback key. "
6210 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6211 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6212 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006213 return true; // restart the event
6214 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006215 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6216 ALOGD("Unhandled key event: No fallback key.");
6217 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006218
6219 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006220 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006221 }
6222 }
6223 return false;
6224}
6225
Prabir Pradhancef936d2021-07-21 16:17:52 +00006226bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006227 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006228 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006229 return false;
6230}
6231
Michael Wrightd02c5b62014-02-10 15:10:22 -08006232void InputDispatcher::traceInboundQueueLengthLocked() {
6233 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006234 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006235 }
6236}
6237
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006238void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006239 if (ATRACE_ENABLED()) {
6240 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006241 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6242 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006243 }
6244}
6245
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006246void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006247 if (ATRACE_ENABLED()) {
6248 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006249 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6250 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006251 }
6252}
6253
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006254void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006255 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006257 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006258 dumpDispatchStateLocked(dump);
6259
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006260 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006261 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006262 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006263 }
6264}
6265
6266void InputDispatcher::monitor() {
6267 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006268 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006269 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006270 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006271}
6272
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006273/**
6274 * Wake up the dispatcher and wait until it processes all events and commands.
6275 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6276 * this method can be safely called from any thread, as long as you've ensured that
6277 * the work you are interested in completing has already been queued.
6278 */
6279bool InputDispatcher::waitForIdle() {
6280 /**
6281 * Timeout should represent the longest possible time that a device might spend processing
6282 * events and commands.
6283 */
6284 constexpr std::chrono::duration TIMEOUT = 100ms;
6285 std::unique_lock lock(mLock);
6286 mLooper->wake();
6287 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6288 return result == std::cv_status::no_timeout;
6289}
6290
Vishnu Naire798b472020-07-23 13:52:21 -07006291/**
6292 * Sets focus to the window identified by the token. This must be called
6293 * after updating any input window handles.
6294 *
6295 * Params:
6296 * request.token - input channel token used to identify the window that should gain focus.
6297 * request.focusedToken - the token that the caller expects currently to be focused. If the
6298 * specified token does not match the currently focused window, this request will be dropped.
6299 * If the specified focused token matches the currently focused window, the call will succeed.
6300 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6301 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6302 * when requesting the focus change. This determines which request gets
6303 * precedence if there is a focus change request from another source such as pointer down.
6304 */
Vishnu Nair958da932020-08-21 17:12:37 -07006305void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6306 { // acquire lock
6307 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006308 std::optional<FocusResolver::FocusChanges> changes =
6309 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6310 if (changes) {
6311 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006312 }
6313 } // release lock
6314 // Wake up poll loop since it may need to make new input dispatching choices.
6315 mLooper->wake();
6316}
6317
Vishnu Nairc519ff72021-01-21 08:23:08 -08006318void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6319 if (changes.oldFocus) {
6320 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006321 if (focusedInputChannel) {
6322 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6323 "focus left window");
6324 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006325 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006326 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006327 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006328 if (changes.newFocus) {
6329 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006330 }
6331
Prabir Pradhan99987712020-11-10 18:43:05 -08006332 // If a window has pointer capture, then it must have focus. We need to ensure that this
6333 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6334 // If the window loses focus before it loses pointer capture, then the window can be in a state
6335 // where it has pointer capture but not focus, violating the contract. Therefore we must
6336 // dispatch the pointer capture event before the focus event. Since focus events are added to
6337 // the front of the queue (above), we add the pointer capture event to the front of the queue
6338 // after the focus events are added. This ensures the pointer capture event ends up at the
6339 // front.
6340 disablePointerCaptureForcedLocked();
6341
Vishnu Nairc519ff72021-01-21 08:23:08 -08006342 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006343 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006344 }
6345}
Vishnu Nair958da932020-08-21 17:12:37 -07006346
Prabir Pradhan99987712020-11-10 18:43:05 -08006347void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006348 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006349 return;
6350 }
6351
6352 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6353
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006354 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006355 setPointerCaptureLocked(false);
6356 }
6357
6358 if (!mWindowTokenWithPointerCapture) {
6359 // No need to send capture changes because no window has capture.
6360 return;
6361 }
6362
6363 if (mPendingEvent != nullptr) {
6364 // Move the pending event to the front of the queue. This will give the chance
6365 // for the pending event to be dropped if it is a captured event.
6366 mInboundQueue.push_front(mPendingEvent);
6367 mPendingEvent = nullptr;
6368 }
6369
6370 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006371 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006372 mInboundQueue.push_front(std::move(entry));
6373}
6374
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006375void InputDispatcher::setPointerCaptureLocked(bool enable) {
6376 mCurrentPointerCaptureRequest.enable = enable;
6377 mCurrentPointerCaptureRequest.seq++;
6378 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006379 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006380 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006381 };
6382 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006383}
6384
Vishnu Nair599f1412021-06-21 10:39:58 -07006385void InputDispatcher::displayRemoved(int32_t displayId) {
6386 { // acquire lock
6387 std::scoped_lock _l(mLock);
6388 // Set an empty list to remove all handles from the specific display.
6389 setInputWindowsLocked(/* window handles */ {}, displayId);
6390 setFocusedApplicationLocked(displayId, nullptr);
6391 // Call focus resolver to clean up stale requests. This must be called after input windows
6392 // have been removed for the removed display.
6393 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006394 // Reset pointer capture eligibility, regardless of previous state.
6395 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006396 // Remove the associated touch mode state.
6397 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006398 } // release lock
6399
6400 // Wake up poll loop since it may need to make new input dispatching choices.
6401 mLooper->wake();
6402}
6403
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006404void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6405 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006406 // The listener sends the windows as a flattened array. Separate the windows by display for
6407 // more convenient parsing.
6408 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006409 for (const auto& info : windowInfos) {
6410 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006411 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006412 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006413
6414 { // acquire lock
6415 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006416
6417 // Ensure that we have an entry created for all existing displays so that if a displayId has
6418 // no windows, we can tell that the windows were removed from the display.
6419 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6420 handlesPerDisplay[displayId];
6421 }
6422
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006423 mDisplayInfos.clear();
6424 for (const auto& displayInfo : displayInfos) {
6425 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6426 }
6427
6428 for (const auto& [displayId, handles] : handlesPerDisplay) {
6429 setInputWindowsLocked(handles, displayId);
6430 }
6431 }
6432 // Wake up poll loop since it may need to make new input dispatching choices.
6433 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006434}
6435
Vishnu Nair062a8672021-09-03 16:07:44 -07006436bool InputDispatcher::shouldDropInput(
6437 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006438 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6439 (windowHandle->getInfo()->inputConfig.test(
6440 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006441 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006442 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6443 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006444 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006445 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006446 windowHandle->getInfo()->displayId);
6447 return true;
6448 }
6449 return false;
6450}
6451
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006452void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6453 const std::vector<gui::WindowInfo>& windowInfos,
6454 const std::vector<DisplayInfo>& displayInfos) {
6455 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6456}
6457
Arthur Hungdfd528e2021-12-08 13:23:04 +00006458void InputDispatcher::cancelCurrentTouch() {
6459 {
6460 std::scoped_lock _l(mLock);
6461 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6462 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6463 "cancel current touch");
6464 synthesizeCancelationEventsForAllConnectionsLocked(options);
6465
6466 mTouchStatesByDisplay.clear();
6467 mLastHoverWindowHandle.clear();
6468 }
6469 // Wake up poll loop since there might be work to do.
6470 mLooper->wake();
6471}
6472
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006473void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6474 std::scoped_lock _l(mLock);
6475 mMonitorDispatchingTimeout = timeout;
6476}
6477
Garfield Tane84e6f92019-08-29 17:28:41 -07006478} // namespace android::inputdispatcher