blob: 8ae59390c0ddb37180f7c0f61811353a68bae895 [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>
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -080032#include <input/PrintTools.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070033#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010034#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070035#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080036
Michael Wright44753b12020-07-08 13:48:11 +010037#include <cerrno>
38#include <cinttypes>
39#include <climits>
40#include <cstddef>
41#include <ctime>
42#include <queue>
43#include <sstream>
44
45#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000046#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070047#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010048
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#define INDENT " "
50#define INDENT2 " "
51#define INDENT3 " "
52#define INDENT4 " "
53
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080054using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000055using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080056using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070057using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050058using android::gui::FocusRequest;
59using android::gui::TouchOcclusionMode;
60using android::gui::WindowInfo;
61using android::gui::WindowInfoHandle;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100062using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080063using android::os::InputEventInjectionResult;
64using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080065
Garfield Tane84e6f92019-08-29 17:28:41 -070066namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080067
Prabir Pradhancef936d2021-07-21 16:17:52 +000068namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000069// Temporarily releases a held mutex for the lifetime of the instance.
70// Named to match std::scoped_lock
71class scoped_unlock {
72public:
73 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
74 ~scoped_unlock() { mMutex.lock(); }
75
76private:
77 std::mutex& mMutex;
78};
79
Michael Wrightd02c5b62014-02-10 15:10:22 -080080// Default input dispatching timeout if there is no focused application or paused window
81// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080082const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
83 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
84 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080085
86// Amount of time to allow for all pending events to be processed when an app switch
87// key is on the way. This is used to preempt input dispatch and drop input events
88// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000089constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080091const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
Michael Wrightd02c5b62014-02-10 15:10:22 -080093// 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 +000094constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
95
96// Log a warning when an interception call takes longer than this to process.
97constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080098
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -070099// Additional key latency in case a connection is still processing some motion events.
100// This will help with the case when a user touched a button that opens a new window,
101// and gives us the chance to dispatch the key to this new window.
102constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000105constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
106
Antonio Kantekea47acb2021-12-23 12:41:25 -0800107// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108constexpr int LOGTAG_INPUT_INTERACTION = 62000;
109constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000110constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000111
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000112inline nsecs_t now() {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800113 return systemTime(SYSTEM_TIME_MONOTONIC);
114}
115
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000116inline const char* toString(bool value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800117 return value ? "true" : "false";
118}
119
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000120inline const std::string toString(const sp<IBinder>& binder) {
Bernardo Rufino49d99e42021-01-18 15:16:59 +0000121 if (binder == nullptr) {
122 return "<null>";
123 }
124 return StringPrintf("%p", binder.get());
125}
126
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000127inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700128 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
129 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130}
131
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000132bool isValidKeyAction(int32_t action) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800133 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700134 case AKEY_EVENT_ACTION_DOWN:
135 case AKEY_EVENT_ACTION_UP:
136 return true;
137 default:
138 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139 }
140}
141
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000142bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700143 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 ALOGE("Key event has invalid action code 0x%x", action);
145 return false;
146 }
147 return true;
148}
149
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000150bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800151 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700152 case AMOTION_EVENT_ACTION_DOWN:
153 case AMOTION_EVENT_ACTION_UP:
154 case AMOTION_EVENT_ACTION_CANCEL:
155 case AMOTION_EVENT_ACTION_MOVE:
156 case AMOTION_EVENT_ACTION_OUTSIDE:
157 case AMOTION_EVENT_ACTION_HOVER_ENTER:
158 case AMOTION_EVENT_ACTION_HOVER_MOVE:
159 case AMOTION_EVENT_ACTION_HOVER_EXIT:
160 case AMOTION_EVENT_ACTION_SCROLL:
161 return true;
162 case AMOTION_EVENT_ACTION_POINTER_DOWN:
163 case AMOTION_EVENT_ACTION_POINTER_UP: {
164 int32_t index = getMotionEventActionPointerIndex(action);
165 return index >= 0 && index < pointerCount;
166 }
167 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
168 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
169 return actionButton != 0;
170 default:
171 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800172 }
173}
174
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000175int64_t millis(std::chrono::nanoseconds t) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500176 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
177}
178
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000179bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
180 const PointerProperties* pointerProperties) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700181 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800182 ALOGE("Motion event has invalid action code 0x%x", action);
183 return false;
184 }
185 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800186 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %zu.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700187 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800188 return false;
189 }
190 BitSet32 pointerIdBits;
191 for (size_t i = 0; i < pointerCount; i++) {
192 int32_t id = pointerProperties[i].id;
193 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700194 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
195 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196 return false;
197 }
198 if (pointerIdBits.hasBit(id)) {
199 ALOGE("Motion event has duplicate pointer id %d", id);
200 return false;
201 }
202 pointerIdBits.markBit(id);
203 }
204 return true;
205}
206
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000207std::string dumpRegion(const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800208 if (region.isEmpty()) {
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000209 return "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 }
211
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000212 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800213 bool first = true;
214 Region::const_iterator cur = region.begin();
215 Region::const_iterator const tail = region.end();
216 while (cur != tail) {
217 if (first) {
218 first = false;
219 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800220 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800222 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 cur++;
224 }
Bernardo Rufino53fc31e2020-11-03 11:01:07 +0000225 return dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800226}
227
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000228std::string dumpQueue(const std::deque<DispatchEntry*>& queue, nsecs_t currentTime) {
Siarhei Vishniakou14411c92020-09-18 21:15:05 -0500229 constexpr size_t maxEntries = 50; // max events to print
230 constexpr size_t skipBegin = maxEntries / 2;
231 const size_t skipEnd = queue.size() - maxEntries / 2;
232 // skip from maxEntries / 2 ... size() - maxEntries/2
233 // only print from 0 .. skipBegin and then from skipEnd .. size()
234
235 std::string dump;
236 for (size_t i = 0; i < queue.size(); i++) {
237 const DispatchEntry& entry = *queue[i];
238 if (i >= skipBegin && i < skipEnd) {
239 dump += StringPrintf(INDENT4 "<skipped %zu entries>\n", skipEnd - skipBegin);
240 i = skipEnd - 1; // it will be incremented to "skipEnd" by 'continue'
241 continue;
242 }
243 dump.append(INDENT4);
244 dump += entry.eventEntry->getDescription();
245 dump += StringPrintf(", seq=%" PRIu32
246 ", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64 "ms",
247 entry.seq, entry.targetFlags, entry.resolvedAction,
248 ns2ms(currentTime - entry.eventEntry->eventTime));
249 if (entry.deliveryTime != 0) {
250 // This entry was delivered, so add information on how long we've been waiting
251 dump += StringPrintf(", wait=%" PRId64 "ms", ns2ms(currentTime - entry.deliveryTime));
252 }
253 dump.append("\n");
254 }
255 return dump;
256}
257
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700258/**
259 * Find the entry in std::unordered_map by key, and return it.
260 * If the entry is not found, return a default constructed entry.
261 *
262 * Useful when the entries are vectors, since an empty vector will be returned
263 * if the entry is not found.
264 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
265 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700266template <typename K, typename V>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000267V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700268 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700269 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800270}
271
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000272bool haveSameToken(const sp<WindowInfoHandle>& first, const sp<WindowInfoHandle>& second) {
chaviwaf87b3e2019-10-01 16:59:28 -0700273 if (first == second) {
274 return true;
275 }
276
277 if (first == nullptr || second == nullptr) {
278 return false;
279 }
280
281 return first->getToken() == second->getToken();
282}
283
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000284bool haveSameApplicationToken(const WindowInfo* first, const WindowInfo* second) {
Bernardo Rufino1ff9d592021-01-18 16:58:57 +0000285 if (first == nullptr || second == nullptr) {
286 return false;
287 }
288 return first->applicationInfo.token != nullptr &&
289 first->applicationInfo.token == second->applicationInfo.token;
290}
291
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000292std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
293 std::shared_ptr<EventEntry> eventEntry,
294 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700295 if (inputTarget.useDefaultPointerTransform()) {
296 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700297 return std::make_unique<DispatchEntry>(eventEntry, inputTargetFlags, transform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700298 inputTarget.displayTransform,
299 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000300 }
301
302 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
303 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
304
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700305 std::vector<PointerCoords> pointerCoords;
306 pointerCoords.resize(motionEntry.pointerCount);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000307
308 // Use the first pointer information to normalize all other pointers. This could be any pointer
309 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700310 // uses the transform for the normalized pointer.
311 const ui::Transform& firstPointerTransform =
312 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
313 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000314
315 // Iterate through all pointers in the event to normalize against the first.
316 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
317 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
318 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700319 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000320
321 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700322 // First, apply the current pointer's transform to update the coordinates into
323 // window space.
324 pointerCoords[pointerIndex].transform(currTransform);
325 // Next, apply the inverse transform of the normalized coordinates so the
326 // current coordinates are transformed into the normalized coordinate space.
327 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000328 }
329
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700330 std::unique_ptr<MotionEntry> combinedMotionEntry =
331 std::make_unique<MotionEntry>(motionEntry.id, motionEntry.eventTime,
332 motionEntry.deviceId, motionEntry.source,
333 motionEntry.displayId, motionEntry.policyFlags,
334 motionEntry.action, motionEntry.actionButton,
335 motionEntry.flags, motionEntry.metaState,
336 motionEntry.buttonState, motionEntry.classification,
337 motionEntry.edgeFlags, motionEntry.xPrecision,
338 motionEntry.yPrecision, motionEntry.xCursorPosition,
339 motionEntry.yCursorPosition, motionEntry.downTime,
340 motionEntry.pointerCount, motionEntry.pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +0000341 pointerCoords.data());
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000342
343 if (motionEntry.injectionState) {
344 combinedMotionEntry->injectionState = motionEntry.injectionState;
345 combinedMotionEntry->injectionState->refCount += 1;
346 }
347
348 std::unique_ptr<DispatchEntry> dispatchEntry =
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700349 std::make_unique<DispatchEntry>(std::move(combinedMotionEntry), inputTargetFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700350 firstPointerTransform, inputTarget.displayTransform,
351 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000352 return dispatchEntry;
353}
354
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000355status_t openInputChannelPair(const std::string& name, std::shared_ptr<InputChannel>& serverChannel,
356 std::unique_ptr<InputChannel>& clientChannel) {
Garfield Tan15601662020-09-22 15:32:38 -0700357 std::unique_ptr<InputChannel> uniqueServerChannel;
358 status_t result = InputChannel::openInputChannelPair(name, uniqueServerChannel, clientChannel);
359
360 serverChannel = std::move(uniqueServerChannel);
361 return result;
362}
363
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500364template <typename T>
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000365bool sharedPointersEqual(const std::shared_ptr<T>& lhs, const std::shared_ptr<T>& rhs) {
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -0500366 if (lhs == nullptr && rhs == nullptr) {
367 return true;
368 }
369 if (lhs == nullptr || rhs == nullptr) {
370 return false;
371 }
372 return *lhs == *rhs;
373}
374
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000375KeyEvent createKeyEvent(const KeyEntry& entry) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +0000376 KeyEvent event;
377 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
378 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
379 entry.repeatCount, entry.downTime, entry.eventTime);
380 return event;
381}
382
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000383bool shouldReportMetricsForConnection(const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000384 // Do not keep track of gesture monitors. They receive every event and would disproportionately
385 // affect the statistics.
386 if (connection.monitor) {
387 return false;
388 }
389 // If the connection is experiencing ANR, let's skip it. We have separate ANR metrics
390 if (!connection.responsive) {
391 return false;
392 }
393 return true;
394}
395
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000396bool shouldReportFinishedEvent(const DispatchEntry& dispatchEntry, const Connection& connection) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000397 const EventEntry& eventEntry = *dispatchEntry.eventEntry;
398 const int32_t& inputEventId = eventEntry.id;
399 if (inputEventId != dispatchEntry.resolvedEventId) {
400 // Event was transmuted
401 return false;
402 }
403 if (inputEventId == android::os::IInputConstants::INVALID_INPUT_EVENT_ID) {
404 return false;
405 }
406 // Only track latency for events that originated from hardware
407 if (eventEntry.isSynthesized()) {
408 return false;
409 }
410 const EventEntry::Type& inputEventEntryType = eventEntry.type;
411 if (inputEventEntryType == EventEntry::Type::KEY) {
412 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
413 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
414 return false;
415 }
416 } else if (inputEventEntryType == EventEntry::Type::MOTION) {
417 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
418 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL ||
419 motionEntry.action == AMOTION_EVENT_ACTION_HOVER_EXIT) {
420 return false;
421 }
422 } else {
423 // Not a key or a motion
424 return false;
425 }
426 if (!shouldReportMetricsForConnection(connection)) {
427 return false;
428 }
429 return true;
430}
431
Prabir Pradhancef936d2021-07-21 16:17:52 +0000432/**
433 * Connection is responsive if it has no events in the waitQueue that are older than the
434 * current time.
435 */
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000436bool isConnectionResponsive(const Connection& connection) {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000437 const nsecs_t currentTime = now();
438 for (const DispatchEntry* entry : connection.waitQueue) {
439 if (entry->timeoutTime < currentTime) {
440 return false;
441 }
442 }
443 return true;
444}
445
Antonio Kantekf16f2832021-09-28 04:39:20 +0000446// Returns true if the event type passed as argument represents a user activity.
447bool isUserActivityEvent(const EventEntry& eventEntry) {
448 switch (eventEntry.type) {
449 case EventEntry::Type::FOCUS:
450 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
451 case EventEntry::Type::DRAG:
452 case EventEntry::Type::TOUCH_MODE_CHANGED:
453 case EventEntry::Type::SENSOR:
454 case EventEntry::Type::CONFIGURATION_CHANGED:
455 return false;
456 case EventEntry::Type::DEVICE_RESET:
457 case EventEntry::Type::KEY:
458 case EventEntry::Type::MOTION:
459 return true;
460 }
461}
462
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800463// Returns true if the given window can accept pointer events at the given display location.
Prabir Pradhand65552b2021-10-07 11:23:50 -0700464bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, int32_t x, int32_t y,
465 bool isStylus) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800466 const auto inputConfig = windowInfo.inputConfig;
467 if (windowInfo.displayId != displayId ||
468 inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800469 return false;
470 }
Prabir Pradhand65552b2021-10-07 11:23:50 -0700471 const bool windowCanInterceptTouch = isStylus && windowInfo.interceptsStylus();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -0800472 if (inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) && !windowCanInterceptTouch) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800473 return false;
474 }
Prabir Pradhan06349042022-02-04 09:19:17 -0800475 if (!windowInfo.touchableRegionContainsPoint(x, y)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800476 return false;
477 }
478 return true;
479}
480
Prabir Pradhand65552b2021-10-07 11:23:50 -0700481bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
482 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
483 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
484 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
485}
486
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000487// Determines if the given window can be targeted as InputTarget::FLAG_FOREGROUND.
488// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
489// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
490// be sent to such a window, but it is not a foreground event and doesn't use
491// InputTarget::FLAG_FOREGROUND.
492bool canReceiveForegroundTouches(const WindowInfo& info) {
493 // A non-touchable window can still receive touch events (e.g. in the case of
494 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
495 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
496}
497
Antonio Kantek48710e42022-03-24 14:19:30 -0700498bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
499 if (windowHandle == nullptr) {
500 return false;
501 }
502 const WindowInfo* windowInfo = windowHandle->getInfo();
503 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
504 return true;
505 }
506 return false;
507}
508
Prabir Pradhan5735a322022-04-11 17:23:34 +0000509// Checks targeted injection using the window's owner's uid.
510// Returns an empty string if an entry can be sent to the given window, or an error message if the
511// entry is a targeted injection whose uid target doesn't match the window owner.
512std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
513 const EventEntry& entry) {
514 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
515 // The event was not injected, or the injected event does not target a window.
516 return {};
517 }
518 const int32_t uid = *entry.injectionState->targetUid;
519 if (window == nullptr) {
520 return StringPrintf("No valid window target for injection into uid %d.", uid);
521 }
522 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
523 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
524 "owned by uid %d.",
525 uid, window->getName().c_str(), window->getInfo()->ownerUid);
526 }
527 return {};
528}
529
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -0700530Point resolveTouchedPosition(const MotionEntry& entry) {
531 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
532 // Always dispatch mouse events to cursor position.
533 if (isFromMouse) {
534 return Point(static_cast<int32_t>(entry.xCursorPosition),
535 static_cast<int32_t>(entry.yCursorPosition));
536 }
537
538 const int32_t pointerIndex = getMotionEventActionPointerIndex(entry.action);
539 return Point(static_cast<int32_t>(
540 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X)),
541 static_cast<int32_t>(
542 entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y)));
543}
544
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -0700545std::optional<nsecs_t> getDownTime(const EventEntry& eventEntry) {
546 if (eventEntry.type == EventEntry::Type::KEY) {
547 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
548 return keyEntry.downTime;
549 } else if (eventEntry.type == EventEntry::Type::MOTION) {
550 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
551 return motionEntry.downTime;
552 }
553 return std::nullopt;
554}
555
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000556} // namespace
557
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558// --- InputDispatcher ---
559
Garfield Tan00f511d2019-06-12 16:55:40 -0700560InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800561 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
562
563InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
564 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700565 : mPolicy(policy),
566 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700567 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800568 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700569 mAppSwitchSawKeyDown(false),
Colin Cross5b799302022-10-18 21:52:41 -0700570 mAppSwitchDueTime(LLONG_MAX),
Garfield Tan00f511d2019-06-12 16:55:40 -0700571 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800572 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700573 mDispatchEnabled(false),
574 mDispatchFrozen(false),
575 mInputFilterEnabled(false),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100576 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000577 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800578 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800579 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000580 mLatencyAggregator(),
Antonio Kantek15beb512022-06-13 22:35:41 +0000581 mLatencyTracker(&mLatencyAggregator) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700582 mLooper = sp<Looper>::make(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800583 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700585 mWindowInfoListener = sp<DispatcherWindowListener>::make(*this);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700586#if defined(__ANDROID__)
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700587 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
Siarhei Vishniakou31977182022-09-30 08:51:23 -0700588#endif
Yi Kong9b14ac62018-07-17 13:48:38 -0700589 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800590 policy->getDispatcherConfiguration(&mConfig);
591}
592
593InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000594 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800595
Prabir Pradhancef936d2021-07-21 16:17:52 +0000596 resetKeyRepeatLocked();
597 releasePendingEventLocked();
598 drainInboundQueueLocked();
599 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800600
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000601 while (!mConnectionsByToken.empty()) {
602 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000603 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
604 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800605 }
606}
607
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700608status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700609 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700610 return ALREADY_EXISTS;
611 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700612 mThread = std::make_unique<InputThread>(
613 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
614 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700615}
616
617status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700618 if (mThread && mThread->isCallingThread()) {
619 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700620 return INVALID_OPERATION;
621 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700622 mThread.reset();
623 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700624}
625
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626void InputDispatcher::dispatchOnce() {
Colin Cross5b799302022-10-18 21:52:41 -0700627 nsecs_t nextWakeupTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800628 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800629 std::scoped_lock _l(mLock);
630 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631
632 // Run a dispatch loop if there are no pending commands.
633 // The dispatch loop might enqueue commands to run afterwards.
634 if (!haveCommandsLocked()) {
635 dispatchOnceInnerLocked(&nextWakeupTime);
636 }
637
638 // Run all pending commands if there are any.
639 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000640 if (runCommandsLockedInterruptable()) {
Colin Cross5b799302022-10-18 21:52:41 -0700641 nextWakeupTime = LLONG_MIN;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800643
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700644 // If we are still waiting for ack on some events,
645 // we might have to wake up earlier to check if an app is anr'ing.
646 const nsecs_t nextAnrCheck = processAnrsLocked();
647 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
648
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800649 // We are about to enter an infinitely long sleep, because we have no commands or
650 // pending or queued events
Colin Cross5b799302022-10-18 21:52:41 -0700651 if (nextWakeupTime == LLONG_MAX) {
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800652 mDispatcherEnteredIdle.notify_all();
653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 } // release lock
655
656 // Wait for callback or timeout or wake. (make sure we round up, not down)
657 nsecs_t currentTime = now();
658 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
659 mLooper->pollOnce(timeoutMillis);
660}
661
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700662/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500663 * Raise ANR if there is no focused window.
664 * Before the ANR is raised, do a final state check:
665 * 1. The currently focused application must be the same one we are waiting for.
666 * 2. Ensure we still don't have a focused window.
667 */
668void InputDispatcher::processNoFocusedWindowAnrLocked() {
669 // Check if the application that we are waiting for is still focused.
670 std::shared_ptr<InputApplicationHandle> focusedApplication =
671 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
672 if (focusedApplication == nullptr ||
673 focusedApplication->getApplicationToken() !=
674 mAwaitedFocusedApplication->getApplicationToken()) {
675 // Unexpected because we should have reset the ANR timer when focused application changed
676 ALOGE("Waited for a focused window, but focused application has already changed to %s",
677 focusedApplication->getName().c_str());
678 return; // The focused application has changed.
679 }
680
chaviw98318de2021-05-19 16:45:23 -0500681 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500682 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
683 if (focusedWindowHandle != nullptr) {
684 return; // We now have a focused window. No need for ANR.
685 }
686 onAnrLocked(mAwaitedFocusedApplication);
687}
688
689/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700690 * Check if any of the connections' wait queues have events that are too old.
691 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
692 * Return the time at which we should wake up next.
693 */
694nsecs_t InputDispatcher::processAnrsLocked() {
695 const nsecs_t currentTime = now();
Colin Cross5b799302022-10-18 21:52:41 -0700696 nsecs_t nextAnrCheck = LLONG_MAX;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700697 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
698 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
699 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500700 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700701 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500702 mNoFocusedWindowTimeoutTime = std::nullopt;
Colin Cross5b799302022-10-18 21:52:41 -0700703 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700704 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500705 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700706 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
707 }
708 }
709
710 // Check if any connection ANRs are due
711 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
712 if (currentTime < nextAnrCheck) { // most likely scenario
713 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
714 }
715
716 // If we reached here, we have an unresponsive connection.
717 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
718 if (connection == nullptr) {
719 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
720 return nextAnrCheck;
721 }
722 connection->responsive = false;
723 // Stop waking up for this unresponsive connection
724 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000725 onAnrLocked(connection);
Colin Cross5b799302022-10-18 21:52:41 -0700726 return LLONG_MIN;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700727}
728
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800729std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
730 const sp<Connection>& connection) {
731 if (connection->monitor) {
732 return mMonitorDispatchingTimeout;
733 }
734 const sp<WindowInfoHandle> window =
735 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700736 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500737 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700738 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500739 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700740}
741
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
743 nsecs_t currentTime = now();
744
Jeff Browndc5992e2014-04-11 01:27:26 -0700745 // Reset the key repeat timer whenever normal dispatch is suspended while the
746 // device is in a non-interactive state. This is to ensure that we abort a key
747 // repeat if the device is just coming out of sleep.
748 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749 resetKeyRepeatLocked();
750 }
751
752 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
753 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100754 if (DEBUG_FOCUS) {
755 ALOGD("Dispatch frozen. Waiting some more.");
756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757 return;
758 }
759
760 // Optimize latency of app switches.
761 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
762 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
763 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
764 if (mAppSwitchDueTime < *nextWakeupTime) {
765 *nextWakeupTime = mAppSwitchDueTime;
766 }
767
768 // Ready to start a new event.
769 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700770 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700771 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772 if (isAppSwitchDue) {
773 // The inbound queue is empty so the app switch key we were waiting
774 // for will never arrive. Stop waiting for it.
775 resetPendingAppSwitchLocked(false);
776 isAppSwitchDue = false;
777 }
778
779 // Synthesize a key repeat if appropriate.
780 if (mKeyRepeatState.lastKeyEntry) {
781 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
782 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
783 } else {
784 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
785 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
786 }
787 }
788 }
789
790 // Nothing to do if there is no pending event.
791 if (!mPendingEvent) {
792 return;
793 }
794 } else {
795 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700796 mPendingEvent = mInboundQueue.front();
797 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 traceInboundQueueLengthLocked();
799 }
800
801 // Poke user activity for this event.
802 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700803 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 }
806
807 // Now we have an event to dispatch.
808 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700809 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700811 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700813 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700815 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800816 }
817
818 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700819 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820 }
821
822 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700823 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700824 const ConfigurationChangedEntry& typedEntry =
825 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700826 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700827 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700828 break;
829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700831 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700832 const DeviceResetEntry& typedEntry =
833 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700834 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700835 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700836 break;
837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100839 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700840 std::shared_ptr<FocusEntry> typedEntry =
841 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100842 dispatchFocusLocked(currentTime, typedEntry);
843 done = true;
844 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
845 break;
846 }
847
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700848 case EventEntry::Type::TOUCH_MODE_CHANGED: {
849 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
850 dispatchTouchModeChangeLocked(currentTime, typedEntry);
851 done = true;
852 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
853 break;
854 }
855
Prabir Pradhan99987712020-11-10 18:43:05 -0800856 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
857 const auto typedEntry =
858 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
859 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
860 done = true;
861 break;
862 }
863
arthurhungb89ccb02020-12-30 16:19:01 +0800864 case EventEntry::Type::DRAG: {
865 std::shared_ptr<DragEntry> typedEntry =
866 std::static_pointer_cast<DragEntry>(mPendingEvent);
867 dispatchDragLocked(currentTime, typedEntry);
868 done = true;
869 break;
870 }
871
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700872 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700873 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700874 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700875 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700876 resetPendingAppSwitchLocked(true);
877 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700878 } else if (dropReason == DropReason::NOT_DROPPED) {
879 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700880 }
881 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700882 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700884 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700885 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
886 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700887 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700888 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700889 break;
890 }
891
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700892 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700893 std::shared_ptr<MotionEntry> motionEntry =
894 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700895 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
896 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700898 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700899 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700900 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700901 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
902 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700903 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700904 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700905 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906 }
Chris Yef59a2f42020-10-16 12:55:26 -0700907
908 case EventEntry::Type::SENSOR: {
909 std::shared_ptr<SensorEntry> sensorEntry =
910 std::static_pointer_cast<SensorEntry>(mPendingEvent);
911 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
912 dropReason = DropReason::APP_SWITCH;
913 }
914 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
915 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
916 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
917 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
918 dropReason = DropReason::STALE;
919 }
920 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
921 done = true;
922 break;
923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 }
925
926 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700927 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700928 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 }
Michael Wright3a981722015-06-10 15:26:13 +0100930 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931
932 releasePendingEventLocked();
Colin Cross5b799302022-10-18 21:52:41 -0700933 *nextWakeupTime = LLONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934 }
935}
936
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800937bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
938 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
939}
940
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700941/**
942 * Return true if the events preceding this incoming motion event should be dropped
943 * Return false otherwise (the default behaviour)
944 */
945bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700947 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700948
949 // Optimize case where the current application is unresponsive and the user
950 // decides to touch a window in a different application.
951 // If the application takes too long to catch up then we drop all events preceding
952 // the touch into the other window.
953 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700954 const int32_t displayId = motionEntry.displayId;
955 const auto [x, y] = resolveTouchedPosition(motionEntry);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700956 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
Siarhei Vishniakou9306c382022-09-30 15:30:31 -0700957
chaviw98318de2021-05-19 16:45:23 -0500958 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700959 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700960 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700961 touchedWindowHandle->getApplicationToken() !=
962 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700963 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700964 ALOGI("Pruning input queue because user touched a different application while waiting "
965 "for %s",
966 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700967 return true;
968 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700969
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800970 // Alternatively, maybe there's a spy window that could handle this event.
971 const std::vector<sp<WindowInfoHandle>> touchedSpies =
972 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
973 for (const auto& windowHandle : touchedSpies) {
974 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000975 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800976 // This spy window could take more input. Drop all events preceding this
977 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700978 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800979 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700980 mAwaitedFocusedApplication->getName().c_str());
981 return true;
982 }
983 }
984 }
985
986 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
987 // yet been processed by some connections, the dispatcher will wait for these motion
988 // events to be processed before dispatching the key event. This is because these motion events
989 // may cause a new window to be launched, which the user might expect to receive focus.
990 // To prevent waiting forever for such events, just send the key to the currently focused window
991 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
992 ALOGD("Received a new pointer down event, stop waiting for events to process and "
993 "just send the pending key event to the focused window.");
994 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700995 }
996 return false;
997}
998
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700999bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001000 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001001 mInboundQueue.push_back(std::move(newEntry));
1002 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 traceInboundQueueLengthLocked();
1004
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001005 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001006 case EventEntry::Type::KEY: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001007 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1008 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001009 // Optimize app switch latency.
1010 // If the application takes too long to catch up then we drop all events preceding
1011 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001012 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001013 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001014 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001015 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001016 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001017 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001018 if (DEBUG_APP_SWITCH) {
1019 ALOGD("App switch is pending!");
1020 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001021 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001022 mAppSwitchSawKeyDown = false;
1023 needWake = true;
1024 }
1025 }
1026 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001027
1028 // If a new up event comes in, and the pending event with same key code has been asked
1029 // to try again later because of the policy. We have to reset the intercept key wake up
1030 // time for it may have been handled in the policy and could be dropped.
1031 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1032 mPendingEvent->type == EventEntry::Type::KEY) {
1033 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1034 if (pendingKey.keyCode == keyEntry.keyCode &&
1035 pendingKey.interceptKeyResult ==
1036 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1037 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1038 pendingKey.interceptKeyWakeupTime = 0;
1039 needWake = true;
1040 }
1041 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001042 break;
1043 }
1044
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001045 case EventEntry::Type::MOTION: {
Prabir Pradhan5735a322022-04-11 17:23:34 +00001046 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1047 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001048 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1049 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001050 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001052 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001054 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001055 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1056 break;
1057 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001058 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001059 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001060 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001061 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001062 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1063 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001064 // nothing to do
1065 break;
1066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
1068
1069 return needWake;
1070}
1071
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001072void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001073 // Do not store sensor event in recent queue to avoid flooding the queue.
1074 if (entry->type != EventEntry::Type::SENSOR) {
1075 mRecentQueue.push_back(entry);
1076 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001077 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001078 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 }
1080}
1081
chaviw98318de2021-05-19 16:45:23 -05001082sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
1083 int32_t y, TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001084 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001085 bool addOutsideTargets,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07001086 bool ignoreDragWindow) const {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001087 if (addOutsideTargets && touchState == nullptr) {
1088 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001091 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001092 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001093 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001094 continue;
1095 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001097 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhand65552b2021-10-07 11:23:50 -07001098 if (!info.isSpy() && windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001099 return windowHandle;
1100 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001101
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001102 if (addOutsideTargets &&
1103 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001104 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1105 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 }
1107 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001108 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109}
1110
Prabir Pradhand65552b2021-10-07 11:23:50 -07001111std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
1112 int32_t displayId, int32_t x, int32_t y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001113 // Traverse windows from front to back and gather the touched spy windows.
1114 std::vector<sp<WindowInfoHandle>> spyWindows;
1115 const auto& windowHandles = getWindowHandlesLocked(displayId);
1116 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1117 const WindowInfo& info = *windowHandle->getInfo();
1118
Prabir Pradhand65552b2021-10-07 11:23:50 -07001119 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus)) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001120 continue;
1121 }
1122 if (!info.isSpy()) {
1123 // The first touched non-spy window was found, so return the spy windows touched so far.
1124 return spyWindows;
1125 }
1126 spyWindows.push_back(windowHandle);
1127 }
1128 return spyWindows;
1129}
1130
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001131void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 const char* reason;
1133 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001134 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001135 if (DEBUG_INBOUND_EVENT_DETAILS) {
1136 ALOGD("Dropped event because policy consumed it.");
1137 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001138 reason = "inbound event was dropped because the policy consumed it";
1139 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001140 case DropReason::DISABLED:
1141 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001142 ALOGI("Dropped event because input dispatch is disabled.");
1143 }
1144 reason = "inbound event was dropped because input dispatch is disabled";
1145 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001146 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001147 ALOGI("Dropped event because of pending overdue app switch.");
1148 reason = "inbound event was dropped because of pending overdue app switch";
1149 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001150 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001151 ALOGI("Dropped event because the current application is not responding and the user "
1152 "has started interacting with a different application.");
1153 reason = "inbound event was dropped because the current application is not responding "
1154 "and the user has started interacting with a different application";
1155 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001156 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001157 ALOGI("Dropped event because it is stale.");
1158 reason = "inbound event was dropped because it is stale";
1159 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001160 case DropReason::NO_POINTER_CAPTURE:
1161 ALOGI("Dropped event because there is no window with Pointer Capture.");
1162 reason = "inbound event was dropped because there is no window with Pointer Capture";
1163 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001164 case DropReason::NOT_DROPPED: {
1165 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001166 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001167 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 }
1169
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001170 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001171 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1173 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001174 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001176 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001177 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1178 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001179 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1180 synthesizeCancelationEventsForAllConnectionsLocked(options);
1181 } else {
1182 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1183 synthesizeCancelationEventsForAllConnectionsLocked(options);
1184 }
1185 break;
1186 }
Chris Yef59a2f42020-10-16 12:55:26 -07001187 case EventEntry::Type::SENSOR: {
1188 break;
1189 }
arthurhungb89ccb02020-12-30 16:19:01 +08001190 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1191 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001192 break;
1193 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001194 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001195 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001196 case EventEntry::Type::CONFIGURATION_CHANGED:
1197 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001198 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001199 break;
1200 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 }
1202}
1203
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001204static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001205 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1206 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207}
1208
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001209bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1210 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1211 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1212 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213}
1214
1215bool InputDispatcher::isAppSwitchPendingLocked() {
Colin Cross5b799302022-10-18 21:52:41 -07001216 return mAppSwitchDueTime != LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217}
1218
1219void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
Colin Cross5b799302022-10-18 21:52:41 -07001220 mAppSwitchDueTime = LLONG_MAX;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001222 if (DEBUG_APP_SWITCH) {
1223 if (handled) {
1224 ALOGD("App switch has arrived.");
1225 } else {
1226 ALOGD("App switch was abandoned.");
1227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229}
1230
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001232 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233}
1234
Prabir Pradhancef936d2021-07-21 16:17:52 +00001235bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001236 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 return false;
1238 }
1239
1240 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001241 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001242 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001243 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1244 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001245 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 return true;
1247}
1248
Prabir Pradhancef936d2021-07-21 16:17:52 +00001249void InputDispatcher::postCommandLocked(Command&& command) {
1250 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251}
1252
1253void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001254 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001255 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001256 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 releaseInboundEventLocked(entry);
1258 }
1259 traceInboundQueueLengthLocked();
1260}
1261
1262void InputDispatcher::releasePendingEventLocked() {
1263 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001265 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 }
1267}
1268
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001269void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001271 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001272 if (DEBUG_DISPATCH_CYCLE) {
1273 ALOGD("Injected inbound event was dropped.");
1274 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001275 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 }
1277 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001278 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 }
1280 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281}
1282
1283void InputDispatcher::resetKeyRepeatLocked() {
1284 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001285 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001286 }
1287}
1288
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001289std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1290 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291
Michael Wright2e732952014-09-24 13:26:59 -07001292 uint32_t policyFlags = entry->policyFlags &
1293 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001295 std::shared_ptr<KeyEntry> newEntry =
1296 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1297 entry->source, entry->displayId, policyFlags, entry->action,
1298 entry->flags, entry->keyCode, entry->scanCode,
1299 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001301 newEntry->syntheticRepeat = true;
1302 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001304 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001305}
1306
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001307bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001308 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001309 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1310 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312
1313 // Reset key repeating in case a keyboard device was added or removed or something.
1314 resetKeyRepeatLocked();
1315
1316 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001317 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1318 scoped_unlock unlock(mLock);
1319 mPolicy->notifyConfigurationChanged(eventTime);
1320 };
1321 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 return true;
1323}
1324
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001325bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1326 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001327 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1328 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1329 entry.deviceId);
1330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001331
liushenxiang42232912021-05-21 20:24:09 +08001332 // Reset key repeating in case a keyboard device was disabled or enabled.
1333 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1334 resetKeyRepeatLocked();
1335 }
1336
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001337 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001338 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 synthesizeCancelationEventsForAllConnectionsLocked(options);
1340 return true;
1341}
1342
Vishnu Nairad321cd2020-08-20 16:40:21 -07001343void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001344 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001345 if (mPendingEvent != nullptr) {
1346 // Move the pending event to the front of the queue. This will give the chance
1347 // for the pending event to get dispatched to the newly focused window
1348 mInboundQueue.push_front(mPendingEvent);
1349 mPendingEvent = nullptr;
1350 }
1351
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001352 std::unique_ptr<FocusEntry> focusEntry =
1353 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1354 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001355
1356 // This event should go to the front of the queue, but behind all other focus events
1357 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001358 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001359 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001360 [](const std::shared_ptr<EventEntry>& event) {
1361 return event->type == EventEntry::Type::FOCUS;
1362 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001363
1364 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001365 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001366}
1367
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001368void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001369 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001370 if (channel == nullptr) {
1371 return; // Window has gone away
1372 }
1373 InputTarget target;
1374 target.inputChannel = channel;
1375 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1376 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001377 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1378 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001379 std::string reason = std::string("reason=").append(entry->reason);
1380 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001381 dispatchEventLocked(currentTime, entry, {target});
1382}
1383
Prabir Pradhan99987712020-11-10 18:43:05 -08001384void InputDispatcher::dispatchPointerCaptureChangedLocked(
1385 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1386 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001387 dropReason = DropReason::NOT_DROPPED;
1388
Prabir Pradhan99987712020-11-10 18:43:05 -08001389 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001390 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001391
1392 if (entry->pointerCaptureRequest.enable) {
1393 // Enable Pointer Capture.
1394 if (haveWindowWithPointerCapture &&
1395 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001396 // This can happen if pointer capture is disabled and re-enabled before we notify the
1397 // app of the state change, so there is no need to notify the app.
1398 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1399 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001400 }
1401 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001402 // This can happen if a window requests capture and immediately releases capture.
1403 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001404 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001405 return;
1406 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001407 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1408 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1409 return;
1410 }
1411
Vishnu Nairc519ff72021-01-21 08:23:08 -08001412 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001413 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1414 mWindowTokenWithPointerCapture = token;
1415 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001416 // Disable Pointer Capture.
1417 // We do not check if the sequence number matches for requests to disable Pointer Capture
1418 // for two reasons:
1419 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1420 // to disable capture with the same sequence number: one generated by
1421 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1422 // Capture being disabled in InputReader.
1423 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1424 // actual Pointer Capture state that affects events being generated by input devices is
1425 // in InputReader.
1426 if (!haveWindowWithPointerCapture) {
1427 // Pointer capture was already forcefully disabled because of focus change.
1428 dropReason = DropReason::NOT_DROPPED;
1429 return;
1430 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001431 token = mWindowTokenWithPointerCapture;
1432 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001433 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001434 setPointerCaptureLocked(false);
1435 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001436 }
1437
1438 auto channel = getInputChannelLocked(token);
1439 if (channel == nullptr) {
1440 // Window has gone away, clean up Pointer Capture state.
1441 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001442 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001443 setPointerCaptureLocked(false);
1444 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001445 return;
1446 }
1447 InputTarget target;
1448 target.inputChannel = channel;
1449 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1450 entry->dispatchInProgress = true;
1451 dispatchEventLocked(currentTime, entry, {target});
1452
1453 dropReason = DropReason::NOT_DROPPED;
1454}
1455
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001456void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1457 const std::shared_ptr<TouchModeEntry>& entry) {
1458 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Antonio Kantek15beb512022-06-13 22:35:41 +00001459 getWindowHandlesLocked(entry->displayId);
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001460 if (windowHandles.empty()) {
1461 return;
1462 }
1463 const std::vector<InputTarget> inputTargets =
1464 getInputTargetsFromWindowHandlesLocked(windowHandles);
1465 if (inputTargets.empty()) {
1466 return;
1467 }
1468 entry->dispatchInProgress = true;
1469 dispatchEventLocked(currentTime, entry, inputTargets);
1470}
1471
1472std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1473 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1474 std::vector<InputTarget> inputTargets;
1475 for (const sp<WindowInfoHandle>& handle : windowHandles) {
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001476 const sp<IBinder>& token = handle->getToken();
1477 if (token == nullptr) {
1478 continue;
1479 }
1480 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1481 if (channel == nullptr) {
1482 continue; // Window has gone away
1483 }
1484 InputTarget target;
1485 target.inputChannel = channel;
1486 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1487 inputTargets.push_back(target);
1488 }
1489 return inputTargets;
1490}
1491
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001492bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001493 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001495 if (!entry->dispatchInProgress) {
1496 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1497 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1498 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1499 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001500 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 // We have seen two identical key downs in a row which indicates that the device
1502 // driver is automatically generating key repeats itself. We take note of the
1503 // repeat here, but we disable our own next key repeat timer since it is clear that
1504 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001505 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1506 // Make sure we don't get key down from a different device. If a different
1507 // device Id has same key pressed down, the new device Id will replace the
1508 // current one to hold the key repeat with repeat count reset.
1509 // In the future when got a KEY_UP on the device id, drop it and do not
1510 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1512 resetKeyRepeatLocked();
Colin Cross5b799302022-10-18 21:52:41 -07001513 mKeyRepeatState.nextRepeatTime = LLONG_MAX; // don't generate repeats ourselves
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 } else {
1515 // Not a repeat. Save key down state in case we do see a repeat later.
1516 resetKeyRepeatLocked();
1517 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1518 }
1519 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001520 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1521 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001522 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001523 if (DEBUG_INBOUND_EVENT_DETAILS) {
1524 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1525 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001526 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 resetKeyRepeatLocked();
1528 }
1529
1530 if (entry->repeatCount == 1) {
1531 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1532 } else {
1533 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1534 }
1535
1536 entry->dispatchInProgress = true;
1537
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001538 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 }
1540
1541 // Handle case where the policy asked us to try again later last time.
1542 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1543 if (currentTime < entry->interceptKeyWakeupTime) {
1544 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1545 *nextWakeupTime = entry->interceptKeyWakeupTime;
1546 }
1547 return false; // wait until next wakeup
1548 }
1549 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1550 entry->interceptKeyWakeupTime = 0;
1551 }
1552
1553 // Give the policy a chance to intercept the key.
1554 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1555 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001556 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001557 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001558
1559 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1560 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1561 };
1562 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 return false; // wait for the command to run
1564 } else {
1565 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1566 }
1567 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001568 if (*dropReason == DropReason::NOT_DROPPED) {
1569 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 }
1571 }
1572
1573 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001574 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001575 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001576 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1577 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001578 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 return true;
1580 }
1581
1582 // Identify targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001583 InputEventInjectionResult injectionResult;
1584 sp<WindowInfoHandle> focusedWindow =
1585 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime,
1586 /*byref*/ injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001587 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 return false;
1589 }
1590
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001591 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001592 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 return true;
1594 }
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001595 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1596
1597 std::vector<InputTarget> inputTargets;
1598 addWindowTargetLocked(focusedWindow,
1599 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1600 BitSet32(0), getDownTime(*entry), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001602 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001603 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604
1605 // Dispatch the key.
1606 dispatchEventLocked(currentTime, entry, inputTargets);
1607 return true;
1608}
1609
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001610void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001611 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1612 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1613 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1614 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1615 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1616 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1617 entry.metaState, entry.repeatCount, entry.downTime);
1618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619}
1620
Prabir Pradhancef936d2021-07-21 16:17:52 +00001621void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1622 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001623 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001624 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1625 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1626 "source=0x%x, sensorType=%s",
1627 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001628 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001629 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001630 auto command = [this, entry]() REQUIRES(mLock) {
1631 scoped_unlock unlock(mLock);
1632
1633 if (entry->accuracyChanged) {
1634 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1635 }
1636 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1637 entry->hwTimestamp, entry->values);
1638 };
1639 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001640}
1641
1642bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001643 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1644 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001645 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001646 }
Chris Yef59a2f42020-10-16 12:55:26 -07001647 { // acquire lock
1648 std::scoped_lock _l(mLock);
1649
1650 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1651 std::shared_ptr<EventEntry> entry = *it;
1652 if (entry->type == EventEntry::Type::SENSOR) {
1653 it = mInboundQueue.erase(it);
1654 releaseInboundEventLocked(entry);
1655 }
1656 }
1657 }
1658 return true;
1659}
1660
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001661bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001662 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001663 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001665 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 entry->dispatchInProgress = true;
1667
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001668 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 }
1670
1671 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001672 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001673 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001674 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1675 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 return true;
1677 }
1678
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001679 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680
1681 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001682 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683
1684 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001685 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 if (isPointerEvent) {
1687 // Pointer event. (eg. touchscreen)
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00001688
1689 if (mDragState &&
1690 (entry->action & AMOTION_EVENT_ACTION_MASK) == AMOTION_EVENT_ACTION_POINTER_DOWN) {
1691 // If drag and drop ongoing and pointer down occur: pilfer drag window pointers
1692 pilferPointersLocked(mDragState->dragWindow->getToken());
1693 }
1694
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001695 std::vector<TouchedWindow> touchedWindows =
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07001696 findTouchedWindowTargetsLocked(currentTime, *entry, &conflictingPointerActions,
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001697 /*byref*/ injectionResult);
1698 for (const TouchedWindow& touchedWindow : touchedWindows) {
1699 LOG_ALWAYS_FATAL_IF(injectionResult != InputEventInjectionResult::SUCCEEDED,
1700 "Shouldn't be adding window if the injection didn't succeed.");
1701 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1702 touchedWindow.pointerIds, touchedWindow.firstDownTimeInTarget,
1703 inputTargets);
1704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705 } else {
1706 // Non touch event. (eg. trackball)
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001707 sp<WindowInfoHandle> focusedWindow =
1708 findFocusedWindowTargetLocked(currentTime, *entry, nextWakeupTime, injectionResult);
1709 if (injectionResult == InputEventInjectionResult::SUCCEEDED) {
1710 LOG_ALWAYS_FATAL_IF(focusedWindow == nullptr);
1711 addWindowTargetLocked(focusedWindow,
1712 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1713 BitSet32(0), getDownTime(*entry), inputTargets);
1714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001716 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 return false;
1718 }
1719
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001720 setInjectionResult(*entry, injectionResult);
Prabir Pradhan5735a322022-04-11 17:23:34 +00001721 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001722 return true;
1723 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001724 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001725 CancelationOptions::Mode mode(isPointerEvent
1726 ? CancelationOptions::CANCEL_POINTER_EVENTS
1727 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1728 CancelationOptions options(mode, "input event injection failed");
1729 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 return true;
1731 }
1732
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001733 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001734 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735
1736 // Dispatch the motion.
1737 if (conflictingPointerActions) {
1738 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001739 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 synthesizeCancelationEventsForAllConnectionsLocked(options);
1741 }
1742 dispatchEventLocked(currentTime, entry, inputTargets);
1743 return true;
1744}
1745
chaviw98318de2021-05-19 16:45:23 -05001746void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001747 bool isExiting, const int32_t rawX,
1748 const int32_t rawY) {
1749 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001750 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001751 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1752 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001753
1754 enqueueInboundEventLocked(std::move(dragEntry));
1755}
1756
1757void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1758 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1759 if (channel == nullptr) {
1760 return; // Window has gone away
1761 }
1762 InputTarget target;
1763 target.inputChannel = channel;
1764 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1765 entry->dispatchInProgress = true;
1766 dispatchEventLocked(currentTime, entry, {target});
1767}
1768
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001769void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001770 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1771 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1772 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001773 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001774 "metaState=0x%x, buttonState=0x%x,"
1775 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1776 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001777 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1778 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1779 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001781 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1782 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1783 "x=%f, y=%f, pressure=%f, size=%f, "
1784 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1785 "orientation=%f",
1786 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1787 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1788 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1789 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1790 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1791 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1792 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1793 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1794 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1795 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1796 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798}
1799
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001800void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1801 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001802 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001803 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001804 if (DEBUG_DISPATCH_CYCLE) {
1805 ALOGD("dispatchEventToCurrentInputTargets");
1806 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001808 updateInteractionTokensLocked(*eventEntry, inputTargets);
1809
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1811
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001812 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001814 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001815 sp<Connection> connection =
1816 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001817 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001818 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001820 if (DEBUG_FOCUS) {
1821 ALOGD("Dropping event delivery to target with channel '%s' because it "
1822 "is no longer registered with the input dispatcher.",
1823 inputTarget.inputChannel->getName().c_str());
1824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 }
1826 }
1827}
1828
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001829void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1830 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1831 // If the policy decides to close the app, we will get a channel removal event via
1832 // unregisterInputChannel, and will clean up the connection that way. We are already not
1833 // sending new pointers to the connection when it blocked, but focused events will continue to
1834 // pile up.
1835 ALOGW("Canceling events for %s because it is unresponsive",
1836 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001837 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001838 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1839 "application not responding");
1840 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 }
1842}
1843
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001844void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001845 if (DEBUG_FOCUS) {
1846 ALOGD("Resetting ANR timeouts.");
1847 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848
1849 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001850 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001851 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852}
1853
Tiger Huang721e26f2018-07-24 22:26:19 +08001854/**
1855 * Get the display id that the given event should go to. If this event specifies a valid display id,
1856 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1857 * Focused display is the display that the user most recently interacted with.
1858 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001859int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001860 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001861 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001862 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001863 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1864 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001865 break;
1866 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001867 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001868 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1869 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001870 break;
1871 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001872 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001873 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001874 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001875 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001876 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001877 case EventEntry::Type::SENSOR:
1878 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001879 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001880 return ADISPLAY_ID_NONE;
1881 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001882 }
1883 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1884}
1885
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001886bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1887 const char* focusedWindowName) {
1888 if (mAnrTracker.empty()) {
1889 // already processed all events that we waited for
1890 mKeyIsWaitingForEventsTimeout = std::nullopt;
1891 return false;
1892 }
1893
1894 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1895 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001896 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001897 mKeyIsWaitingForEventsTimeout = currentTime +
1898 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1899 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001900 return true;
1901 }
1902
1903 // We still have pending events, and already started the timer
1904 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1905 return true; // Still waiting
1906 }
1907
1908 // Waited too long, and some connection still hasn't processed all motions
1909 // Just send the key to the focused window
1910 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1911 focusedWindowName);
1912 mKeyIsWaitingForEventsTimeout = std::nullopt;
1913 return false;
1914}
1915
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001916sp<WindowInfoHandle> InputDispatcher::findFocusedWindowTargetLocked(
1917 nsecs_t currentTime, const EventEntry& entry, nsecs_t* nextWakeupTime,
1918 InputEventInjectionResult& outInjectionResult) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001919 std::string reason;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001920 outInjectionResult = InputEventInjectionResult::FAILED; // Default result
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921
Tiger Huang721e26f2018-07-24 22:26:19 +08001922 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001923 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001924 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001925 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1926
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 // If there is no currently focused window and no focused application
1928 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001929 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1930 ALOGI("Dropping %s event because there is no focused window or focused application in "
1931 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001932 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001933 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934 }
1935
Vishnu Nair062a8672021-09-03 16:07:44 -07001936 // Drop key events if requested by input feature
1937 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001938 return nullptr;
Vishnu Nair062a8672021-09-03 16:07:44 -07001939 }
1940
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001941 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1942 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1943 // start interacting with another application via touch (app switch). This code can be removed
1944 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1945 // an app is expected to have a focused window.
1946 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1947 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1948 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001949 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1950 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1951 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001952 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001953 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001954 ALOGW("Waiting because no window has focus but %s may eventually add a "
1955 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001956 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001957 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001958 outInjectionResult = InputEventInjectionResult::PENDING;
1959 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001960 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1961 // Already raised ANR. Drop the event
1962 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001963 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001964 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001965 } else {
1966 // Still waiting for the focused window
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001967 outInjectionResult = InputEventInjectionResult::PENDING;
1968 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001969 }
1970 }
1971
1972 // we have a valid, non-null focused window
1973 resetNoFocusedWindowTimeoutLocked();
1974
Prabir Pradhan5735a322022-04-11 17:23:34 +00001975 // Verify targeted injection.
1976 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1977 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001978 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
1979 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980 }
1981
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001982 if (focusedWindowHandle->getInfo()->inputConfig.test(
1983 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001984 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07001985 outInjectionResult = InputEventInjectionResult::PENDING;
1986 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001987 }
1988
1989 // If the event is a key event, then we must wait for all previous events to
1990 // complete before delivering it because previous events may have the
1991 // side-effect of transferring focus to a different window and we want to
1992 // ensure that the following keys are sent to the new window.
1993 //
1994 // Suppose the user touches a button in a window then immediately presses "A".
1995 // If the button causes a pop-up window to appear then we want to ensure that
1996 // the "A" key is delivered to the new pop-up window. This is because users
1997 // often anticipate pending UI changes when typing on a keyboard.
1998 // To obtain this behavior, we must serialize key events with respect to all
1999 // prior input events.
2000 if (entry.type == EventEntry::Type::KEY) {
2001 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
2002 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002003 outInjectionResult = InputEventInjectionResult::PENDING;
2004 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 }
2007
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002008 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
2009 return focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010}
2011
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002012/**
2013 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
2014 * that are currently unresponsive.
2015 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002016std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
2017 const std::vector<Monitor>& monitors) const {
2018 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002019 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002020 [this](const Monitor& monitor) REQUIRES(mLock) {
2021 sp<Connection> connection =
2022 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002023 if (connection == nullptr) {
2024 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002025 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002026 return false;
2027 }
2028 if (!connection->responsive) {
2029 ALOGW("Unresponsive monitor %s will not get the new gesture",
2030 connection->inputChannel->getName().c_str());
2031 return false;
2032 }
2033 return true;
2034 });
2035 return responsiveMonitors;
2036}
2037
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002038/**
2039 * In general, touch should be always split between windows. Some exceptions:
2040 * 1. Don't split touch is if we have an active pointer down, and a new pointer is going down that's
2041 * from the same device, *and* the window that's receiving the current pointer does not support
2042 * split touch.
2043 * 2. Don't split mouse events
2044 */
2045bool InputDispatcher::shouldSplitTouch(const TouchState& touchState,
2046 const MotionEntry& entry) const {
2047 if (isFromSource(entry.source, AINPUT_SOURCE_MOUSE)) {
2048 // We should never split mouse events
2049 return false;
2050 }
2051 for (const TouchedWindow& touchedWindow : touchState.windows) {
2052 if (touchedWindow.windowHandle->getInfo()->isSpy()) {
2053 // Spy windows should not affect whether or not touch is split.
2054 continue;
2055 }
2056 if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
2057 continue;
2058 }
2059 // Eventually, touchedWindow will contain the deviceId of each pointer that's currently
2060 // being sent there. For now, use deviceId from touch state.
2061 if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
2062 return false;
2063 }
2064 }
2065 return true;
2066}
2067
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002068std::vector<TouchedWindow> InputDispatcher::findTouchedWindowTargetsLocked(
Siarhei Vishniakou4fe57392022-10-25 13:44:30 -07002069 nsecs_t currentTime, const MotionEntry& entry, bool* outConflictingPointerActions,
2070 InputEventInjectionResult& outInjectionResult) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002071 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002073 std::vector<TouchedWindow> touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 // For security reasons, we defer updating the touch state until we are sure that
2075 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002076 const int32_t displayId = entry.displayId;
2077 const int32_t action = entry.action;
2078 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079
2080 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002081 outInjectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002082 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2083 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002085 // Copy current touch state into tempTouchState.
2086 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2087 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002088 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002089 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002090 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2091 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002092 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002093 }
2094
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002095 bool isSplit = shouldSplitTouch(tempTouchState, entry);
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002096 const bool switchedDevice = (oldState != nullptr) &&
2097 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002098
2099 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2100 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2101 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2102 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2103 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002104 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 if (newGesture) {
2106 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002107 if (switchedDevice && tempTouchState.isDown() && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002108 ALOGI("Dropping event because a pointer for a different device is already down "
2109 "in display %" PRId32,
2110 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002111 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002112 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002113 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002115 tempTouchState.reset();
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002116 tempTouchState.deviceId = entry.deviceId;
2117 tempTouchState.source = entry.source;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002119 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002120 ALOGI("Dropping move event because a pointer for a different device is already active "
2121 "in display %" PRId32,
2122 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002123 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002124 outInjectionResult = InputEventInjectionResult::FAILED;
Siarhei Vishniakouf0ab2c82022-10-25 18:15:28 -07002125 return touchedWindows; // wrong device
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 }
2127
2128 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2129 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002130 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002131 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002132 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002133 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002134 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002135 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002136
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002138 if (newTouchedWindowHandle == nullptr) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002139 ALOGD("No new touched window at (%" PRId32 ", %" PRId32 ") in display %" PRId32, x, y,
2140 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002142 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002143 }
2144
Prabir Pradhan5735a322022-04-11 17:23:34 +00002145 // Verify targeted injection.
2146 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2147 ALOGW("Dropping injected touch event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002148 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002149 newTouchedWindowHandle = nullptr;
2150 goto Failed;
2151 }
2152
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002153 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002154 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002155 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2156 // New window supports splitting, but we should never split mouse events.
2157 isSplit = !isFromMouse;
2158 } else if (isSplit) {
2159 // New window does not support splitting but we have already split events.
2160 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002161 newTouchedWindowHandle = nullptr;
2162 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002163 } else {
2164 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002165 // be delivered to a new window which supports split touch. Pointers from a mouse device
2166 // should never be split.
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07002167 isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002168 }
2169
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002170 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002171 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002172 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2173 newHoverWindowHandle = nullptr;
2174 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002175 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002176 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002177 }
2178
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002179 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002180 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002181 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002182 // Process the foreground window first so that it is the first to receive the event.
2183 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002184 }
2185
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002186 if (newTouchedWindows.empty()) {
2187 ALOGI("Dropping event because there is no touchable window at (%d, %d) on display %d.",
2188 x, y, displayId);
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002189 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002190 goto Failed;
2191 }
2192
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002193 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07002194 if (!canWindowReceiveMotionLocked(windowHandle, entry)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002195 continue;
2196 }
2197
2198 // Set target flags.
2199 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2200
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002201 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2202 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002203 targetFlags |= InputTarget::FLAG_FOREGROUND;
2204 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002205
2206 if (isSplit) {
2207 targetFlags |= InputTarget::FLAG_SPLIT;
2208 }
2209 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2210 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2211 } else if (isWindowObscuredLocked(windowHandle)) {
2212 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2213 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002214
2215 // Update the temporary touch state.
2216 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002217 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002218
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002219 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
2220 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 }
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00002222
2223 // If any existing window is pilfering pointers from newly added window, remove it
2224 BitSet32 canceledPointers = BitSet32(0);
2225 for (const TouchedWindow& window : tempTouchState.windows) {
2226 if (window.isPilferingPointers) {
2227 canceledPointers |= window.pointerIds;
2228 }
2229 }
2230 tempTouchState.cancelPointersForNonPilferingWindows(canceledPointers);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 } else {
2232 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2233
2234 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002235 if (!tempTouchState.isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002236 ALOGD_IF(DEBUG_FOCUS,
2237 "Dropping event because the pointer is not down or we previously "
2238 "dropped the pointer down event in display %" PRId32 ": %s",
2239 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002240 outInjectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241 goto Failed;
2242 }
2243
arthurhung6d4bed92021-03-17 11:59:33 +08002244 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002245
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002247 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002248 tempTouchState.isSlippery()) {
Siarhei Vishniakou9306c382022-09-30 15:30:31 -07002249 const auto [x, y] = resolveTouchedPosition(entry);
Prabir Pradhand65552b2021-10-07 11:23:50 -07002250 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002251 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002252 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002253 newTouchedWindowHandle =
2254 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002255
Prabir Pradhan5735a322022-04-11 17:23:34 +00002256 // Verify targeted injection.
2257 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2258 ALOGW("Dropping injected event: %s", (*err).c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002259 outInjectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002260 newTouchedWindowHandle = nullptr;
2261 goto Failed;
2262 }
2263
Vishnu Nair062a8672021-09-03 16:07:44 -07002264 // Drop touch events if requested by input feature
2265 if (newTouchedWindowHandle != nullptr &&
2266 shouldDropInput(entry, newTouchedWindowHandle)) {
2267 newTouchedWindowHandle = nullptr;
2268 }
2269
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002270 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2271 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002272 if (DEBUG_FOCUS) {
2273 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2274 oldTouchedWindowHandle->getName().c_str(),
2275 newTouchedWindowHandle->getName().c_str(), displayId);
2276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002278 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2279 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2280 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281
2282 // Make a slippery entrance into the new window.
2283 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002284 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 }
2286
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002287 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2288 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2289 targetFlags |= InputTarget::FLAG_FOREGROUND;
2290 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 if (isSplit) {
2292 targetFlags |= InputTarget::FLAG_SPLIT;
2293 }
2294 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2295 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002296 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2297 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 }
2299
2300 BitSet32 pointerIds;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00002301 pointerIds.markBit(entry.pointerProperties[0].id);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002302 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
2303 entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 }
2305 }
2306 }
2307
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002308 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002310 // Let the previous window know that the hover sequence is over, unless we already did
2311 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002312 if (mLastHoverWindowHandle != nullptr &&
2313 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2314 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002315 if (DEBUG_HOVER) {
2316 ALOGD("Sending hover exit event to window %s.",
2317 mLastHoverWindowHandle->getName().c_str());
2318 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002319 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2320 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 }
2322
Garfield Tandf26e862020-07-01 20:18:19 -07002323 // Let the new window know that the hover sequence is starting, unless we already did it
2324 // when dispatching it as is to newTouchedWindowHandle.
2325 if (newHoverWindowHandle != nullptr &&
2326 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2327 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002328 if (DEBUG_HOVER) {
2329 ALOGD("Sending hover enter event to window %s.",
2330 newHoverWindowHandle->getName().c_str());
2331 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002332 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2333 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2334 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 }
2336 }
2337
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002338 // Ensure that we have at least one foreground window or at least one window that cannot be a
2339 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2340 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2341 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002342 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2343 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002344 return !canReceiveForegroundTouches(
2345 *touchedWindow.windowHandle->getInfo()) ||
2346 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002347 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002348 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2349 displayId, entry.getDescription().c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002350 outInjectionResult = InputEventInjectionResult::FAILED;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002351 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
2353
Prabir Pradhan5735a322022-04-11 17:23:34 +00002354 // Ensure that all touched windows are valid for injection.
2355 if (entry.injectionState != nullptr) {
2356 std::string errs;
2357 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2358 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2359 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2360 // dispatched to any uid, since the coords will be zeroed out later.
2361 continue;
2362 }
2363 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2364 if (err) errs += "\n - " + *err;
2365 }
2366 if (!errs.empty()) {
2367 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2368 "%d:%s",
2369 *entry.injectionState->targetUid, errs.c_str());
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002370 outInjectionResult = InputEventInjectionResult::TARGET_MISMATCH;
Prabir Pradhan5735a322022-04-11 17:23:34 +00002371 goto Failed;
2372 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002373 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002374
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375 // Check whether windows listening for outside touches are owned by the same UID. If it is
2376 // set the policy flag that we will not reveal coordinate information to this window.
2377 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002378 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002379 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002380 if (foregroundWindowHandle) {
2381 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002382 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002383 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002384 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2385 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2386 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002387 InputTarget::FLAG_ZERO_COORDS,
2388 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390 }
2391 }
2392 }
2393 }
2394
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 // If this is the first pointer going down and the touched window has a wallpaper
2396 // then also add the touched wallpaper windows so they are locked in for the duration
2397 // of the touch gesture.
2398 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2399 // engine only supports touch events. We would need to add a mechanism similar
2400 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2401 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002402 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002403 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002404 if (foregroundWindowHandle &&
2405 foregroundWindowHandle->getInfo()->inputConfig.test(
2406 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002407 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002408 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002409 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2410 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002411 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002412 windowHandle->getInfo()->inputConfig.test(
2413 WindowInfo::InputConfig::IS_WALLPAPER)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002414 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002415 .addOrUpdateWindow(windowHandle,
2416 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2417 InputTarget::
2418 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2419 InputTarget::FLAG_DISPATCH_AS_IS,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002420 BitSet32(0), entry.eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 }
2422 }
2423 }
2424 }
2425
2426 // Success! Output targets.
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002427 touchedWindows = tempTouchState.windows;
2428 outInjectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429
2430 // Drop the outside or hover touch windows since we will not care about them
2431 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002432 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433
2434Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002436 if (switchedDevice) {
2437 if (DEBUG_FOCUS) {
2438 ALOGD("Conflicting pointer actions: Switched to a different device.");
2439 }
2440 *outConflictingPointerActions = true;
2441 }
2442
2443 if (isHoverAction) {
2444 // Started hovering, therefore no longer down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002445 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002446 ALOGD_IF(DEBUG_FOCUS,
2447 "Conflicting pointer actions: Hover received while pointer was down.");
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002448 *outConflictingPointerActions = true;
2449 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002450 tempTouchState.reset();
2451 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2452 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2453 tempTouchState.deviceId = entry.deviceId;
2454 tempTouchState.source = entry.source;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002455 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002456 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2457 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2458 // All pointers up or canceled.
2459 tempTouchState.reset();
2460 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2461 // First pointer went down.
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07002462 if (oldState && oldState->isDown()) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08002463 ALOGD("Conflicting pointer actions: Down received while already down.");
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002464 *outConflictingPointerActions = true;
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002465 }
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002466 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2467 // One pointer went up.
2468 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2469 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002471 for (size_t i = 0; i < tempTouchState.windows.size();) {
2472 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2473 touchedWindow.pointerIds.clearBit(pointerId);
2474 if (touchedWindow.pointerIds.isEmpty()) {
2475 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2476 continue;
2477 }
2478 i += 1;
2479 }
2480 } else if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2481 // If no split, we suppose all touched windows should receive pointer down.
2482 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2483 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2484 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2485 // Ignore drag window for it should just track one pointer.
2486 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2487 continue;
2488 }
2489 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 }
2492
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002493 // Save changes unless the action was scroll in which case the temporary touch
2494 // state was only valid for this one action.
2495 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07002496 if (displayId >= 0) {
Siarhei Vishniakou79c32662022-10-25 17:56:25 -07002497 mTouchStatesByDisplay[displayId] = tempTouchState;
2498 } else {
2499 mTouchStatesByDisplay.erase(displayId);
2500 }
2501 }
2502
2503 // Update hover state.
2504 mLastHoverWindowHandle = newHoverWindowHandle;
2505
Siarhei Vishniakou6278ca22022-10-25 11:19:19 -07002506 return touchedWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507}
2508
arthurhung6d4bed92021-03-17 11:59:33 +08002509void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002510 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2511 // have an explicit reason to support it.
2512 constexpr bool isStylus = false;
2513
chaviw98318de2021-05-19 16:45:23 -05002514 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002515 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002516 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002517 if (dropWindow) {
2518 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002519 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002520 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002521 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002522 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002523 }
2524 mDragState.reset();
2525}
2526
2527void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002528 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002529 return;
2530 }
2531
arthurhung6d4bed92021-03-17 11:59:33 +08002532 if (!mDragState->isStartDrag) {
2533 mDragState->isStartDrag = true;
2534 mDragState->isStylusButtonDownAtStart =
2535 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2536 }
2537
Arthur Hung54745652022-04-20 07:17:41 +00002538 // Find the pointer index by id.
2539 int32_t pointerIndex = 0;
2540 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2541 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2542 if (pointerProperties.id == mDragState->pointerId) {
2543 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002544 }
Arthur Hung54745652022-04-20 07:17:41 +00002545 }
arthurhung6d4bed92021-03-17 11:59:33 +08002546
Arthur Hung54745652022-04-20 07:17:41 +00002547 if (uint32_t(pointerIndex) == entry.pointerCount) {
2548 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002549 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002550 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002551 return;
2552 }
2553
2554 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
2555 const int32_t x = entry.pointerCoords[pointerIndex].getX();
2556 const int32_t y = entry.pointerCoords[pointerIndex].getY();
2557
2558 switch (maskedAction) {
2559 case AMOTION_EVENT_ACTION_MOVE: {
2560 // Handle the special case : stylus button no longer pressed.
2561 bool isStylusButtonDown =
2562 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2563 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2564 finishDragAndDrop(entry.displayId, x, y);
2565 return;
2566 }
2567
2568 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2569 // until we have an explicit reason to support it.
2570 constexpr bool isStylus = false;
2571
2572 const sp<WindowInfoHandle> hoverWindowHandle =
2573 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2574 isStylus, false /*addOutsideTargets*/,
2575 true /*ignoreDragWindow*/);
2576 // enqueue drag exit if needed.
2577 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2578 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2579 if (mDragState->dragHoverWindowHandle != nullptr) {
2580 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2581 y);
2582 }
2583 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2584 }
2585 // enqueue drag location if needed.
2586 if (hoverWindowHandle != nullptr) {
2587 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2588 }
2589 break;
2590 }
2591
2592 case AMOTION_EVENT_ACTION_POINTER_UP:
2593 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2594 break;
2595 }
2596 // The drag pointer is up.
2597 [[fallthrough]];
2598 case AMOTION_EVENT_ACTION_UP:
2599 finishDragAndDrop(entry.displayId, x, y);
2600 break;
2601 case AMOTION_EVENT_ACTION_CANCEL: {
2602 ALOGD("Receiving cancel when drag and drop.");
2603 sendDropWindowCommandLocked(nullptr, 0, 0);
2604 mDragState.reset();
2605 break;
2606 }
arthurhungb89ccb02020-12-30 16:19:01 +08002607 }
2608}
2609
chaviw98318de2021-05-19 16:45:23 -05002610void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002611 int32_t targetFlags, BitSet32 pointerIds,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002612 std::optional<nsecs_t> firstDownTimeInTarget,
Siarhei Vishniakouf75cddb2022-10-25 10:42:16 -07002613 std::vector<InputTarget>& inputTargets) const {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002614 std::vector<InputTarget>::iterator it =
2615 std::find_if(inputTargets.begin(), inputTargets.end(),
2616 [&windowHandle](const InputTarget& inputTarget) {
2617 return inputTarget.inputChannel->getConnectionToken() ==
2618 windowHandle->getToken();
2619 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00002620
chaviw98318de2021-05-19 16:45:23 -05002621 const WindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002622
2623 if (it == inputTargets.end()) {
2624 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002625 std::shared_ptr<InputChannel> inputChannel =
2626 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002627 if (inputChannel == nullptr) {
2628 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
2629 return;
2630 }
2631 inputTarget.inputChannel = inputChannel;
2632 inputTarget.flags = targetFlags;
2633 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002634 inputTarget.firstDownTimeInTarget = firstDownTimeInTarget;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002635 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2636 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002637 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002638 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002639 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002640 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002641 inputTargets.push_back(inputTarget);
2642 it = inputTargets.end() - 1;
2643 }
2644
2645 ALOG_ASSERT(it->flags == targetFlags);
2646 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2647
chaviw1ff3d1e2020-07-01 15:53:47 -07002648 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649}
2650
Michael Wright3dd60e22019-03-27 22:06:44 +00002651void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002652 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002653 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2654 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002655
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002656 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2657 InputTarget target;
2658 target.inputChannel = monitor.inputChannel;
2659 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002660 // target.firstDownTimeInTarget is not set for global monitors. It is only required in split
2661 // touch and global monitoring works as intended even without setting firstDownTimeInTarget
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002662 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2663 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002664 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002665 target.setDefaultPointerTransform(target.displayTransform);
2666 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667 }
2668}
2669
Robert Carrc9bf1d32020-04-13 17:21:08 -07002670/**
2671 * Indicate whether one window handle should be considered as obscuring
2672 * another window handle. We only check a few preconditions. Actually
2673 * checking the bounds is left to the caller.
2674 */
chaviw98318de2021-05-19 16:45:23 -05002675static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2676 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002677 // Compare by token so cloned layers aren't counted
2678 if (haveSameToken(windowHandle, otherHandle)) {
2679 return false;
2680 }
2681 auto info = windowHandle->getInfo();
2682 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002683 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002684 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002685 } else if (otherInfo->alpha == 0 &&
2686 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002687 // Those act as if they were invisible, so we don't need to flag them.
2688 // We do want to potentially flag touchable windows even if they have 0
2689 // opacity, since they can consume touches and alter the effects of the
2690 // user interaction (eg. apps that rely on
2691 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2692 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2693 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002694 } else if (info->ownerUid == otherInfo->ownerUid) {
2695 // If ownerUid is the same we don't generate occlusion events as there
2696 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002697 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002698 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002699 return false;
2700 } else if (otherInfo->displayId != info->displayId) {
2701 return false;
2702 }
2703 return true;
2704}
2705
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002706/**
2707 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2708 * untrusted, one should check:
2709 *
2710 * 1. If result.hasBlockingOcclusion is true.
2711 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2712 * BLOCK_UNTRUSTED.
2713 *
2714 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2715 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2716 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2717 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2718 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2719 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2720 *
2721 * If neither of those is true, then it means the touch can be allowed.
2722 */
2723InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002724 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2725 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002726 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002727 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002728 TouchOcclusionInfo info;
2729 info.hasBlockingOcclusion = false;
2730 info.obscuringOpacity = 0;
2731 info.obscuringUid = -1;
2732 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002733 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002734 if (windowHandle == otherHandle) {
2735 break; // All future windows are below us. Exit early.
2736 }
chaviw98318de2021-05-19 16:45:23 -05002737 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002738 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2739 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002740 if (DEBUG_TOUCH_OCCLUSION) {
2741 info.debugInfo.push_back(
2742 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2743 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002744 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2745 // we perform the checks below to see if the touch can be propagated or not based on the
2746 // window's touch occlusion mode
2747 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2748 info.hasBlockingOcclusion = true;
2749 info.obscuringUid = otherInfo->ownerUid;
2750 info.obscuringPackage = otherInfo->packageName;
2751 break;
2752 }
2753 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2754 uint32_t uid = otherInfo->ownerUid;
2755 float opacity =
2756 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2757 // Given windows A and B:
2758 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2759 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2760 opacityByUid[uid] = opacity;
2761 if (opacity > info.obscuringOpacity) {
2762 info.obscuringOpacity = opacity;
2763 info.obscuringUid = uid;
2764 info.obscuringPackage = otherInfo->packageName;
2765 }
2766 }
2767 }
2768 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002769 if (DEBUG_TOUCH_OCCLUSION) {
2770 info.debugInfo.push_back(
2771 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2772 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002773 return info;
2774}
2775
chaviw98318de2021-05-19 16:45:23 -05002776std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002777 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002778 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2779 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2780 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2781 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002782 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2783 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2784 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2785 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2786 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002787 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002788 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002789}
2790
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002791bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2792 if (occlusionInfo.hasBlockingOcclusion) {
2793 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2794 occlusionInfo.obscuringUid);
2795 return false;
2796 }
2797 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2798 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2799 "%.2f, maximum allowed = %.2f)",
2800 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2801 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2802 return false;
2803 }
2804 return true;
2805}
2806
chaviw98318de2021-05-19 16:45:23 -05002807bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002810 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2811 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002812 if (windowHandle == otherHandle) {
2813 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814 }
chaviw98318de2021-05-19 16:45:23 -05002815 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002816 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002817 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 return true;
2819 }
2820 }
2821 return false;
2822}
2823
chaviw98318de2021-05-19 16:45:23 -05002824bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002825 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002826 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2827 const WindowInfo* windowInfo = windowHandle->getInfo();
2828 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002829 if (windowHandle == otherHandle) {
2830 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002831 }
chaviw98318de2021-05-19 16:45:23 -05002832 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002833 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002834 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002835 return true;
2836 }
2837 }
2838 return false;
2839}
2840
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002841std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002842 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002843 if (applicationHandle != nullptr) {
2844 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002845 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846 } else {
2847 return applicationHandle->getName();
2848 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002849 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002850 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002852 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 }
2854}
2855
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002856void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002857 if (!isUserActivityEvent(eventEntry)) {
2858 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002859 return;
2860 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002861 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002862 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002863 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002864 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002865 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002866 if (DEBUG_DISPATCH_CYCLE) {
2867 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002869 return;
2870 }
2871 }
2872
2873 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002874 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002875 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002876 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2877 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002878 return;
2879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002881 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002882 eventType = USER_ACTIVITY_EVENT_TOUCH;
2883 }
2884 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002886 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002887 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2888 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002889 return;
2890 }
2891 eventType = USER_ACTIVITY_EVENT_BUTTON;
2892 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002894 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002895 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002896 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002897 break;
2898 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899 }
2900
Prabir Pradhancef936d2021-07-21 16:17:52 +00002901 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2902 REQUIRES(mLock) {
2903 scoped_unlock unlock(mLock);
2904 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2905 };
2906 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002907}
2908
2909void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002910 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002911 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002912 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002913 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002914 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002915 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002916 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002917 ATRACE_NAME(message.c_str());
2918 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002919 if (DEBUG_DISPATCH_CYCLE) {
2920 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2921 "globalScaleFactor=%f, pointerIds=0x%x %s",
2922 connection->getInputChannelName().c_str(), inputTarget.flags,
2923 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2924 inputTarget.getPointerInfoString().c_str());
2925 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926
2927 // Skip this event if the connection status is not normal.
2928 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002929 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002930 if (DEBUG_DISPATCH_CYCLE) {
2931 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002932 connection->getInputChannelName().c_str(),
2933 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002934 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935 return;
2936 }
2937
2938 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002939 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2940 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2941 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002942 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002944 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002945 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002946 LOG_ALWAYS_FATAL_IF(!inputTarget.firstDownTimeInTarget.has_value(),
2947 "Splitting motion events requires a down time to be set for the "
2948 "target");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002949 std::unique_ptr<MotionEntry> splitMotionEntry =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00002950 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds,
2951 inputTarget.firstDownTimeInTarget.value());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002952 if (!splitMotionEntry) {
2953 return; // split event was dropped
2954 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002955 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2956 std::string reason = std::string("reason=pointer cancel on split window");
2957 android_log_event_list(LOGTAG_INPUT_CANCEL)
2958 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2959 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002960 if (DEBUG_FOCUS) {
2961 ALOGD("channel '%s' ~ Split motion event.",
2962 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002963 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002964 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002965 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2966 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002967 return;
2968 }
2969 }
2970
2971 // Not splitting. Enqueue dispatch entries for the event as is.
2972 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2973}
2974
2975void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002976 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002977 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002978 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002979 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002980 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002981 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002982 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002983 ATRACE_NAME(message.c_str());
2984 }
2985
hongzuo liu95785e22022-09-06 02:51:35 +00002986 const bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002987
2988 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002989 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002990 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002991 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002992 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002993 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002994 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002995 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002996 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002997 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002998 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002999 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003000 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001
3002 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003003 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004 startDispatchCycleLocked(currentTime, connection);
3005 }
3006}
3007
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003008void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003009 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003010 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003011 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003012 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003013 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3014 connection->getInputChannelName().c_str(),
3015 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003016 ATRACE_NAME(message.c_str());
3017 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003018 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 if (!(inputTargetFlags & dispatchMode)) {
3020 return;
3021 }
3022 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
3023
3024 // This is a new event.
3025 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003026 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003027 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003029 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3030 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003031 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003033 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003034 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003035 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003036 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003037 dispatchEntry->resolvedAction = keyEntry.action;
3038 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003040 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3041 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003042 if (DEBUG_DISPATCH_CYCLE) {
3043 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3044 "event",
3045 connection->getInputChannelName().c_str());
3046 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003047 return; // skip the inconsistent event
3048 }
3049 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003052 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003053 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003054 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3055 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3056 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3057 static_cast<int32_t>(IdGenerator::Source::OTHER);
3058 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003059 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3060 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3061 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3062 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3063 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3064 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3065 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3066 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3067 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3068 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3069 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003070 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003071 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003072 }
3073 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003074 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3075 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003076 if (DEBUG_DISPATCH_CYCLE) {
3077 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3078 "enter event",
3079 connection->getInputChannelName().c_str());
3080 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003081 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3082 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003083 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003086 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003087 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3088 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3089 }
3090 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3091 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3092 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003094 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3095 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003096 if (DEBUG_DISPATCH_CYCLE) {
3097 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3098 "event",
3099 connection->getInputChannelName().c_str());
3100 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003101 return; // skip the inconsistent event
3102 }
3103
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003104 dispatchEntry->resolvedEventId =
3105 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3106 ? mIdGenerator.nextId()
3107 : motionEntry.id;
3108 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3109 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3110 ") to MotionEvent(id=0x%" PRIx32 ").",
3111 motionEntry.id, dispatchEntry->resolvedEventId);
3112 ATRACE_NAME(message.c_str());
3113 }
3114
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003115 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3116 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3117 // Skip reporting pointer down outside focus to the policy.
3118 break;
3119 }
3120
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003121 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003122 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003123
3124 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003126 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003127 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003128 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3129 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003130 break;
3131 }
Chris Yef59a2f42020-10-16 12:55:26 -07003132 case EventEntry::Type::SENSOR: {
3133 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3134 break;
3135 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003136 case EventEntry::Type::CONFIGURATION_CHANGED:
3137 case EventEntry::Type::DEVICE_RESET: {
3138 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003139 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003140 break;
3141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 }
3143
3144 // Remember that we are waiting for this dispatch to complete.
3145 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003146 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 }
3148
3149 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003150 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003151 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003152}
3153
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003154/**
3155 * This function is purely for debugging. It helps us understand where the user interaction
3156 * was taking place. For example, if user is touching launcher, we will see a log that user
3157 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3158 * We will see both launcher and wallpaper in that list.
3159 * Once the interaction with a particular set of connections starts, no new logs will be printed
3160 * until the set of interacted connections changes.
3161 *
3162 * The following items are skipped, to reduce the logspam:
3163 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3164 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3165 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3166 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3167 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003168 */
3169void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3170 const std::vector<InputTarget>& targets) {
3171 // Skip ACTION_UP events, and all events other than keys and motions
3172 if (entry.type == EventEntry::Type::KEY) {
3173 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3174 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3175 return;
3176 }
3177 } else if (entry.type == EventEntry::Type::MOTION) {
3178 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3179 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3180 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3181 return;
3182 }
3183 } else {
3184 return; // Not a key or a motion
3185 }
3186
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003187 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003188 std::vector<sp<Connection>> newConnections;
3189 for (const InputTarget& target : targets) {
3190 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3191 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3192 continue; // Skip windows that receive ACTION_OUTSIDE
3193 }
3194
3195 sp<IBinder> token = target.inputChannel->getConnectionToken();
3196 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003197 if (connection == nullptr) {
3198 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003199 }
3200 newConnectionTokens.insert(std::move(token));
3201 newConnections.emplace_back(connection);
3202 }
3203 if (newConnectionTokens == mInteractionConnectionTokens) {
3204 return; // no change
3205 }
3206 mInteractionConnectionTokens = newConnectionTokens;
3207
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003208 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003209 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003210 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003211 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003212 std::string message = "Interaction with: " + targetList;
3213 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003214 message += "<none>";
3215 }
3216 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3217}
3218
chaviwfd6d3512019-03-25 13:23:49 -07003219void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003220 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003221 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003222 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3223 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003224 return;
3225 }
3226
Vishnu Nairc519ff72021-01-21 08:23:08 -08003227 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003228 if (focusedToken == token) {
3229 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003230 return;
3231 }
3232
Prabir Pradhancef936d2021-07-21 16:17:52 +00003233 auto command = [this, token]() REQUIRES(mLock) {
3234 scoped_unlock unlock(mLock);
3235 mPolicy->onPointerDownOutsideFocus(token);
3236 };
3237 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238}
3239
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003240status_t InputDispatcher::publishMotionEvent(Connection& connection,
3241 DispatchEntry& dispatchEntry) const {
3242 const EventEntry& eventEntry = *(dispatchEntry.eventEntry);
3243 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
3244
3245 PointerCoords scaledCoords[MAX_POINTERS];
3246 const PointerCoords* usingCoords = motionEntry.pointerCoords;
3247
3248 // Set the X and Y offset and X and Y scale depending on the input source.
3249 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
3250 !(dispatchEntry.targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3251 float globalScaleFactor = dispatchEntry.globalScaleFactor;
3252 if (globalScaleFactor != 1.0f) {
3253 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3254 scaledCoords[i] = motionEntry.pointerCoords[i];
3255 // Don't apply window scale here since we don't want scale to affect raw
3256 // coordinates. The scale will be sent back to the client and applied
3257 // later when requesting relative coordinates.
3258 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3259 1 /* windowYScale */);
3260 }
3261 usingCoords = scaledCoords;
3262 }
3263 } else if (dispatchEntry.targetFlags & InputTarget::FLAG_ZERO_COORDS) {
3264 // We don't want the dispatch target to know the coordinates
3265 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3266 scaledCoords[i].clear();
3267 }
3268 usingCoords = scaledCoords;
3269 }
3270
3271 std::array<uint8_t, 32> hmac = getSignature(motionEntry, dispatchEntry);
3272
3273 // Publish the motion event.
3274 return connection.inputPublisher
3275 .publishMotionEvent(dispatchEntry.seq, dispatchEntry.resolvedEventId,
3276 motionEntry.deviceId, motionEntry.source, motionEntry.displayId,
3277 std::move(hmac), dispatchEntry.resolvedAction,
3278 motionEntry.actionButton, dispatchEntry.resolvedFlags,
3279 motionEntry.edgeFlags, motionEntry.metaState,
3280 motionEntry.buttonState, motionEntry.classification,
3281 dispatchEntry.transform, motionEntry.xPrecision,
3282 motionEntry.yPrecision, motionEntry.xCursorPosition,
3283 motionEntry.yCursorPosition, dispatchEntry.rawTransform,
3284 motionEntry.downTime, motionEntry.eventTime,
3285 motionEntry.pointerCount, motionEntry.pointerProperties,
3286 usingCoords);
3287}
3288
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003290 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003291 if (ATRACE_ENABLED()) {
3292 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003293 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003294 ATRACE_NAME(message.c_str());
3295 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003296 if (DEBUG_DISPATCH_CYCLE) {
3297 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3298 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003300 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003301 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003303 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003304 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305
3306 // Publish the event.
3307 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003308 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3309 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003310 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003311 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3312 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003314 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003315 status = connection->inputPublisher
3316 .publishKeyEvent(dispatchEntry->seq,
3317 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3318 keyEntry.source, keyEntry.displayId,
3319 std::move(hmac), dispatchEntry->resolvedAction,
3320 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3321 keyEntry.scanCode, keyEntry.metaState,
3322 keyEntry.repeatCount, keyEntry.downTime,
3323 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003324 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 }
3326
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003327 case EventEntry::Type::MOTION: {
Siarhei Vishniakoucce7e112022-10-25 13:31:17 -07003328 status = publishMotionEvent(*connection, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 break;
3330 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003331
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003332 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003333 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003334 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003335 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003336 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003337 break;
3338 }
3339
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003340 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3341 const TouchModeEntry& touchModeEntry =
3342 static_cast<const TouchModeEntry&>(eventEntry);
3343 status = connection->inputPublisher
3344 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3345 touchModeEntry.inTouchMode);
3346
3347 break;
3348 }
3349
Prabir Pradhan99987712020-11-10 18:43:05 -08003350 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3351 const auto& captureEntry =
3352 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3353 status = connection->inputPublisher
3354 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003355 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003356 break;
3357 }
3358
arthurhungb89ccb02020-12-30 16:19:01 +08003359 case EventEntry::Type::DRAG: {
3360 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3361 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3362 dragEntry.id, dragEntry.x,
3363 dragEntry.y,
3364 dragEntry.isExiting);
3365 break;
3366 }
3367
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003368 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003369 case EventEntry::Type::DEVICE_RESET:
3370 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003371 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003372 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003373 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 }
3376
3377 // Check the result.
3378 if (status) {
3379 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003380 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003382 "This is unexpected because the wait queue is empty, so the pipe "
3383 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003384 "event to it, status=%s(%d)",
3385 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3386 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3388 } else {
3389 // Pipe is full and we are waiting for the app to finish process some events
3390 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003391 if (DEBUG_DISPATCH_CYCLE) {
3392 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3393 "waiting for the application to catch up",
3394 connection->getInputChannelName().c_str());
3395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 }
3397 } else {
3398 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003399 "status=%s(%d)",
3400 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3401 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3403 }
3404 return;
3405 }
3406
3407 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003408 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3409 connection->outboundQueue.end(),
3410 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003411 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003412 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003413 if (connection->responsive) {
3414 mAnrTracker.insert(dispatchEntry->timeoutTime,
3415 connection->inputChannel->getConnectionToken());
3416 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003417 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 }
3419}
3420
chaviw09c8d2d2020-08-24 15:48:26 -07003421std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3422 size_t size;
3423 switch (event.type) {
3424 case VerifiedInputEvent::Type::KEY: {
3425 size = sizeof(VerifiedKeyEvent);
3426 break;
3427 }
3428 case VerifiedInputEvent::Type::MOTION: {
3429 size = sizeof(VerifiedMotionEvent);
3430 break;
3431 }
3432 }
3433 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3434 return mHmacKeyManager.sign(start, size);
3435}
3436
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003437const std::array<uint8_t, 32> InputDispatcher::getSignature(
3438 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003439 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3440 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003441 // Only sign events up and down events as the purely move events
3442 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003443 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003444 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003445
3446 VerifiedMotionEvent verifiedEvent =
3447 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3448 verifiedEvent.actionMasked = actionMasked;
3449 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3450 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003451}
3452
3453const std::array<uint8_t, 32> InputDispatcher::getSignature(
3454 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3455 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3456 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3457 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003458 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003459}
3460
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003462 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003463 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003464 if (DEBUG_DISPATCH_CYCLE) {
3465 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3466 connection->getInputChannelName().c_str(), seq, toString(handled));
3467 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003469 if (connection->status == Connection::Status::BROKEN ||
3470 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 return;
3472 }
3473
3474 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003475 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3476 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3477 };
3478 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479}
3480
3481void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003482 const sp<Connection>& connection,
3483 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003484 if (DEBUG_DISPATCH_CYCLE) {
3485 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3486 connection->getInputChannelName().c_str(), toString(notify));
3487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488
3489 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003490 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003491 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003492 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003493 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494
3495 // The connection appears to be unrecoverably broken.
3496 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003497 if (connection->status == Connection::Status::NORMAL) {
3498 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499
3500 if (notify) {
3501 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003502 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3503 connection->getInputChannelName().c_str());
3504
3505 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003506 scoped_unlock unlock(mLock);
3507 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3508 };
3509 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510 }
3511 }
3512}
3513
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003514void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3515 while (!queue.empty()) {
3516 DispatchEntry* dispatchEntry = queue.front();
3517 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003518 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519 }
3520}
3521
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003522void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003524 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525 }
3526 delete dispatchEntry;
3527}
3528
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003529int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3530 std::scoped_lock _l(mLock);
3531 sp<Connection> connection = getConnectionLocked(connectionToken);
3532 if (connection == nullptr) {
3533 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3534 connectionToken.get(), events);
3535 return 0; // remove the callback
3536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003538 bool notify;
3539 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3540 if (!(events & ALOOPER_EVENT_INPUT)) {
3541 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3542 "events=0x%x",
3543 connection->getInputChannelName().c_str(), events);
3544 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 }
3546
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003547 nsecs_t currentTime = now();
3548 bool gotOne = false;
3549 status_t status = OK;
3550 for (;;) {
3551 Result<InputPublisher::ConsumerResponse> result =
3552 connection->inputPublisher.receiveConsumerResponse();
3553 if (!result.ok()) {
3554 status = result.error().code();
3555 break;
3556 }
3557
3558 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3559 const InputPublisher::Finished& finish =
3560 std::get<InputPublisher::Finished>(*result);
3561 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3562 finish.consumeTime);
3563 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003564 if (shouldReportMetricsForConnection(*connection)) {
3565 const InputPublisher::Timeline& timeline =
3566 std::get<InputPublisher::Timeline>(*result);
3567 mLatencyTracker
3568 .trackGraphicsLatency(timeline.inputEventId,
3569 connection->inputChannel->getConnectionToken(),
3570 std::move(timeline.graphicsTimeline));
3571 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003572 }
3573 gotOne = true;
3574 }
3575 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003576 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003577 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578 return 1;
3579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 }
3581
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003582 notify = status != DEAD_OBJECT || !connection->monitor;
3583 if (notify) {
3584 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3585 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3586 status);
3587 }
3588 } else {
3589 // Monitor channels are never explicitly unregistered.
3590 // We do it automatically when the remote endpoint is closed so don't warn about them.
3591 const bool stillHaveWindowHandle =
3592 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3593 notify = !connection->monitor && stillHaveWindowHandle;
3594 if (notify) {
3595 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3596 connection->getInputChannelName().c_str(), events);
3597 }
3598 }
3599
3600 // Remove the channel.
3601 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3602 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603}
3604
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003605void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003607 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003608 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 }
3610}
3611
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003612void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003613 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003614 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003615 for (const Monitor& monitor : monitors) {
3616 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003617 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003618 }
3619}
3620
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003622 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003623 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003624 if (connection == nullptr) {
3625 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003627
3628 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629}
3630
3631void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3632 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003633 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 return;
3635 }
3636
3637 nsecs_t currentTime = now();
3638
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003639 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003640 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003642 if (cancelationEvents.empty()) {
3643 return;
3644 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003645 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3646 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3647 "with reality: %s, mode=%d.",
3648 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3649 options.mode);
3650 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003651
Arthur Hungb3307ee2021-10-14 10:57:37 +00003652 std::string reason = std::string("reason=").append(options.reason);
3653 android_log_event_list(LOGTAG_INPUT_CANCEL)
3654 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3655
Svet Ganov5d3bc372020-01-26 23:11:07 -08003656 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003657 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003658 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3659 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003660 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003661 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003662 target.globalScaleFactor = windowInfo->globalScaleFactor;
3663 }
3664 target.inputChannel = connection->inputChannel;
3665 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3666
hongzuo liu95785e22022-09-06 02:51:35 +00003667 const bool wasEmpty = connection->outboundQueue.empty();
3668
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003669 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003670 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003671 switch (cancelationEventEntry->type) {
3672 case EventEntry::Type::KEY: {
3673 logOutboundKeyDetails("cancel - ",
3674 static_cast<const KeyEntry&>(*cancelationEventEntry));
3675 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003677 case EventEntry::Type::MOTION: {
3678 logOutboundMotionDetails("cancel - ",
3679 static_cast<const MotionEntry&>(*cancelationEventEntry));
3680 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003682 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003683 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003684 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3685 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003686 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003687 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003688 break;
3689 }
3690 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003691 case EventEntry::Type::DEVICE_RESET:
3692 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003693 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003694 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003695 break;
3696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 }
3698
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003699 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3700 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003702
hongzuo liu95785e22022-09-06 02:51:35 +00003703 // If the outbound queue was previously empty, start the dispatch cycle going.
3704 if (wasEmpty && !connection->outboundQueue.empty()) {
3705 startDispatchCycleLocked(currentTime, connection);
3706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707}
3708
Svet Ganov5d3bc372020-01-26 23:11:07 -08003709void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003710 const nsecs_t downTime, const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003711 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003712 return;
3713 }
3714
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003715 std::vector<std::unique_ptr<EventEntry>> downEvents =
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003716 connection->inputState.synthesizePointerDownEvents(downTime);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003717
3718 if (downEvents.empty()) {
3719 return;
3720 }
3721
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003722 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003723 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3724 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003725 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003726
3727 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003728 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003729 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3730 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003731 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003732 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003733 target.globalScaleFactor = windowInfo->globalScaleFactor;
3734 }
3735 target.inputChannel = connection->inputChannel;
3736 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3737
hongzuo liu95785e22022-09-06 02:51:35 +00003738 const bool wasEmpty = connection->outboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003739 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003740 switch (downEventEntry->type) {
3741 case EventEntry::Type::MOTION: {
3742 logOutboundMotionDetails("down - ",
3743 static_cast<const MotionEntry&>(*downEventEntry));
3744 break;
3745 }
3746
3747 case EventEntry::Type::KEY:
3748 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003749 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003750 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003751 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003752 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003753 case EventEntry::Type::SENSOR:
3754 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003755 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003756 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003757 break;
3758 }
3759 }
3760
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003761 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3762 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003763 }
3764
hongzuo liu95785e22022-09-06 02:51:35 +00003765 // If the outbound queue was previously empty, start the dispatch cycle going.
3766 if (wasEmpty && !connection->outboundQueue.empty()) {
3767 startDispatchCycleLocked(downTime, connection);
3768 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003769}
3770
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003771std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003772 const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 ALOG_ASSERT(pointerIds.value != 0);
3774
3775 uint32_t splitPointerIndexMap[MAX_POINTERS];
3776 PointerProperties splitPointerProperties[MAX_POINTERS];
3777 PointerCoords splitPointerCoords[MAX_POINTERS];
3778
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003779 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 uint32_t splitPointerCount = 0;
3781
3782 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003783 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003785 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 uint32_t pointerId = uint32_t(pointerProperties.id);
3787 if (pointerIds.hasBit(pointerId)) {
3788 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3789 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3790 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003791 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792 splitPointerCount += 1;
3793 }
3794 }
3795
3796 if (splitPointerCount != pointerIds.count()) {
3797 // This is bad. We are missing some of the pointers that we expected to deliver.
3798 // Most likely this indicates that we received an ACTION_MOVE events that has
3799 // different pointer ids than we expected based on the previous ACTION_DOWN
3800 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3801 // in this way.
3802 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003803 "we expected there to be %d pointers. This probably means we received "
3804 "a broken sequence of pointer ids from the input device.",
3805 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003806 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 }
3808
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003809 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003811 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3812 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3814 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003815 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816 uint32_t pointerId = uint32_t(pointerProperties.id);
3817 if (pointerIds.hasBit(pointerId)) {
3818 if (pointerIds.count() == 1) {
3819 // The first/last pointer went down/up.
3820 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003821 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003822 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3823 ? AMOTION_EVENT_ACTION_CANCEL
3824 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 } else {
3826 // A secondary pointer went down/up.
3827 uint32_t splitPointerIndex = 0;
3828 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3829 splitPointerIndex += 1;
3830 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003831 action = maskedAction |
3832 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 }
3834 } else {
3835 // An unrelated pointer changed.
3836 action = AMOTION_EVENT_ACTION_MOVE;
3837 }
3838 }
3839
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003840 if (action == AMOTION_EVENT_ACTION_DOWN) {
3841 LOG_ALWAYS_FATAL_IF(splitDownTime != originalMotionEntry.eventTime,
3842 "Split motion event has mismatching downTime and eventTime for "
3843 "ACTION_DOWN, motionEntry=%s, splitDownTime=%" PRId64 "ms",
3844 originalMotionEntry.getDescription().c_str(), ns2ms(splitDownTime));
3845 }
3846
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003847 int32_t newId = mIdGenerator.nextId();
3848 if (ATRACE_ENABLED()) {
3849 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3850 ") to MotionEvent(id=0x%" PRIx32 ").",
3851 originalMotionEntry.id, newId);
3852 ATRACE_NAME(message.c_str());
3853 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003854 std::unique_ptr<MotionEntry> splitMotionEntry =
3855 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3856 originalMotionEntry.deviceId, originalMotionEntry.source,
3857 originalMotionEntry.displayId,
3858 originalMotionEntry.policyFlags, action,
3859 originalMotionEntry.actionButton,
3860 originalMotionEntry.flags, originalMotionEntry.metaState,
3861 originalMotionEntry.buttonState,
3862 originalMotionEntry.classification,
3863 originalMotionEntry.edgeFlags,
3864 originalMotionEntry.xPrecision,
3865 originalMotionEntry.yPrecision,
3866 originalMotionEntry.xCursorPosition,
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00003867 originalMotionEntry.yCursorPosition, splitDownTime,
3868 splitPointerCount, splitPointerProperties,
3869 splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003871 if (originalMotionEntry.injectionState) {
3872 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873 splitMotionEntry->injectionState->refCount += 1;
3874 }
3875
3876 return splitMotionEntry;
3877}
3878
3879void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003880 if (DEBUG_INBOUND_EVENT_DETAILS) {
3881 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3882 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883
Antonio Kantekf16f2832021-09-28 04:39:20 +00003884 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003886 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003888 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3889 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3890 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891 } // release lock
3892
3893 if (needWake) {
3894 mLooper->wake();
3895 }
3896}
3897
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003898/**
3899 * If one of the meta shortcuts is detected, process them here:
3900 * Meta + Backspace -> generate BACK
3901 * Meta + Enter -> generate HOME
3902 * This will potentially overwrite keyCode and metaState.
3903 */
3904void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003905 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003906 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3907 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3908 if (keyCode == AKEYCODE_DEL) {
3909 newKeyCode = AKEYCODE_BACK;
3910 } else if (keyCode == AKEYCODE_ENTER) {
3911 newKeyCode = AKEYCODE_HOME;
3912 }
3913 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003914 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003915 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003916 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003917 keyCode = newKeyCode;
3918 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3919 }
3920 } else if (action == AKEY_EVENT_ACTION_UP) {
3921 // In order to maintain a consistent stream of up and down events, check to see if the key
3922 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3923 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003924 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003925 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003926 auto replacementIt = mReplacedKeys.find(replacement);
3927 if (replacementIt != mReplacedKeys.end()) {
3928 keyCode = replacementIt->second;
3929 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003930 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3931 }
3932 }
3933}
3934
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003936 if (DEBUG_INBOUND_EVENT_DETAILS) {
3937 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3938 "policyFlags=0x%x, action=0x%x, "
3939 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3940 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3941 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3942 args->downTime);
3943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 if (!validateKeyEvent(args->action)) {
3945 return;
3946 }
3947
3948 uint32_t policyFlags = args->policyFlags;
3949 int32_t flags = args->flags;
3950 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003951 // InputDispatcher tracks and generates key repeats on behalf of
3952 // whatever notifies it, so repeatCount should always be set to 0
3953 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3955 policyFlags |= POLICY_FLAG_VIRTUAL;
3956 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 if (policyFlags & POLICY_FLAG_FUNCTION) {
3959 metaState |= AMETA_FUNCTION_ON;
3960 }
3961
3962 policyFlags |= POLICY_FLAG_TRUSTED;
3963
Michael Wright78f24442014-08-06 15:55:28 -07003964 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003965 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003966
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003968 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003969 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3970 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971
Michael Wright2b3c3302018-03-02 17:19:13 +00003972 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003974 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3975 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003976 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978
Antonio Kantekf16f2832021-09-28 04:39:20 +00003979 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 { // acquire lock
3981 mLock.lock();
3982
3983 if (shouldSendKeyToInputFilterLocked(args)) {
3984 mLock.unlock();
3985
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003986 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3988 return; // event was consumed by the filter
3989 }
3990
3991 mLock.lock();
3992 }
3993
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003994 std::unique_ptr<KeyEntry> newEntry =
3995 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3996 args->displayId, policyFlags, args->action, flags,
3997 keyCode, args->scanCode, metaState, repeatCount,
3998 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004000 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 mLock.unlock();
4002 } // release lock
4003
4004 if (needWake) {
4005 mLooper->wake();
4006 }
4007}
4008
4009bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4010 return mInputFilterEnabled;
4011}
4012
4013void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004014 if (DEBUG_INBOUND_EVENT_DETAILS) {
4015 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4016 "displayId=%" PRId32 ", policyFlags=0x%x, "
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004017 "action=%s, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004018 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4019 "yCursorPosition=%f, downTime=%" PRId64,
4020 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
Siarhei Vishniakou6ebd0692022-10-20 15:05:45 -07004021 args->policyFlags, MotionEvent::actionToString(args->action).c_str(),
4022 args->actionButton, args->flags, args->metaState, args->buttonState, args->edgeFlags,
4023 args->xPrecision, args->yPrecision, args->xCursorPosition, args->yCursorPosition,
4024 args->downTime);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004025 for (uint32_t i = 0; i < args->pointerCount; i++) {
4026 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4027 "x=%f, y=%f, pressure=%f, size=%f, "
4028 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4029 "orientation=%f",
4030 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4031 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4032 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4033 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4034 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4035 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4036 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4037 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4038 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4039 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4040 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004042 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4043 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044 return;
4045 }
4046
4047 uint32_t policyFlags = args->policyFlags;
4048 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004049
4050 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004051 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004052 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4053 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004054 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056
Antonio Kantekf16f2832021-09-28 04:39:20 +00004057 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058 { // acquire lock
4059 mLock.lock();
4060
4061 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004062 ui::Transform displayTransform;
4063 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4064 displayTransform = it->second.transform;
4065 }
4066
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067 mLock.unlock();
4068
4069 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004070 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4071 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004072 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004073 displayTransform, args->xPrecision, args->yPrecision,
4074 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004075 args->downTime, args->eventTime, args->pointerCount,
4076 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077
4078 policyFlags |= POLICY_FLAG_FILTERED;
4079 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4080 return; // event was consumed by the filter
4081 }
4082
4083 mLock.lock();
4084 }
4085
4086 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004087 std::unique_ptr<MotionEntry> newEntry =
4088 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4089 args->source, args->displayId, policyFlags,
4090 args->action, args->actionButton, args->flags,
4091 args->metaState, args->buttonState,
4092 args->classification, args->edgeFlags,
4093 args->xPrecision, args->yPrecision,
4094 args->xCursorPosition, args->yCursorPosition,
4095 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004096 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004098 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4099 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4100 !mInputFilterEnabled) {
4101 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4102 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4103 }
4104
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004105 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 mLock.unlock();
4107 } // release lock
4108
4109 if (needWake) {
4110 mLooper->wake();
4111 }
4112}
4113
Chris Yef59a2f42020-10-16 12:55:26 -07004114void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004115 if (DEBUG_INBOUND_EVENT_DETAILS) {
4116 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4117 " sensorType=%s",
4118 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004119 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004120 }
Chris Yef59a2f42020-10-16 12:55:26 -07004121
Antonio Kantekf16f2832021-09-28 04:39:20 +00004122 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004123 { // acquire lock
4124 mLock.lock();
4125
4126 // Just enqueue a new sensor event.
4127 std::unique_ptr<SensorEntry> newEntry =
4128 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4129 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4130 args->sensorType, args->accuracy,
4131 args->accuracyChanged, args->values);
4132
4133 needWake = enqueueInboundEventLocked(std::move(newEntry));
4134 mLock.unlock();
4135 } // release lock
4136
4137 if (needWake) {
4138 mLooper->wake();
4139 }
4140}
4141
Chris Yefb552902021-02-03 17:18:37 -08004142void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004143 if (DEBUG_INBOUND_EVENT_DETAILS) {
4144 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4145 args->deviceId, args->isOn);
4146 }
Chris Yefb552902021-02-03 17:18:37 -08004147 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4148}
4149
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004151 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152}
4153
4154void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004155 if (DEBUG_INBOUND_EVENT_DETAILS) {
4156 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4157 "switchMask=0x%08x",
4158 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4159 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160
4161 uint32_t policyFlags = args->policyFlags;
4162 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004163 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164}
4165
4166void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004167 if (DEBUG_INBOUND_EVENT_DETAILS) {
4168 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4169 args->deviceId);
4170 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171
Antonio Kantekf16f2832021-09-28 04:39:20 +00004172 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004174 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004176 std::unique_ptr<DeviceResetEntry> newEntry =
4177 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4178 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179 } // release lock
4180
4181 if (needWake) {
4182 mLooper->wake();
4183 }
4184}
4185
Prabir Pradhan7e186182020-11-10 13:56:45 -08004186void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004187 if (DEBUG_INBOUND_EVENT_DETAILS) {
4188 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004189 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004190 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004191
Antonio Kantekf16f2832021-09-28 04:39:20 +00004192 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004193 { // acquire lock
4194 std::scoped_lock _l(mLock);
4195 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004196 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004197 needWake = enqueueInboundEventLocked(std::move(entry));
4198 } // release lock
4199
4200 if (needWake) {
4201 mLooper->wake();
4202 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004203}
4204
Prabir Pradhan5735a322022-04-11 17:23:34 +00004205InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4206 std::optional<int32_t> targetUid,
4207 InputEventInjectionSync syncMode,
4208 std::chrono::milliseconds timeout,
4209 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004210 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004211 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4212 "policyFlags=0x%08x",
4213 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4214 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004215 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004216 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217
Prabir Pradhan5735a322022-04-11 17:23:34 +00004218 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004220 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004221 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4222 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4223 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4224 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4225 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004226 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004227 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004228 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004229 }
4230
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004231 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004233 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004234 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4235 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004236 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004237 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004238 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004240 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004241 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4242 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4243 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004244 int32_t keyCode = incomingKey.getKeyCode();
4245 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004246 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004247 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004248 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004249 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004250 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4251 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4252 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004254 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4255 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004256 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004257
4258 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4259 android::base::Timer t;
4260 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4261 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4262 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4263 std::to_string(t.duration().count()).c_str());
4264 }
4265 }
4266
4267 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004268 std::unique_ptr<KeyEntry> injectedEntry =
4269 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004270 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004271 incomingKey.getDisplayId(), policyFlags, action,
4272 flags, keyCode, incomingKey.getScanCode(), metaState,
4273 incomingKey.getRepeatCount(),
4274 incomingKey.getDownTime());
4275 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004276 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 }
4278
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004279 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004280 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004281 const int32_t action = motionEvent.getAction();
4282 const bool isPointerEvent =
4283 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4284 // If a pointer event has no displayId specified, inject it to the default display.
4285 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4286 ? ADISPLAY_ID_DEFAULT
4287 : event->getDisplayId();
4288 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004289 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004290 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004291 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004292 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004293 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004294 }
4295
4296 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004297 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004298 android::base::Timer t;
4299 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4300 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4301 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4302 std::to_string(t.duration().count()).c_str());
4303 }
4304 }
4305
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004306 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4307 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4308 }
4309
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004310 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004311 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4312 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004313 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004314 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4315 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004316 displayId, policyFlags, action, actionButton,
4317 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004318 motionEvent.getButtonState(),
4319 motionEvent.getClassification(),
4320 motionEvent.getEdgeFlags(),
4321 motionEvent.getXPrecision(),
4322 motionEvent.getYPrecision(),
4323 motionEvent.getRawXCursorPosition(),
4324 motionEvent.getRawYCursorPosition(),
4325 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004326 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004327 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004328 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004329 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004330 sampleEventTimes += 1;
4331 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004332 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004333 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4334 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004335 displayId, policyFlags, action, actionButton,
4336 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004337 motionEvent.getButtonState(),
4338 motionEvent.getClassification(),
4339 motionEvent.getEdgeFlags(),
4340 motionEvent.getXPrecision(),
4341 motionEvent.getYPrecision(),
4342 motionEvent.getRawXCursorPosition(),
4343 motionEvent.getRawYCursorPosition(),
4344 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004345 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004346 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004347 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4348 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004349 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004350 }
4351 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004354 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004355 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004356 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 }
4358
Prabir Pradhan5735a322022-04-11 17:23:34 +00004359 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004360 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 injectionState->injectionIsAsync = true;
4362 }
4363
4364 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004365 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366
4367 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004368 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004369 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004370 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 }
4372
4373 mLock.unlock();
4374
4375 if (needWake) {
4376 mLooper->wake();
4377 }
4378
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004379 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004381 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004383 if (syncMode == InputEventInjectionSync::NONE) {
4384 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385 } else {
4386 for (;;) {
4387 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004388 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 break;
4390 }
4391
4392 nsecs_t remainingTimeout = endTime - now();
4393 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004394 if (DEBUG_INJECTION) {
4395 ALOGD("injectInputEvent - Timed out waiting for injection result "
4396 "to become available.");
4397 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004398 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399 break;
4400 }
4401
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004402 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 }
4404
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004405 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4406 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004408 if (DEBUG_INJECTION) {
4409 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4410 injectionState->pendingForegroundDispatches);
4411 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412 nsecs_t remainingTimeout = endTime - now();
4413 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004414 if (DEBUG_INJECTION) {
4415 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4416 "dispatches to finish.");
4417 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004418 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419 break;
4420 }
4421
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004422 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 }
4424 }
4425 }
4426
4427 injectionState->release();
4428 } // release lock
4429
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004430 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004431 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433
4434 return injectionResult;
4435}
4436
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004437std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004438 std::array<uint8_t, 32> calculatedHmac;
4439 std::unique_ptr<VerifiedInputEvent> result;
4440 switch (event.getType()) {
4441 case AINPUT_EVENT_TYPE_KEY: {
4442 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4443 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4444 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004445 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004446 break;
4447 }
4448 case AINPUT_EVENT_TYPE_MOTION: {
4449 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4450 VerifiedMotionEvent verifiedMotionEvent =
4451 verifiedMotionEventFromMotionEvent(motionEvent);
4452 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004453 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004454 break;
4455 }
4456 default: {
4457 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4458 return nullptr;
4459 }
4460 }
4461 if (calculatedHmac == INVALID_HMAC) {
4462 return nullptr;
4463 }
4464 if (calculatedHmac != event.getHmac()) {
4465 return nullptr;
4466 }
4467 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004468}
4469
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004470void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004471 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004472 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004474 if (DEBUG_INJECTION) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00004475 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004476 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004478 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 // Log the outcome since the injector did not wait for the injection result.
4480 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004481 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004482 ALOGV("Asynchronous input event injection succeeded.");
4483 break;
Prabir Pradhan5735a322022-04-11 17:23:34 +00004484 case InputEventInjectionResult::TARGET_MISMATCH:
4485 ALOGV("Asynchronous input event injection target mismatch.");
4486 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004487 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004488 ALOGW("Asynchronous input event injection failed.");
4489 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004490 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004491 ALOGW("Asynchronous input event injection timed out.");
4492 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004493 case InputEventInjectionResult::PENDING:
4494 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4495 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 }
4497 }
4498
4499 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004500 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 }
4502}
4503
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004504void InputDispatcher::transformMotionEntryForInjectionLocked(
4505 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004506 // Input injection works in the logical display coordinate space, but the input pipeline works
4507 // display space, so we need to transform the injected events accordingly.
4508 const auto it = mDisplayInfos.find(entry.displayId);
4509 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004510 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004511
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004512 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4513 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4514 const vec2 cursor =
4515 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4516 {entry.xCursorPosition, entry.yCursorPosition});
4517 entry.xCursorPosition = cursor.x;
4518 entry.yCursorPosition = cursor.y;
4519 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004520 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004521 entry.pointerCoords[i] =
4522 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4523 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004524 }
4525}
4526
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004527void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4528 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004529 if (injectionState) {
4530 injectionState->pendingForegroundDispatches += 1;
4531 }
4532}
4533
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004534void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4535 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536 if (injectionState) {
4537 injectionState->pendingForegroundDispatches -= 1;
4538
4539 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004540 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004541 }
4542 }
4543}
4544
chaviw98318de2021-05-19 16:45:23 -05004545const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004546 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004547 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004548 auto it = mWindowHandlesByDisplay.find(displayId);
4549 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004550}
4551
chaviw98318de2021-05-19 16:45:23 -05004552sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004553 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004554 if (windowHandleToken == nullptr) {
4555 return nullptr;
4556 }
4557
Arthur Hungb92218b2018-08-14 12:00:21 +08004558 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004559 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4560 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004561 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004562 return windowHandle;
4563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 }
4565 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004566 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567}
4568
chaviw98318de2021-05-19 16:45:23 -05004569sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4570 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004571 if (windowHandleToken == nullptr) {
4572 return nullptr;
4573 }
4574
chaviw98318de2021-05-19 16:45:23 -05004575 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004576 if (windowHandle->getToken() == windowHandleToken) {
4577 return windowHandle;
4578 }
4579 }
4580 return nullptr;
4581}
4582
chaviw98318de2021-05-19 16:45:23 -05004583sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4584 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004585 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004586 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4587 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004588 if (handle->getId() == windowHandle->getId() &&
4589 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004590 if (windowHandle->getInfo()->displayId != it.first) {
4591 ALOGE("Found window %s in display %" PRId32
4592 ", but it should belong to display %" PRId32,
4593 windowHandle->getName().c_str(), it.first,
4594 windowHandle->getInfo()->displayId);
4595 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004596 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004597 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598 }
4599 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004600 return nullptr;
4601}
4602
chaviw98318de2021-05-19 16:45:23 -05004603sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004604 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4605 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606}
4607
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004608bool InputDispatcher::canWindowReceiveMotionLocked(const sp<WindowInfoHandle>& window,
4609 const MotionEntry& motionEntry) const {
4610 const WindowInfo& info = *window->getInfo();
4611
4612 // Skip spy window targets that are not valid for targeted injection.
4613 if (const auto err = verifyTargetedInjection(window, motionEntry); err) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004614 return false;
4615 }
4616
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004617 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
4618 ALOGI("Not sending touch event to %s because it is paused", window->getName().c_str());
4619 return false;
4620 }
4621
4622 if (info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
4623 ALOGW("Not sending touch gesture to %s because it has config NO_INPUT_CHANNEL",
4624 window->getName().c_str());
4625 return false;
4626 }
4627
4628 sp<Connection> connection = getConnectionLocked(window->getToken());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004629 if (connection == nullptr) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004630 ALOGW("Not sending touch to %s because there's no corresponding connection",
4631 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004632 return false;
4633 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004634
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004635 if (!connection->responsive) {
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004636 ALOGW("Not sending touch to %s because it is not responsive", window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004637 return false;
4638 }
Siarhei Vishniakoud4e3f3a2022-09-27 14:31:05 -07004639
4640 // Drop events that can't be trusted due to occlusion
4641 const auto [x, y] = resolveTouchedPosition(motionEntry);
4642 TouchOcclusionInfo occlusionInfo = computeTouchOcclusionInfoLocked(window, x, y);
4643 if (!isTouchTrustedLocked(occlusionInfo)) {
4644 if (DEBUG_TOUCH_OCCLUSION) {
4645 ALOGD("Stack of obscuring windows during untrusted touch (%d, %d):", x, y);
4646 for (const auto& log : occlusionInfo.debugInfo) {
4647 ALOGD("%s", log.c_str());
4648 }
4649 }
4650 ALOGW("Dropping untrusted touch event due to %s/%d", occlusionInfo.obscuringPackage.c_str(),
4651 occlusionInfo.obscuringUid);
4652 return false;
4653 }
4654
4655 // Drop touch events if requested by input feature
4656 if (shouldDropInput(motionEntry, window)) {
4657 return false;
4658 }
4659
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004660 return true;
4661}
4662
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004663std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4664 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004665 auto connectionIt = mConnectionsByToken.find(token);
4666 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004667 return nullptr;
4668 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004669 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004670}
4671
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004672void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004673 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4674 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004675 // Remove all handles on a display if there are no windows left.
4676 mWindowHandlesByDisplay.erase(displayId);
4677 return;
4678 }
4679
4680 // Since we compare the pointer of input window handles across window updates, we need
4681 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004682 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4683 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4684 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004685 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004686 }
4687
chaviw98318de2021-05-19 16:45:23 -05004688 std::vector<sp<WindowInfoHandle>> newHandles;
4689 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004690 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004691 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004692 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004693 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004694 const bool canReceiveInput =
4695 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4696 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004697 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004698 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004699 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004700 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004701 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004702 }
4703
4704 if (info->displayId != displayId) {
4705 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4706 handle->getName().c_str(), displayId, info->displayId);
4707 continue;
4708 }
4709
Robert Carredd13602020-04-13 17:24:34 -07004710 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4711 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004712 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004713 oldHandle->updateFrom(handle);
4714 newHandles.push_back(oldHandle);
4715 } else {
4716 newHandles.push_back(handle);
4717 }
4718 }
4719
4720 // Insert or replace
4721 mWindowHandlesByDisplay[displayId] = newHandles;
4722}
4723
Arthur Hung72d8dc32020-03-28 00:48:39 +00004724void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004725 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004726 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004727 { // acquire lock
4728 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004729 for (const auto& [displayId, handles] : handlesPerDisplay) {
4730 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004731 }
4732 }
4733 // Wake up poll loop since it may need to make new input dispatching choices.
4734 mLooper->wake();
4735}
4736
Arthur Hungb92218b2018-08-14 12:00:21 +08004737/**
4738 * Called from InputManagerService, update window handle list by displayId that can receive input.
4739 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4740 * If set an empty list, remove all handles from the specific display.
4741 * For focused handle, check if need to change and send a cancel event to previous one.
4742 * For removed handle, check if need to send a cancel event if already in touch.
4743 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004744void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004745 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004746 if (DEBUG_FOCUS) {
4747 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004748 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004749 windowList += iwh->getName() + " ";
4750 }
4751 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4752 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753
Prabir Pradhand65552b2021-10-07 11:23:50 -07004754 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004755 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004756 const WindowInfo& info = *window->getInfo();
4757
4758 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004759 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004760 if (noInputWindow && window->getToken() != nullptr) {
4761 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4762 window->getName().c_str());
4763 window->releaseChannel();
4764 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004765
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004766 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004767 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4768 !info.inputConfig.test(
4769 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004770 "%s has feature SPY, but is not a trusted overlay.",
4771 window->getName().c_str());
4772
Prabir Pradhand65552b2021-10-07 11:23:50 -07004773 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004774 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4775 !info.inputConfig.test(
4776 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004777 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4778 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004779 }
4780
Arthur Hung72d8dc32020-03-28 00:48:39 +00004781 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004782 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004784 // Save the old windows' orientation by ID before it gets updated.
4785 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004786 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004787 oldWindowOrientations.emplace(handle->getId(),
4788 handle->getInfo()->transform.getOrientation());
4789 }
4790
chaviw98318de2021-05-19 16:45:23 -05004791 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004792
chaviw98318de2021-05-19 16:45:23 -05004793 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Vishnu Nair958da932020-08-21 17:12:37 -07004794 if (mLastHoverWindowHandle &&
4795 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4796 windowHandles.end()) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004797 mLastHoverWindowHandle = nullptr;
4798 }
4799
Vishnu Nairc519ff72021-01-21 08:23:08 -08004800 std::optional<FocusResolver::FocusChanges> changes =
4801 mFocusResolver.setInputWindows(displayId, windowHandles);
4802 if (changes) {
4803 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004806 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4807 mTouchStatesByDisplay.find(displayId);
4808 if (stateIt != mTouchStatesByDisplay.end()) {
4809 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004810 for (size_t i = 0; i < state.windows.size();) {
4811 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004812 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004813 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004814 ALOGD("Touched window was removed: %s in display %" PRId32,
4815 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004816 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004817 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004818 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4819 if (touchedInputChannel != nullptr) {
4820 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4821 "touched window was removed");
4822 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004823 // Since we are about to drop the touch, cancel the events for the wallpaper as
4824 // well.
4825 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004826 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4827 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004828 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4829 if (wallpaper != nullptr) {
4830 sp<Connection> wallpaperConnection =
4831 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004832 if (wallpaperConnection != nullptr) {
4833 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4834 options);
4835 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004836 }
4837 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004839 state.windows.erase(state.windows.begin() + i);
4840 } else {
4841 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 }
4843 }
arthurhungb89ccb02020-12-30 16:19:01 +08004844
arthurhung6d4bed92021-03-17 11:59:33 +08004845 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004846 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004847 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004848 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004849 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004850 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4851 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004852 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004853 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004854 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004855
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004856 // Determine if the orientation of any of the input windows have changed, and cancel all
4857 // pointer events if necessary.
4858 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4859 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4860 if (newWindowHandle != nullptr &&
4861 newWindowHandle->getInfo()->transform.getOrientation() !=
4862 oldWindowOrientations[oldWindowHandle->getId()]) {
4863 std::shared_ptr<InputChannel> inputChannel =
4864 getInputChannelLocked(newWindowHandle->getToken());
4865 if (inputChannel != nullptr) {
4866 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4867 "touched window's orientation changed");
4868 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004869 }
4870 }
4871 }
4872
Arthur Hung72d8dc32020-03-28 00:48:39 +00004873 // Release information for windows that are no longer present.
4874 // This ensures that unused input channels are released promptly.
4875 // Otherwise, they might stick around until the window handle is destroyed
4876 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004877 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004878 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004879 if (DEBUG_FOCUS) {
4880 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004881 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004882 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004883 }
chaviw291d88a2019-02-14 10:33:58 -08004884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885}
4886
4887void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004888 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004889 if (DEBUG_FOCUS) {
4890 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4891 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4892 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004893 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004894 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004895 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 } // release lock
4897
4898 // Wake up poll loop since it may need to make new input dispatching choices.
4899 mLooper->wake();
4900}
4901
Vishnu Nair599f1412021-06-21 10:39:58 -07004902void InputDispatcher::setFocusedApplicationLocked(
4903 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4904 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4905 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4906
4907 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4908 return; // This application is already focused. No need to wake up or change anything.
4909 }
4910
4911 // Set the new application handle.
4912 if (inputApplicationHandle != nullptr) {
4913 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4914 } else {
4915 mFocusedApplicationHandlesByDisplay.erase(displayId);
4916 }
4917
4918 // No matter what the old focused application was, stop waiting on it because it is
4919 // no longer focused.
4920 resetNoFocusedWindowTimeoutLocked();
4921}
4922
Tiger Huang721e26f2018-07-24 22:26:19 +08004923/**
4924 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4925 * the display not specified.
4926 *
4927 * We track any unreleased events for each window. If a window loses the ability to receive the
4928 * released event, we will send a cancel event to it. So when the focused display is changed, we
4929 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4930 * display. The display-specified events won't be affected.
4931 */
4932void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004933 if (DEBUG_FOCUS) {
4934 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4935 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004936 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004937 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004938
4939 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004940 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004941 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004942 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004943 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004944 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004945 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004946 CancelationOptions
4947 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4948 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004949 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004950 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4951 }
4952 }
4953 mFocusedDisplayId = displayId;
4954
Chris Ye3c2d6f52020-08-09 10:39:48 -07004955 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004956 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004957 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004958
Vishnu Nairad321cd2020-08-20 16:40:21 -07004959 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004960 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004961 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004962 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004963 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004964 }
4965 }
4966 }
4967
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004968 if (DEBUG_FOCUS) {
4969 logDispatchStateLocked();
4970 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004971 } // release lock
4972
4973 // Wake up poll loop since it may need to make new input dispatching choices.
4974 mLooper->wake();
4975}
4976
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004978 if (DEBUG_FOCUS) {
4979 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004981
4982 bool changed;
4983 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004984 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004985
4986 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4987 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004988 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989 }
4990
4991 if (mDispatchEnabled && !enabled) {
4992 resetAndDropEverythingLocked("dispatcher is being disabled");
4993 }
4994
4995 mDispatchEnabled = enabled;
4996 mDispatchFrozen = frozen;
4997 changed = true;
4998 } else {
4999 changed = false;
5000 }
5001
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005002 if (DEBUG_FOCUS) {
5003 logDispatchStateLocked();
5004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005005 } // release lock
5006
5007 if (changed) {
5008 // Wake up poll loop since it may need to make new input dispatching choices.
5009 mLooper->wake();
5010 }
5011}
5012
5013void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005014 if (DEBUG_FOCUS) {
5015 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
5016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005017
5018 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005019 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005020
5021 if (mInputFilterEnabled == enabled) {
5022 return;
5023 }
5024
5025 mInputFilterEnabled = enabled;
5026 resetAndDropEverythingLocked("input filter is being enabled or disabled");
5027 } // release lock
5028
5029 // Wake up poll loop since there might be work to do to drop everything.
5030 mLooper->wake();
5031}
5032
Antonio Kanteka042c022022-07-06 16:51:07 -07005033bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission,
5034 int32_t displayId) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005035 bool needWake = false;
5036 {
5037 std::scoped_lock lock(mLock);
Antonio Kantek15beb512022-06-13 22:35:41 +00005038 ALOGD_IF(DEBUG_TOUCH_MODE,
5039 "Request to change touch mode to %s (calling pid=%d, uid=%d, "
5040 "hasPermission=%s, target displayId=%d, mTouchModePerDisplay[displayId]=%s)",
5041 toString(inTouchMode), pid, uid, toString(hasPermission), displayId,
5042 mTouchModePerDisplay.count(displayId) == 0
5043 ? "not set"
5044 : std::to_string(mTouchModePerDisplay[displayId]).c_str());
5045
Antonio Kantek15beb512022-06-13 22:35:41 +00005046 auto touchModeIt = mTouchModePerDisplay.find(displayId);
5047 if (touchModeIt != mTouchModePerDisplay.end() && touchModeIt->second == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005048 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005049 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005050 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005051 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5052 !recentWindowsAreOwnedByLocked(pid, uid)) {
5053 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5054 "window nor none of the previously interacted window",
5055 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005056 return false;
5057 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005058 }
Antonio Kantek15beb512022-06-13 22:35:41 +00005059 mTouchModePerDisplay[displayId] = inTouchMode;
5060 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode,
5061 displayId);
Antonio Kantekf16f2832021-09-28 04:39:20 +00005062 needWake = enqueueInboundEventLocked(std::move(entry));
5063 } // release lock
5064
5065 if (needWake) {
5066 mLooper->wake();
5067 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005068 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005069}
5070
Antonio Kantek48710e42022-03-24 14:19:30 -07005071bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5072 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5073 if (focusedToken == nullptr) {
5074 return false;
5075 }
5076 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5077 return isWindowOwnedBy(windowHandle, pid, uid);
5078}
5079
5080bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5081 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5082 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5083 const sp<WindowInfoHandle> windowHandle =
5084 getWindowHandleLocked(connectionToken);
5085 return isWindowOwnedBy(windowHandle, pid, uid);
5086 }) != mInteractionConnectionTokens.end();
5087}
5088
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005089void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5090 if (opacity < 0 || opacity > 1) {
5091 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5092 return;
5093 }
5094
5095 std::scoped_lock lock(mLock);
5096 mMaximumObscuringOpacityForTouch = opacity;
5097}
5098
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005099std::tuple<TouchState*, TouchedWindow*, int32_t /*displayId*/>
5100InputDispatcher::findTouchStateWindowAndDisplayLocked(const sp<IBinder>& token) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00005101 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5102 for (TouchedWindow& w : state.windows) {
5103 if (w.windowHandle->getToken() == token) {
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005104 return std::make_tuple(&state, &w, displayId);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005105 }
5106 }
5107 }
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005108 return std::make_tuple(nullptr, nullptr, ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005109}
5110
arthurhungb89ccb02020-12-30 16:19:01 +08005111bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5112 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005113 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005114 if (DEBUG_FOCUS) {
5115 ALOGD("Trivial transfer to same window.");
5116 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005117 return true;
5118 }
5119
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005121 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122
Arthur Hungabbb9d82021-09-01 14:52:30 +00005123 // Find the target touch state and touched window by fromToken.
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005124 auto [state, touchedWindow, displayId] = findTouchStateWindowAndDisplayLocked(fromToken);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005125 if (state == nullptr || touchedWindow == nullptr) {
5126 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127 return false;
5128 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005129
Arthur Hungabbb9d82021-09-01 14:52:30 +00005130 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5131 if (toWindowHandle == nullptr) {
5132 ALOGW("Cannot transfer focus because to window not found.");
5133 return false;
5134 }
5135
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005136 if (DEBUG_FOCUS) {
5137 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005138 touchedWindow->windowHandle->getName().c_str(),
5139 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 }
5141
Arthur Hungabbb9d82021-09-01 14:52:30 +00005142 // Erase old window.
5143 int32_t oldTargetFlags = touchedWindow->targetFlags;
5144 BitSet32 pointerIds = touchedWindow->pointerIds;
5145 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146
Arthur Hungabbb9d82021-09-01 14:52:30 +00005147 // Add new window.
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005148 nsecs_t downTimeInTarget = now();
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005149 int32_t newTargetFlags =
5150 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5151 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5152 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5153 }
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005154 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds, downTimeInTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155
Arthur Hungabbb9d82021-09-01 14:52:30 +00005156 // Store the dragging window.
5157 if (isDragDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005158 if (pointerIds.count() != 1) {
5159 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5160 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005161 return false;
5162 }
Arthur Hungb75c2aa2022-07-15 09:35:36 +00005163 // Track the pointer id for drag window and generate the drag state.
5164 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005165 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 }
5167
Arthur Hungabbb9d82021-09-01 14:52:30 +00005168 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005169 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5170 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005171 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005172 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005173 CancelationOptions
5174 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5175 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00005177 synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178 }
5179
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005180 if (DEBUG_FOCUS) {
5181 logDispatchStateLocked();
5182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 } // release lock
5184
5185 // Wake up poll loop since it may need to make new input dispatching choices.
5186 mLooper->wake();
5187 return true;
5188}
5189
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005190/**
5191 * Get the touched foreground window on the given display.
5192 * Return null if there are no windows touched on that display, or if more than one foreground
5193 * window is being touched.
5194 */
5195sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5196 auto stateIt = mTouchStatesByDisplay.find(displayId);
5197 if (stateIt == mTouchStatesByDisplay.end()) {
5198 ALOGI("No touch state on display %" PRId32, displayId);
5199 return nullptr;
5200 }
5201
5202 const TouchState& state = stateIt->second;
5203 sp<WindowInfoHandle> touchedForegroundWindow;
5204 // If multiple foreground windows are touched, return nullptr
5205 for (const TouchedWindow& window : state.windows) {
5206 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5207 if (touchedForegroundWindow != nullptr) {
5208 ALOGI("Two or more foreground windows: %s and %s",
5209 touchedForegroundWindow->getName().c_str(),
5210 window.windowHandle->getName().c_str());
5211 return nullptr;
5212 }
5213 touchedForegroundWindow = window.windowHandle;
5214 }
5215 }
5216 return touchedForegroundWindow;
5217}
5218
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005219// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005220bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005221 sp<IBinder> fromToken;
5222 { // acquire lock
5223 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005224 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005225 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005226 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5227 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005228 return false;
5229 }
5230
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005231 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5232 if (from == nullptr) {
5233 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5234 return false;
5235 }
5236
5237 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005238 } // release lock
5239
5240 return transferTouchFocus(fromToken, destChannelToken);
5241}
5242
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005244 if (DEBUG_FOCUS) {
5245 ALOGD("Resetting and dropping all events (%s).", reason);
5246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247
5248 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5249 synthesizeCancelationEventsForAllConnectionsLocked(options);
5250
5251 resetKeyRepeatLocked();
5252 releasePendingEventLocked();
5253 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005254 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005256 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005257 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005259 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260}
5261
5262void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005263 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264 dumpDispatchStateLocked(dump);
5265
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005266 std::istringstream stream(dump);
5267 std::string line;
5268
5269 while (std::getline(stream, line, '\n')) {
5270 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271 }
5272}
5273
Prabir Pradhan99987712020-11-10 18:43:05 -08005274std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5275 std::string dump;
5276
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005277 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5278 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005279
5280 std::string windowName = "None";
5281 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005282 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005283 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5284 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5285 : "token has capture without window";
5286 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005287 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005288
5289 return dump;
5290}
5291
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005292void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005293 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5294 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5295 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005296 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297
Tiger Huang721e26f2018-07-24 22:26:19 +08005298 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5299 dump += StringPrintf(INDENT "FocusedApplications:\n");
5300 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5301 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005302 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005303 const std::chrono::duration timeout =
5304 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005305 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005306 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005307 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005308 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005310 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005312
Vishnu Nairc519ff72021-01-21 08:23:08 -08005313 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005314 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005316 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005317 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005318 for (const auto& [displayId, state] : mTouchStatesByDisplay) {
Siarhei Vishniakou6e1e9872022-11-08 17:51:35 -08005319 std::string touchStateDump = addLinePrefix(state.dump(), INDENT2);
5320 dump += INDENT2 + std::to_string(displayId) + " : " + touchStateDump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321 }
5322 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005323 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 }
5325
arthurhung6d4bed92021-03-17 11:59:33 +08005326 if (mDragState) {
5327 dump += StringPrintf(INDENT "DragState:\n");
5328 mDragState->dump(dump, INDENT2);
5329 }
5330
Arthur Hungb92218b2018-08-14 12:00:21 +08005331 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005332 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5333 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5334 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5335 const auto& displayInfo = it->second;
5336 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5337 displayInfo.logicalHeight);
5338 displayInfo.transform.dump(dump, "transform", INDENT4);
5339 } else {
5340 dump += INDENT2 "No DisplayInfo found!\n";
5341 }
5342
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005343 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005344 dump += INDENT2 "Windows:\n";
5345 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005346 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5347 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005349 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005350 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005351 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005352 "applicationInfo.name=%s, "
5353 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005354 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005355 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005356 windowInfo->displayId,
5357 windowInfo->inputConfig.string().c_str(),
5358 windowInfo->alpha, windowInfo->frameLeft,
5359 windowInfo->frameTop, windowInfo->frameRight,
5360 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005361 windowInfo->applicationInfo.name.c_str(),
5362 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005363 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005364 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005365 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005366 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005367 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005368 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005369 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005370 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005371 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005372 }
5373 } else {
5374 dump += INDENT2 "Windows: <none>\n";
5375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376 }
5377 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005378 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005379 }
5380
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005381 if (!mGlobalMonitorsByDisplay.empty()) {
5382 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5383 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005384 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005386 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005387 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005388 }
5389
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005390 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391
5392 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005393 if (!mRecentQueue.empty()) {
5394 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005395 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005396 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005397 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005398 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399 }
5400 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005401 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005402 }
5403
5404 // Dump event currently being dispatched.
5405 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005406 dump += INDENT "PendingEvent:\n";
5407 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005408 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005409 dump += StringPrintf(", age=%" PRId64 "ms\n",
5410 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005412 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413 }
5414
5415 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005416 if (!mInboundQueue.empty()) {
5417 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005418 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005419 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005420 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005421 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422 }
5423 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005424 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425 }
5426
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005427 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005428 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005429 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5430 const KeyReplacement& replacement = pair.first;
5431 int32_t newKeyCode = pair.second;
5432 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005433 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005434 }
5435 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005436 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005437 }
5438
Prabir Pradhancef936d2021-07-21 16:17:52 +00005439 if (!mCommandQueue.empty()) {
5440 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5441 } else {
5442 dump += INDENT "CommandQueue: <empty>\n";
5443 }
5444
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005445 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005446 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005447 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005448 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005449 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005450 connection->inputChannel->getFd().get(),
5451 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005452 connection->getWindowName().c_str(),
5453 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005454 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005456 if (!connection->outboundQueue.empty()) {
5457 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5458 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005459 dump += dumpQueue(connection->outboundQueue, currentTime);
5460
Michael Wrightd02c5b62014-02-10 15:10:22 -08005461 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005462 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 }
5464
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005465 if (!connection->waitQueue.empty()) {
5466 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5467 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005468 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005470 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005471 }
5472 }
5473 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005474 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005475 }
5476
5477 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005478 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5479 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005480 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005481 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 }
5483
Antonio Kantek15beb512022-06-13 22:35:41 +00005484 if (!mTouchModePerDisplay.empty()) {
5485 dump += INDENT "TouchModePerDisplay:\n";
5486 for (const auto& [displayId, touchMode] : mTouchModePerDisplay) {
5487 dump += StringPrintf(INDENT2 "Display: %" PRId32 " TouchMode: %s\n", displayId,
5488 std::to_string(touchMode).c_str());
5489 }
5490 } else {
5491 dump += INDENT "TouchModePerDisplay: <none>\n";
5492 }
5493
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005494 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005495 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5496 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5497 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005498 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005499 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005500}
5501
Michael Wright3dd60e22019-03-27 22:06:44 +00005502void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5503 const size_t numMonitors = monitors.size();
5504 for (size_t i = 0; i < numMonitors; i++) {
5505 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005506 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005507 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5508 dump += "\n";
5509 }
5510}
5511
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005512class LooperEventCallback : public LooperCallback {
5513public:
5514 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5515 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5516
5517private:
5518 std::function<int(int events)> mCallback;
5519};
5520
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005521Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005522 if (DEBUG_CHANNEL_CREATION) {
5523 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005526 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005527 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005528 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005529
5530 if (result) {
5531 return base::Error(result) << "Failed to open input channel pair with name " << name;
5532 }
5533
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005535 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005536 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005537 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005538 sp<Connection> connection =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005539 sp<Connection>::make(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005540
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005541 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5542 ALOGE("Created a new connection, but the token %p is already known", token.get());
5543 }
5544 mConnectionsByToken.emplace(token, connection);
5545
5546 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5547 this, std::placeholders::_1, token);
5548
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005549 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5550 nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551 } // release lock
5552
5553 // Wake the looper because some connections have changed.
5554 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005555 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556}
5557
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005558Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005559 const std::string& name,
5560 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005561 std::shared_ptr<InputChannel> serverChannel;
5562 std::unique_ptr<InputChannel> clientChannel;
5563 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5564 if (result) {
5565 return base::Error(result) << "Failed to open input channel pair with name " << name;
5566 }
5567
Michael Wright3dd60e22019-03-27 22:06:44 +00005568 { // acquire lock
5569 std::scoped_lock _l(mLock);
5570
5571 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005572 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5573 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005574 }
5575
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005576 sp<Connection> connection =
5577 sp<Connection>::make(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005578 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005579 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005580
5581 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5582 ALOGE("Created a new connection, but the token %p is already known", token.get());
5583 }
5584 mConnectionsByToken.emplace(token, connection);
5585 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5586 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005587
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005588 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005589
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005590 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
5591 nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005592 }
Garfield Tan15601662020-09-22 15:32:38 -07005593
Michael Wright3dd60e22019-03-27 22:06:44 +00005594 // Wake the looper because some connections have changed.
5595 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005596 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005597}
5598
Garfield Tan15601662020-09-22 15:32:38 -07005599status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005601 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602
Garfield Tan15601662020-09-22 15:32:38 -07005603 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005604 if (status) {
5605 return status;
5606 }
5607 } // release lock
5608
5609 // Wake the poll loop because removing the connection may have changed the current
5610 // synchronization state.
5611 mLooper->wake();
5612 return OK;
5613}
5614
Garfield Tan15601662020-09-22 15:32:38 -07005615status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5616 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005617 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005618 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005619 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620 return BAD_VALUE;
5621 }
5622
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005623 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005624
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005626 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627 }
5628
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005629 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630
5631 nsecs_t currentTime = now();
5632 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5633
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005634 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635 return OK;
5636}
5637
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005638void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005639 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5640 auto& [displayId, monitors] = *it;
5641 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5642 return monitor.inputChannel->getConnectionToken() == connectionToken;
5643 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005644
Michael Wright3dd60e22019-03-27 22:06:44 +00005645 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005646 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005647 } else {
5648 ++it;
5649 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650 }
5651}
5652
Michael Wright3dd60e22019-03-27 22:06:44 +00005653status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005654 std::scoped_lock _l(mLock);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005655 return pilferPointersLocked(token);
5656}
Michael Wright3dd60e22019-03-27 22:06:44 +00005657
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00005658status_t InputDispatcher::pilferPointersLocked(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005659 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5660 if (!requestingChannel) {
5661 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5662 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005663 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005664
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005665 auto [statePtr, windowPtr, displayId] = findTouchStateWindowAndDisplayLocked(token);
Siarhei Vishniakou3ad385b2022-11-04 10:09:53 -07005666 if (statePtr == nullptr || windowPtr == nullptr || windowPtr->pointerIds.isEmpty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005667 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5668 " Ignoring.");
5669 return BAD_VALUE;
5670 }
5671
5672 TouchState& state = *statePtr;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005673 TouchedWindow& window = *windowPtr;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005674 // Send cancel events to all the input channels we're stealing from.
5675 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5676 "input channel stole pointer stream");
5677 options.deviceId = state.deviceId;
Siarhei Vishniakou40b8fbd2022-11-04 10:50:26 -07005678 options.displayId = displayId;
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005679 options.pointerIds = window.pointerIds;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005680 std::string canceledWindows;
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005681 for (const TouchedWindow& w : state.windows) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005682 const std::shared_ptr<InputChannel> channel =
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005683 getInputChannelLocked(w.windowHandle->getToken());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005684 if (channel != nullptr && channel->getConnectionToken() != token) {
5685 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5686 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5687 canceledWindows += channel->getName();
5688 }
5689 }
5690 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5691 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5692 canceledWindows.c_str());
5693
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005694 // Prevent the gesture from being sent to any other windows.
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00005695 // This only blocks relevant pointers to be sent to other windows
5696 window.isPilferingPointers = true;
5697
Siarhei Vishniakou64a98532022-10-25 15:20:24 -07005698 state.cancelPointersForWindowsExcept(window.pointerIds, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005699 return OK;
5700}
5701
Prabir Pradhan99987712020-11-10 18:43:05 -08005702void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5703 { // acquire lock
5704 std::scoped_lock _l(mLock);
5705 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005706 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005707 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5708 windowHandle != nullptr ? windowHandle->getName().c_str()
5709 : "token without window");
5710 }
5711
Vishnu Nairc519ff72021-01-21 08:23:08 -08005712 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005713 if (focusedToken != windowToken) {
5714 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5715 enabled ? "enable" : "disable");
5716 return;
5717 }
5718
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005719 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005720 ALOGW("Ignoring request to %s Pointer Capture: "
5721 "window has %s requested pointer capture.",
5722 enabled ? "enable" : "disable", enabled ? "already" : "not");
5723 return;
5724 }
5725
Christine Franksb768bb42021-11-29 12:11:31 -08005726 if (enabled) {
5727 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5728 mIneligibleDisplaysForPointerCapture.end(),
5729 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5730 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5731 return;
5732 }
5733 }
5734
Prabir Pradhan99987712020-11-10 18:43:05 -08005735 setPointerCaptureLocked(enabled);
5736 } // release lock
5737
5738 // Wake the thread to process command entries.
5739 mLooper->wake();
5740}
5741
Christine Franksb768bb42021-11-29 12:11:31 -08005742void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5743 { // acquire lock
5744 std::scoped_lock _l(mLock);
5745 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5746 if (!isEligible) {
5747 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5748 }
5749 } // release lock
5750}
5751
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005752std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5753 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005754 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005755 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005756 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005757 }
5758 }
5759 }
5760 return std::nullopt;
5761}
5762
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005763sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005764 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005765 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005766 }
5767
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005768 for (const auto& [token, connection] : mConnectionsByToken) {
5769 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005770 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771 }
5772 }
Robert Carr4e670e52018-08-15 13:26:12 -07005773
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005774 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775}
5776
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005777std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5778 sp<Connection> connection = getConnectionLocked(connectionToken);
5779 if (connection == nullptr) {
5780 return "<nullptr>";
5781 }
5782 return connection->getInputChannelName();
5783}
5784
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005785void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005786 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005787 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005788}
5789
Prabir Pradhancef936d2021-07-21 16:17:52 +00005790void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5791 const sp<Connection>& connection, uint32_t seq,
5792 bool handled, nsecs_t consumeTime) {
5793 // Handle post-event policy actions.
5794 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5795 if (dispatchEntryIt == connection->waitQueue.end()) {
5796 return;
5797 }
5798 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5799 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5800 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5801 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5802 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5803 }
5804 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5805 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5806 connection->inputChannel->getConnectionToken(),
5807 dispatchEntry->deliveryTime, consumeTime, finishTime);
5808 }
5809
5810 bool restartEvent;
5811 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5812 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5813 restartEvent =
5814 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5815 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5816 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5817 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5818 handled);
5819 } else {
5820 restartEvent = false;
5821 }
5822
5823 // Dequeue the event and start the next cycle.
5824 // Because the lock might have been released, it is possible that the
5825 // contents of the wait queue to have been drained, so we need to double-check
5826 // a few things.
5827 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5828 if (dispatchEntryIt != connection->waitQueue.end()) {
5829 dispatchEntry = *dispatchEntryIt;
5830 connection->waitQueue.erase(dispatchEntryIt);
5831 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5832 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5833 if (!connection->responsive) {
5834 connection->responsive = isConnectionResponsive(*connection);
5835 if (connection->responsive) {
5836 // The connection was unresponsive, and now it's responsive.
5837 processConnectionResponsiveLocked(*connection);
5838 }
5839 }
5840 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005841 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005842 connection->outboundQueue.push_front(dispatchEntry);
5843 traceOutboundQueueLength(*connection);
5844 } else {
5845 releaseDispatchEntry(dispatchEntry);
5846 }
5847 }
5848
5849 // Start the next dispatch cycle for this connection.
5850 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005851}
5852
Prabir Pradhancef936d2021-07-21 16:17:52 +00005853void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5854 const sp<IBinder>& newToken) {
5855 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5856 scoped_unlock unlock(mLock);
5857 mPolicy->notifyFocusChanged(oldToken, newToken);
5858 };
5859 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860}
5861
Prabir Pradhancef936d2021-07-21 16:17:52 +00005862void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5863 auto command = [this, token, x, y]() REQUIRES(mLock) {
5864 scoped_unlock unlock(mLock);
5865 mPolicy->notifyDropWindow(token, x, y);
5866 };
5867 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005868}
5869
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005870void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5871 if (connection == nullptr) {
5872 LOG_ALWAYS_FATAL("Caller must check for nullness");
5873 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005874 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5875 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005876 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005877 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005878 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005879 return;
5880 }
5881 /**
5882 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5883 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5884 * has changed. This could cause newer entries to time out before the already dispatched
5885 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5886 * processes the events linearly. So providing information about the oldest entry seems to be
5887 * most useful.
5888 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005889 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005890 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5891 std::string reason =
5892 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005893 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005894 ns2ms(currentWait),
5895 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005896 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005897 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005898
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005899 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5900
5901 // Stop waking up for events on this connection, it is already unresponsive
5902 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005903}
5904
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005905void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5906 std::string reason =
5907 StringPrintf("%s does not have a focused window", application->getName().c_str());
5908 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005909
Prabir Pradhancef936d2021-07-21 16:17:52 +00005910 auto command = [this, application = std::move(application)]() REQUIRES(mLock) {
5911 scoped_unlock unlock(mLock);
5912 mPolicy->notifyNoFocusedWindowAnr(application);
5913 };
5914 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005915}
5916
chaviw98318de2021-05-19 16:45:23 -05005917void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005918 const std::string& reason) {
5919 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5920 updateLastAnrStateLocked(windowLabel, reason);
5921}
5922
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005923void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5924 const std::string& reason) {
5925 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005926 updateLastAnrStateLocked(windowLabel, reason);
5927}
5928
5929void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5930 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005932 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933 struct tm tm;
5934 localtime_r(&t, &tm);
5935 char timestr[64];
5936 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005937 mLastAnrState.clear();
5938 mLastAnrState += INDENT "ANR:\n";
5939 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005940 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5941 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005942 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943}
5944
Prabir Pradhancef936d2021-07-21 16:17:52 +00005945void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5946 KeyEntry& entry) {
5947 const KeyEvent event = createKeyEvent(entry);
5948 nsecs_t delay = 0;
5949 { // release lock
5950 scoped_unlock unlock(mLock);
5951 android::base::Timer t;
5952 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5953 entry.policyFlags);
5954 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5955 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5956 std::to_string(t.duration().count()).c_str());
5957 }
5958 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005959
5960 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005961 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005962 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005963 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005965 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5966 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005968}
5969
Prabir Pradhancef936d2021-07-21 16:17:52 +00005970void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005971 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005972 std::string reason) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005973 auto command = [this, token, pid, reason = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005974 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005975 mPolicy->notifyWindowUnresponsive(token, pid, reason);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005976 };
5977 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005978}
5979
Prabir Pradhanedd96402022-02-15 01:46:16 -08005980void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5981 std::optional<int32_t> pid) {
5982 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005983 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005984 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005985 };
5986 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005987}
5988
5989/**
5990 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5991 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5992 * command entry to the command queue.
5993 */
5994void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5995 std::string reason) {
5996 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005997 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005998 if (connection.monitor) {
5999 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6000 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08006001 pid = findMonitorPidByTokenLocked(connectionToken);
6002 } else {
6003 // The connection is a window
6004 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
6005 reason.c_str());
6006 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6007 if (handle != nullptr) {
6008 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006009 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006010 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006011 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006012}
6013
6014/**
6015 * Tell the policy that a connection has become responsive so that it can stop ANR.
6016 */
6017void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
6018 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08006019 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006020 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08006021 pid = findMonitorPidByTokenLocked(connectionToken);
6022 } else {
6023 // The connection is a window
6024 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
6025 if (handle != nullptr) {
6026 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006027 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006028 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006029 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006030}
6031
Prabir Pradhancef936d2021-07-21 16:17:52 +00006032bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006033 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006034 KeyEntry& keyEntry, bool handled) {
6035 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006036 if (!handled) {
6037 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006038 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006039 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006040 return false;
6041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006042
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006043 // Get the fallback key state.
6044 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006045 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006046 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006047 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006048 connection->inputState.removeFallbackKey(originalKeyCode);
6049 }
6050
6051 if (handled || !dispatchEntry->hasForegroundTarget()) {
6052 // If the application handles the original key for which we previously
6053 // generated a fallback or if the window is not a foreground window,
6054 // then cancel the associated fallback key, if any.
6055 if (fallbackKeyCode != -1) {
6056 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006057 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6058 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6059 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6060 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6061 keyEntry.policyFlags);
6062 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006063 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006064 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006065
6066 mLock.unlock();
6067
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006068 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006069 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006070
6071 mLock.lock();
6072
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006073 // Cancel the fallback key.
6074 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006075 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006076 "application handled the original non-fallback key "
6077 "or is no longer a foreground target, "
6078 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079 options.keyCode = fallbackKeyCode;
6080 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006081 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006082 connection->inputState.removeFallbackKey(originalKeyCode);
6083 }
6084 } else {
6085 // If the application did not handle a non-fallback key, first check
6086 // that we are in a good state to perform unhandled key event processing
6087 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006088 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006089 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006090 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6091 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6092 "since this is not an initial down. "
6093 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6094 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6095 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006096 return false;
6097 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006098
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006099 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006100 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6101 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6102 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6103 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6104 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006105 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006106
6107 mLock.unlock();
6108
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006109 bool fallback =
6110 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006111 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006112
6113 mLock.lock();
6114
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006115 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006116 connection->inputState.removeFallbackKey(originalKeyCode);
6117 return false;
6118 }
6119
6120 // Latch the fallback keycode for this key on an initial down.
6121 // The fallback keycode cannot change at any other point in the lifecycle.
6122 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006123 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006124 fallbackKeyCode = event.getKeyCode();
6125 } else {
6126 fallbackKeyCode = AKEYCODE_UNKNOWN;
6127 }
6128 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6129 }
6130
6131 ALOG_ASSERT(fallbackKeyCode != -1);
6132
6133 // Cancel the fallback key if the policy decides not to send it anymore.
6134 // We will continue to dispatch the key to the policy but we will no
6135 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006136 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6137 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006138 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6139 if (fallback) {
6140 ALOGD("Unhandled key event: Policy requested to send key %d"
6141 "as a fallback for %d, but on the DOWN it had requested "
6142 "to send %d instead. Fallback canceled.",
6143 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6144 } else {
6145 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6146 "but on the DOWN it had requested to send %d. "
6147 "Fallback canceled.",
6148 originalKeyCode, fallbackKeyCode);
6149 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006150 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006151
6152 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6153 "canceling fallback, policy no longer desires it");
6154 options.keyCode = fallbackKeyCode;
6155 synthesizeCancelationEventsForConnectionLocked(connection, options);
6156
6157 fallback = false;
6158 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006159 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006160 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006161 }
6162 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006163
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006164 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6165 {
6166 std::string msg;
6167 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6168 connection->inputState.getFallbackKeys();
6169 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6170 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6171 }
6172 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6173 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006174 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006175 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006176
6177 if (fallback) {
6178 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006179 keyEntry.eventTime = event.getEventTime();
6180 keyEntry.deviceId = event.getDeviceId();
6181 keyEntry.source = event.getSource();
6182 keyEntry.displayId = event.getDisplayId();
6183 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6184 keyEntry.keyCode = fallbackKeyCode;
6185 keyEntry.scanCode = event.getScanCode();
6186 keyEntry.metaState = event.getMetaState();
6187 keyEntry.repeatCount = event.getRepeatCount();
6188 keyEntry.downTime = event.getDownTime();
6189 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006190
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006191 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6192 ALOGD("Unhandled key event: Dispatching fallback key. "
6193 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6194 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6195 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006196 return true; // restart the event
6197 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006198 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6199 ALOGD("Unhandled key event: No fallback key.");
6200 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006201
6202 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006203 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006204 }
6205 }
6206 return false;
6207}
6208
Prabir Pradhancef936d2021-07-21 16:17:52 +00006209bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006210 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006211 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006212 return false;
6213}
6214
Michael Wrightd02c5b62014-02-10 15:10:22 -08006215void InputDispatcher::traceInboundQueueLengthLocked() {
6216 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006217 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218 }
6219}
6220
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006221void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006222 if (ATRACE_ENABLED()) {
6223 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006224 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6225 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226 }
6227}
6228
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006229void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230 if (ATRACE_ENABLED()) {
6231 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006232 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6233 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006234 }
6235}
6236
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006237void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006238 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006239
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006240 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006241 dumpDispatchStateLocked(dump);
6242
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006243 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006244 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006245 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006246 }
6247}
6248
6249void InputDispatcher::monitor() {
6250 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006251 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006252 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006253 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006254}
6255
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006256/**
6257 * Wake up the dispatcher and wait until it processes all events and commands.
6258 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6259 * this method can be safely called from any thread, as long as you've ensured that
6260 * the work you are interested in completing has already been queued.
6261 */
6262bool InputDispatcher::waitForIdle() {
6263 /**
6264 * Timeout should represent the longest possible time that a device might spend processing
6265 * events and commands.
6266 */
6267 constexpr std::chrono::duration TIMEOUT = 100ms;
6268 std::unique_lock lock(mLock);
6269 mLooper->wake();
6270 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6271 return result == std::cv_status::no_timeout;
6272}
6273
Vishnu Naire798b472020-07-23 13:52:21 -07006274/**
6275 * Sets focus to the window identified by the token. This must be called
6276 * after updating any input window handles.
6277 *
6278 * Params:
6279 * request.token - input channel token used to identify the window that should gain focus.
6280 * request.focusedToken - the token that the caller expects currently to be focused. If the
6281 * specified token does not match the currently focused window, this request will be dropped.
6282 * If the specified focused token matches the currently focused window, the call will succeed.
6283 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6284 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6285 * when requesting the focus change. This determines which request gets
6286 * precedence if there is a focus change request from another source such as pointer down.
6287 */
Vishnu Nair958da932020-08-21 17:12:37 -07006288void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6289 { // acquire lock
6290 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006291 std::optional<FocusResolver::FocusChanges> changes =
6292 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6293 if (changes) {
6294 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006295 }
6296 } // release lock
6297 // Wake up poll loop since it may need to make new input dispatching choices.
6298 mLooper->wake();
6299}
6300
Vishnu Nairc519ff72021-01-21 08:23:08 -08006301void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6302 if (changes.oldFocus) {
6303 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006304 if (focusedInputChannel) {
6305 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6306 "focus left window");
6307 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006308 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006309 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006310 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006311 if (changes.newFocus) {
6312 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006313 }
6314
Prabir Pradhan99987712020-11-10 18:43:05 -08006315 // If a window has pointer capture, then it must have focus. We need to ensure that this
6316 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6317 // If the window loses focus before it loses pointer capture, then the window can be in a state
6318 // where it has pointer capture but not focus, violating the contract. Therefore we must
6319 // dispatch the pointer capture event before the focus event. Since focus events are added to
6320 // the front of the queue (above), we add the pointer capture event to the front of the queue
6321 // after the focus events are added. This ensures the pointer capture event ends up at the
6322 // front.
6323 disablePointerCaptureForcedLocked();
6324
Vishnu Nairc519ff72021-01-21 08:23:08 -08006325 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006326 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006327 }
6328}
Vishnu Nair958da932020-08-21 17:12:37 -07006329
Prabir Pradhan99987712020-11-10 18:43:05 -08006330void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006331 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006332 return;
6333 }
6334
6335 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6336
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006337 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006338 setPointerCaptureLocked(false);
6339 }
6340
6341 if (!mWindowTokenWithPointerCapture) {
6342 // No need to send capture changes because no window has capture.
6343 return;
6344 }
6345
6346 if (mPendingEvent != nullptr) {
6347 // Move the pending event to the front of the queue. This will give the chance
6348 // for the pending event to be dropped if it is a captured event.
6349 mInboundQueue.push_front(mPendingEvent);
6350 mPendingEvent = nullptr;
6351 }
6352
6353 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006354 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006355 mInboundQueue.push_front(std::move(entry));
6356}
6357
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006358void InputDispatcher::setPointerCaptureLocked(bool enable) {
6359 mCurrentPointerCaptureRequest.enable = enable;
6360 mCurrentPointerCaptureRequest.seq++;
6361 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006362 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006363 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006364 };
6365 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006366}
6367
Vishnu Nair599f1412021-06-21 10:39:58 -07006368void InputDispatcher::displayRemoved(int32_t displayId) {
6369 { // acquire lock
6370 std::scoped_lock _l(mLock);
6371 // Set an empty list to remove all handles from the specific display.
6372 setInputWindowsLocked(/* window handles */ {}, displayId);
6373 setFocusedApplicationLocked(displayId, nullptr);
6374 // Call focus resolver to clean up stale requests. This must be called after input windows
6375 // have been removed for the removed display.
6376 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006377 // Reset pointer capture eligibility, regardless of previous state.
6378 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Antonio Kantek15beb512022-06-13 22:35:41 +00006379 // Remove the associated touch mode state.
6380 mTouchModePerDisplay.erase(displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006381 } // release lock
6382
6383 // Wake up poll loop since it may need to make new input dispatching choices.
6384 mLooper->wake();
6385}
6386
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006387void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6388 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006389 // The listener sends the windows as a flattened array. Separate the windows by display for
6390 // more convenient parsing.
6391 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006392 for (const auto& info : windowInfos) {
6393 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006394 handlesPerDisplay[info.displayId].push_back(sp<WindowInfoHandle>::make(info));
chaviw15fab6f2021-06-07 14:15:52 -05006395 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006396
6397 { // acquire lock
6398 std::scoped_lock _l(mLock);
Prabir Pradhan814fe082022-07-22 20:22:18 +00006399
6400 // Ensure that we have an entry created for all existing displays so that if a displayId has
6401 // no windows, we can tell that the windows were removed from the display.
6402 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6403 handlesPerDisplay[displayId];
6404 }
6405
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006406 mDisplayInfos.clear();
6407 for (const auto& displayInfo : displayInfos) {
6408 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6409 }
6410
6411 for (const auto& [displayId, handles] : handlesPerDisplay) {
6412 setInputWindowsLocked(handles, displayId);
6413 }
6414 }
6415 // Wake up poll loop since it may need to make new input dispatching choices.
6416 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006417}
6418
Vishnu Nair062a8672021-09-03 16:07:44 -07006419bool InputDispatcher::shouldDropInput(
6420 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006421 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6422 (windowHandle->getInfo()->inputConfig.test(
6423 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006424 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006425 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6426 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006427 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006428 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006429 windowHandle->getInfo()->displayId);
6430 return true;
6431 }
6432 return false;
6433}
6434
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006435void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6436 const std::vector<gui::WindowInfo>& windowInfos,
6437 const std::vector<DisplayInfo>& displayInfos) {
6438 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6439}
6440
Arthur Hungdfd528e2021-12-08 13:23:04 +00006441void InputDispatcher::cancelCurrentTouch() {
6442 {
6443 std::scoped_lock _l(mLock);
6444 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6445 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6446 "cancel current touch");
6447 synthesizeCancelationEventsForAllConnectionsLocked(options);
6448
6449 mTouchStatesByDisplay.clear();
6450 mLastHoverWindowHandle.clear();
6451 }
6452 // Wake up poll loop since there might be work to do.
6453 mLooper->wake();
6454}
6455
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006456void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6457 std::scoped_lock _l(mLock);
6458 mMonitorDispatchingTimeout = timeout;
6459}
6460
Garfield Tane84e6f92019-08-29 17:28:41 -07006461} // namespace android::inputdispatcher