blob: 9b6289443378a73d5d327c2136b9f8a9bca70a53 [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>
chaviw15fab6f2021-06-07 14:15:52 -050028#include <gui/SurfaceComposerClient.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080029#include <input/InputDevice.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070030#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010031#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070032#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
Michael Wright44753b12020-07-08 13:48:11 +010034#include <cerrno>
35#include <cinttypes>
36#include <climits>
37#include <cstddef>
38#include <ctime>
39#include <queue>
40#include <sstream>
41
42#include "Connection.h"
Arthur Hung1a1007b2022-05-11 07:15:01 +000043#include "DebugConfig.h"
Chris Yef59a2f42020-10-16 12:55:26 -070044#include "InputDispatcher.h"
Michael Wright44753b12020-07-08 13:48:11 +010045
Michael Wrightd02c5b62014-02-10 15:10:22 -080046#define INDENT " "
47#define INDENT2 " "
48#define INDENT3 " "
49#define INDENT4 " "
50
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080051using android::base::HwTimeoutMultiplier;
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +000052using android::base::Result;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080053using android::base::StringPrintf;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -070054using android::gui::DisplayInfo;
chaviw98318de2021-05-19 16:45:23 -050055using android::gui::FocusRequest;
56using android::gui::TouchOcclusionMode;
57using android::gui::WindowInfo;
58using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080059using android::os::BlockUntrustedTouchesMode;
Siarhei Vishniakou2508b872020-12-03 16:33:53 -100060using android::os::IInputConstants;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080061using android::os::InputEventInjectionResult;
62using android::os::InputEventInjectionSync;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080063
Garfield Tane84e6f92019-08-29 17:28:41 -070064namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
Prabir Pradhancef936d2021-07-21 16:17:52 +000066namespace {
Prabir Pradhancef936d2021-07-21 16:17:52 +000067// Temporarily releases a held mutex for the lifetime of the instance.
68// Named to match std::scoped_lock
69class scoped_unlock {
70public:
71 explicit scoped_unlock(std::mutex& mutex) : mMutex(mutex) { mMutex.unlock(); }
72 ~scoped_unlock() { mMutex.lock(); }
73
74private:
75 std::mutex& mMutex;
76};
77
Michael Wrightd02c5b62014-02-10 15:10:22 -080078// Default input dispatching timeout if there is no focused application or paused window
79// from which to determine an appropriate dispatching timeout.
Peter Collingbourneb04b9b82021-02-08 12:09:47 -080080const std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT = std::chrono::milliseconds(
81 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
82 HwTimeoutMultiplier());
Michael Wrightd02c5b62014-02-10 15:10:22 -080083
84// Amount of time to allow for all pending events to be processed when an app switch
85// key is on the way. This is used to preempt input dispatch and drop input events
86// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000087constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080089const std::chrono::duration STALE_EVENT_TIMEOUT = std::chrono::seconds(10) * HwTimeoutMultiplier();
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
Michael Wrightd02c5b62014-02-10 15:10:22 -080091// 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 +000092constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
93
94// Log a warning when an interception call takes longer than this to process.
95constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -070097// Additional key latency in case a connection is still processing some motion events.
98// This will help with the case when a user touched a button that opens a new window,
99// and gives us the chance to dispatch the key to this new window.
100constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
101
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000103constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
104
Antonio Kantekea47acb2021-12-23 12:41:25 -0800105// Event log tags. See EventLogTags.logtags for reference.
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000106constexpr int LOGTAG_INPUT_INTERACTION = 62000;
107constexpr int LOGTAG_INPUT_FOCUS = 62001;
Arthur Hungb3307ee2021-10-14 10:57:37 +0000108constexpr int LOGTAG_INPUT_CANCEL = 62003;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000109
Prabir Pradhanc093bbe2022-12-06 20:30:22 +0000110const ui::Transform kIdentityTransform;
111
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 Pradhandb326da2023-03-09 04:51:55 +0000464bool windowAcceptsTouchAt(const WindowInfo& windowInfo, int32_t displayId, float x, float y,
Prabir Pradhanc093bbe2022-12-06 20:30:22 +0000465 bool isStylus, const ui::Transform& displayTransform) {
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 Pradhanc093bbe2022-12-06 20:30:22 +0000475
476 // Window Manager works in the logical display coordinate space. When it specifies bounds for a
477 // window as (l, t, r, b), the range of x in [l, r) and y in [t, b) are considered to be inside
478 // the window. Points on the right and bottom edges should not be inside the window, so we need
479 // to be careful about performing a hit test when the display is rotated, since the "right" and
480 // "bottom" of the window will be different in the display (un-rotated) space compared to in the
481 // logical display in which WM determined the bounds. Perform the hit test in the logical
482 // display space to ensure these edges are considered correctly in all orientations.
483 const auto touchableRegion = displayTransform.transform(windowInfo.touchableRegion);
484 const auto p = displayTransform.transform(x, y);
485 if (!touchableRegion.contains(std::floor(p.x), std::floor(p.y))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -0800486 return false;
487 }
488 return true;
489}
490
Prabir Pradhand65552b2021-10-07 11:23:50 -0700491bool isPointerFromStylus(const MotionEntry& entry, int32_t pointerIndex) {
492 return isFromSource(entry.source, AINPUT_SOURCE_STYLUS) &&
493 (entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
494 entry.pointerProperties[pointerIndex].toolType == AMOTION_EVENT_TOOL_TYPE_ERASER);
495}
496
Prabir Pradhan6dfbf262022-03-14 15:24:30 +0000497// Determines if the given window can be targeted as InputTarget::FLAG_FOREGROUND.
498// Foreground events are only sent to "foreground targetable" windows, but not all gestures sent to
499// such window are necessarily targeted with the flag. For example, an event with ACTION_OUTSIDE can
500// be sent to such a window, but it is not a foreground event and doesn't use
501// InputTarget::FLAG_FOREGROUND.
502bool canReceiveForegroundTouches(const WindowInfo& info) {
503 // A non-touchable window can still receive touch events (e.g. in the case of
504 // STYLUS_INTERCEPTOR), so prevent such windows from receiving foreground events for touches.
505 return !info.inputConfig.test(gui::WindowInfo::InputConfig::NOT_TOUCHABLE) && !info.isSpy();
506}
507
Antonio Kantek48710e42022-03-24 14:19:30 -0700508bool isWindowOwnedBy(const sp<WindowInfoHandle>& windowHandle, int32_t pid, int32_t uid) {
509 if (windowHandle == nullptr) {
510 return false;
511 }
512 const WindowInfo* windowInfo = windowHandle->getInfo();
513 if (pid == windowInfo->ownerPid && uid == windowInfo->ownerUid) {
514 return true;
515 }
516 return false;
517}
518
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000519// Checks targeted injection using the window's owner's uid.
520// Returns an empty string if an entry can be sent to the given window, or an error message if the
521// entry is a targeted injection whose uid target doesn't match the window owner.
522std::optional<std::string> verifyTargetedInjection(const sp<WindowInfoHandle>& window,
523 const EventEntry& entry) {
524 if (entry.injectionState == nullptr || !entry.injectionState->targetUid) {
525 // The event was not injected, or the injected event does not target a window.
526 return {};
527 }
528 const int32_t uid = *entry.injectionState->targetUid;
529 if (window == nullptr) {
530 return StringPrintf("No valid window target for injection into uid %d.", uid);
531 }
532 if (entry.injectionState->targetUid != window->getInfo()->ownerUid) {
533 return StringPrintf("Injected event targeted at uid %d would be dispatched to window '%s' "
534 "owned by uid %d.",
535 uid, window->getName().c_str(), window->getInfo()->ownerUid);
536 }
537 return {};
538}
539
Prabir Pradhan61a5d242021-07-26 16:41:09 +0000540} // namespace
541
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542// --- InputDispatcher ---
543
Garfield Tan00f511d2019-06-12 16:55:40 -0700544InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800545 : InputDispatcher(policy, STALE_EVENT_TIMEOUT) {}
546
547InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy,
548 std::chrono::nanoseconds staleEventTimeout)
Garfield Tan00f511d2019-06-12 16:55:40 -0700549 : mPolicy(policy),
550 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700551 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800552 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700553 mAppSwitchSawKeyDown(false),
554 mAppSwitchDueTime(LONG_LONG_MAX),
555 mNextUnblockedEvent(nullptr),
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800556 mMonitorDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT),
Garfield Tan00f511d2019-06-12 16:55:40 -0700557 mDispatchEnabled(false),
558 mDispatchFrozen(false),
559 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800560 // mInTouchMode will be initialized by the WindowManager to the default device config.
561 // To avoid leaking stack in case that call never comes, and for tests,
562 // initialize it here anyways.
Antonio Kantekf16f2832021-09-28 04:39:20 +0000563 mInTouchMode(kDefaultInTouchMode),
Bernardo Rufinoea97d182020-08-19 14:43:14 +0100564 mMaximumObscuringOpacityForTouch(1.0f),
Siarhei Vishniakou2508b872020-12-03 16:33:53 -1000565 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Prabir Pradhan99987712020-11-10 18:43:05 -0800566 mWindowTokenWithPointerCapture(nullptr),
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800567 mStaleEventTimeout(staleEventTimeout),
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +0000568 mLatencyAggregator(),
Siarhei Vishniakoubd252722022-01-06 03:49:35 -0800569 mLatencyTracker(&mLatencyAggregator) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800571 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700573 mWindowInfoListener = new DispatcherWindowListener(*this);
574 SurfaceComposerClient::getDefault()->addWindowInfosListener(mWindowInfoListener);
575
Yi Kong9b14ac62018-07-17 13:48:38 -0700576 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577
578 policy->getDispatcherConfiguration(&mConfig);
579}
580
581InputDispatcher::~InputDispatcher() {
Prabir Pradhancef936d2021-07-21 16:17:52 +0000582 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583
Prabir Pradhancef936d2021-07-21 16:17:52 +0000584 resetKeyRepeatLocked();
585 releasePendingEventLocked();
586 drainInboundQueueLocked();
587 mCommandQueue.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800588
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +0000589 while (!mConnectionsByToken.empty()) {
590 sp<Connection> connection = mConnectionsByToken.begin()->second;
Prabir Pradhancef936d2021-07-21 16:17:52 +0000591 removeInputChannelLocked(connection->inputChannel->getConnectionToken(),
592 false /* notify */);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593 }
594}
595
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700596status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700597 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700598 return ALREADY_EXISTS;
599 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700600 mThread = std::make_unique<InputThread>(
601 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
602 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700603}
604
605status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700606 if (mThread && mThread->isCallingThread()) {
607 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700608 return INVALID_OPERATION;
609 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700610 mThread.reset();
611 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700612}
613
Michael Wrightd02c5b62014-02-10 15:10:22 -0800614void InputDispatcher::dispatchOnce() {
615 nsecs_t nextWakeupTime = LONG_LONG_MAX;
616 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800617 std::scoped_lock _l(mLock);
618 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800619
620 // Run a dispatch loop if there are no pending commands.
621 // The dispatch loop might enqueue commands to run afterwards.
622 if (!haveCommandsLocked()) {
623 dispatchOnceInnerLocked(&nextWakeupTime);
624 }
625
626 // Run all pending commands if there are any.
627 // If any commands were run then force the next poll to wake up immediately.
Prabir Pradhancef936d2021-07-21 16:17:52 +0000628 if (runCommandsLockedInterruptable()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 nextWakeupTime = LONG_LONG_MIN;
630 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800631
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700632 // If we are still waiting for ack on some events,
633 // we might have to wake up earlier to check if an app is anr'ing.
634 const nsecs_t nextAnrCheck = processAnrsLocked();
635 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
636
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800637 // We are about to enter an infinitely long sleep, because we have no commands or
638 // pending or queued events
639 if (nextWakeupTime == LONG_LONG_MAX) {
640 mDispatcherEnteredIdle.notify_all();
641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642 } // release lock
643
644 // Wait for callback or timeout or wake. (make sure we round up, not down)
645 nsecs_t currentTime = now();
646 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
647 mLooper->pollOnce(timeoutMillis);
648}
649
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700650/**
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500651 * Raise ANR if there is no focused window.
652 * Before the ANR is raised, do a final state check:
653 * 1. The currently focused application must be the same one we are waiting for.
654 * 2. Ensure we still don't have a focused window.
655 */
656void InputDispatcher::processNoFocusedWindowAnrLocked() {
657 // Check if the application that we are waiting for is still focused.
658 std::shared_ptr<InputApplicationHandle> focusedApplication =
659 getValueByKey(mFocusedApplicationHandlesByDisplay, mAwaitedApplicationDisplayId);
660 if (focusedApplication == nullptr ||
661 focusedApplication->getApplicationToken() !=
662 mAwaitedFocusedApplication->getApplicationToken()) {
663 // Unexpected because we should have reset the ANR timer when focused application changed
664 ALOGE("Waited for a focused window, but focused application has already changed to %s",
665 focusedApplication->getName().c_str());
666 return; // The focused application has changed.
667 }
668
chaviw98318de2021-05-19 16:45:23 -0500669 const sp<WindowInfoHandle>& focusedWindowHandle =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500670 getFocusedWindowHandleLocked(mAwaitedApplicationDisplayId);
671 if (focusedWindowHandle != nullptr) {
672 return; // We now have a focused window. No need for ANR.
673 }
674 onAnrLocked(mAwaitedFocusedApplication);
675}
676
677/**
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700678 * Check if any of the connections' wait queues have events that are too old.
679 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
680 * Return the time at which we should wake up next.
681 */
682nsecs_t InputDispatcher::processAnrsLocked() {
683 const nsecs_t currentTime = now();
684 nsecs_t nextAnrCheck = LONG_LONG_MAX;
685 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
686 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
687 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500688 processNoFocusedWindowAnrLocked();
Chris Yea209fde2020-07-22 13:54:51 -0700689 mAwaitedFocusedApplication.reset();
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -0500690 mNoFocusedWindowTimeoutTime = std::nullopt;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700691 return LONG_LONG_MIN;
692 } else {
Siarhei Vishniakou38a6d272020-10-20 20:29:33 -0500693 // Keep waiting. We will drop the event when mNoFocusedWindowTimeoutTime comes.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700694 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
695 }
696 }
697
698 // Check if any connection ANRs are due
699 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
700 if (currentTime < nextAnrCheck) { // most likely scenario
701 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
702 }
703
704 // If we reached here, we have an unresponsive connection.
705 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
706 if (connection == nullptr) {
707 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
708 return nextAnrCheck;
709 }
710 connection->responsive = false;
711 // Stop waking up for this unresponsive connection
712 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000713 onAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700714 return LONG_LONG_MIN;
715}
716
Prabir Pradhan1376fcd2022-01-21 09:56:35 -0800717std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(
718 const sp<Connection>& connection) {
719 if (connection->monitor) {
720 return mMonitorDispatchingTimeout;
721 }
722 const sp<WindowInfoHandle> window =
723 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700724 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500725 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700726 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500727 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700728}
729
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
731 nsecs_t currentTime = now();
732
Jeff Browndc5992e2014-04-11 01:27:26 -0700733 // Reset the key repeat timer whenever normal dispatch is suspended while the
734 // device is in a non-interactive state. This is to ensure that we abort a key
735 // repeat if the device is just coming out of sleep.
736 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737 resetKeyRepeatLocked();
738 }
739
740 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
741 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100742 if (DEBUG_FOCUS) {
743 ALOGD("Dispatch frozen. Waiting some more.");
744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745 return;
746 }
747
748 // Optimize latency of app switches.
749 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
750 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
751 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
752 if (mAppSwitchDueTime < *nextWakeupTime) {
753 *nextWakeupTime = mAppSwitchDueTime;
754 }
755
756 // Ready to start a new event.
757 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700759 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800760 if (isAppSwitchDue) {
761 // The inbound queue is empty so the app switch key we were waiting
762 // for will never arrive. Stop waiting for it.
763 resetPendingAppSwitchLocked(false);
764 isAppSwitchDue = false;
765 }
766
767 // Synthesize a key repeat if appropriate.
768 if (mKeyRepeatState.lastKeyEntry) {
769 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
770 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
771 } else {
772 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
773 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
774 }
775 }
776 }
777
778 // Nothing to do if there is no pending event.
779 if (!mPendingEvent) {
780 return;
781 }
782 } else {
783 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700784 mPendingEvent = mInboundQueue.front();
785 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 traceInboundQueueLengthLocked();
787 }
788
789 // Poke user activity for this event.
790 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700791 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800793 }
794
795 // Now we have an event to dispatch.
796 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700797 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700799 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700801 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700803 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800804 }
805
806 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700807 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808 }
809
810 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700811 case EventEntry::Type::CONFIGURATION_CHANGED: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700812 const ConfigurationChangedEntry& typedEntry =
813 static_cast<const ConfigurationChangedEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700814 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700815 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700816 break;
817 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700819 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700820 const DeviceResetEntry& typedEntry =
821 static_cast<const DeviceResetEntry&>(*mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700822 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700823 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 break;
825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100827 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700828 std::shared_ptr<FocusEntry> typedEntry =
829 std::static_pointer_cast<FocusEntry>(mPendingEvent);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100830 dispatchFocusLocked(currentTime, typedEntry);
831 done = true;
832 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
833 break;
834 }
835
Antonio Kantek7242d8b2021-08-05 16:07:20 -0700836 case EventEntry::Type::TOUCH_MODE_CHANGED: {
837 const auto typedEntry = std::static_pointer_cast<TouchModeEntry>(mPendingEvent);
838 dispatchTouchModeChangeLocked(currentTime, typedEntry);
839 done = true;
840 dropReason = DropReason::NOT_DROPPED; // touch mode events are never dropped
841 break;
842 }
843
Prabir Pradhan99987712020-11-10 18:43:05 -0800844 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
845 const auto typedEntry =
846 std::static_pointer_cast<PointerCaptureChangedEntry>(mPendingEvent);
847 dispatchPointerCaptureChangedLocked(currentTime, typedEntry, dropReason);
848 done = true;
849 break;
850 }
851
arthurhungb89ccb02020-12-30 16:19:01 +0800852 case EventEntry::Type::DRAG: {
853 std::shared_ptr<DragEntry> typedEntry =
854 std::static_pointer_cast<DragEntry>(mPendingEvent);
855 dispatchDragLocked(currentTime, typedEntry);
856 done = true;
857 break;
858 }
859
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700860 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700861 std::shared_ptr<KeyEntry> keyEntry = std::static_pointer_cast<KeyEntry>(mPendingEvent);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700862 if (isAppSwitchDue) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700863 if (isAppSwitchKeyEvent(*keyEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700864 resetPendingAppSwitchLocked(true);
865 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700866 } else if (dropReason == DropReason::NOT_DROPPED) {
867 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700868 }
869 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700870 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *keyEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700871 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700872 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700873 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
874 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700875 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700876 done = dispatchKeyLocked(currentTime, keyEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700877 break;
878 }
879
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700880 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700881 std::shared_ptr<MotionEntry> motionEntry =
882 std::static_pointer_cast<MotionEntry>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700883 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
884 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700886 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *motionEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700887 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700888 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700889 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
890 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700891 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700892 done = dispatchMotionLocked(currentTime, motionEntry, &dropReason, nextWakeupTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700893 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 }
Chris Yef59a2f42020-10-16 12:55:26 -0700895
896 case EventEntry::Type::SENSOR: {
897 std::shared_ptr<SensorEntry> sensorEntry =
898 std::static_pointer_cast<SensorEntry>(mPendingEvent);
899 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
900 dropReason = DropReason::APP_SWITCH;
901 }
902 // Sensor timestamps use SYSTEM_TIME_BOOTTIME time base, so we can't use
903 // 'currentTime' here, get SYSTEM_TIME_BOOTTIME instead.
904 nsecs_t bootTime = systemTime(SYSTEM_TIME_BOOTTIME);
905 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(bootTime, *sensorEntry)) {
906 dropReason = DropReason::STALE;
907 }
908 dispatchSensorLocked(currentTime, sensorEntry, &dropReason, nextWakeupTime);
909 done = true;
910 break;
911 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912 }
913
914 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700915 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700916 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917 }
Michael Wright3a981722015-06-10 15:26:13 +0100918 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919
920 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700921 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 }
923}
924
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800925bool InputDispatcher::isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
926 return std::chrono::nanoseconds(currentTime - entry.eventTime) >= mStaleEventTimeout;
927}
928
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700929/**
930 * Return true if the events preceding this incoming motion event should be dropped
931 * Return false otherwise (the default behaviour)
932 */
933bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700934 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Prabir Pradhanaa561d12021-09-24 06:57:33 -0700935 isFromSource(motionEntry.source, AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700936
937 // Optimize case where the current application is unresponsive and the user
938 // decides to touch a window in a different application.
939 // If the application takes too long to catch up then we drop all events preceding
940 // the touch into the other window.
941 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700942 int32_t displayId = motionEntry.displayId;
Prabir Pradhandb326da2023-03-09 04:51:55 +0000943 const float x = motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X);
944 const float y = motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y);
Prabir Pradhand65552b2021-10-07 11:23:50 -0700945
946 const bool isStylus = isPointerFromStylus(motionEntry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -0500947 sp<WindowInfoHandle> touchedWindowHandle =
Prabir Pradhand65552b2021-10-07 11:23:50 -0700948 findTouchedWindowAtLocked(displayId, x, y, nullptr, isStylus);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700949 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700950 touchedWindowHandle->getApplicationToken() !=
951 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700952 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700953 ALOGI("Pruning input queue because user touched a different application while waiting "
954 "for %s",
955 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700956 return true;
957 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700958
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800959 // Alternatively, maybe there's a spy window that could handle this event.
960 const std::vector<sp<WindowInfoHandle>> touchedSpies =
961 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
962 for (const auto& windowHandle : touchedSpies) {
963 const sp<Connection> connection = getConnectionLocked(windowHandle->getToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000964 if (connection != nullptr && connection->responsive) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800965 // This spy window could take more input. Drop all events preceding this
966 // event, so that the spy window can get a chance to receive the stream.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700967 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
Prabir Pradhandfabf8a2022-01-21 08:19:30 -0800968 "responsive spy window that may handle the event.",
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700969 mAwaitedFocusedApplication->getName().c_str());
970 return true;
971 }
972 }
973 }
974
975 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
976 // yet been processed by some connections, the dispatcher will wait for these motion
977 // events to be processed before dispatching the key event. This is because these motion events
978 // may cause a new window to be launched, which the user might expect to receive focus.
979 // To prevent waiting forever for such events, just send the key to the currently focused window
980 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
981 ALOGD("Received a new pointer down event, stop waiting for events to process and "
982 "just send the pending key event to the focused window.");
983 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700984 }
985 return false;
986}
987
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700988bool InputDispatcher::enqueueInboundEventLocked(std::unique_ptr<EventEntry> newEntry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700989 bool needWake = mInboundQueue.empty();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700990 mInboundQueue.push_back(std::move(newEntry));
991 EventEntry& entry = *(mInboundQueue.back());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992 traceInboundQueueLengthLocked();
993
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -0700994 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700995 case EventEntry::Type::KEY: {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +0000996 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
997 "Unexpected untrusted event.");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700998 // Optimize app switch latency.
999 // If the application takes too long to catch up then we drop all events preceding
1000 // the app switch key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001001 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001002 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001003 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001004 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001005 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001006 if (mAppSwitchSawKeyDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001007 if (DEBUG_APP_SWITCH) {
1008 ALOGD("App switch is pending!");
1009 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001010 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001011 mAppSwitchSawKeyDown = false;
1012 needWake = true;
1013 }
1014 }
1015 }
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08001016
1017 // If a new up event comes in, and the pending event with same key code has been asked
1018 // to try again later because of the policy. We have to reset the intercept key wake up
1019 // time for it may have been handled in the policy and could be dropped.
1020 if (keyEntry.action == AKEY_EVENT_ACTION_UP && mPendingEvent &&
1021 mPendingEvent->type == EventEntry::Type::KEY) {
1022 KeyEntry& pendingKey = static_cast<KeyEntry&>(*mPendingEvent);
1023 if (pendingKey.keyCode == keyEntry.keyCode &&
1024 pendingKey.interceptKeyResult ==
1025 KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1026 pendingKey.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1027 pendingKey.interceptKeyWakeupTime = 0;
1028 needWake = true;
1029 }
1030 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001031 break;
1032 }
1033
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001034 case EventEntry::Type::MOTION: {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001035 LOG_ALWAYS_FATAL_IF((entry.policyFlags & POLICY_FLAG_TRUSTED) == 0,
1036 "Unexpected untrusted event.");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001037 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(entry))) {
1038 mNextUnblockedEvent = mInboundQueue.back();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001039 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001041 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001043 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001044 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
1045 break;
1046 }
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001047 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001048 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001049 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07001050 case EventEntry::Type::SENSOR:
arthurhungb89ccb02020-12-30 16:19:01 +08001051 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1052 case EventEntry::Type::DRAG: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001053 // nothing to do
1054 break;
1055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
1057
1058 return needWake;
1059}
1060
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001061void InputDispatcher::addRecentEventLocked(std::shared_ptr<EventEntry> entry) {
Chris Yef59a2f42020-10-16 12:55:26 -07001062 // Do not store sensor event in recent queue to avoid flooding the queue.
1063 if (entry->type != EventEntry::Type::SENSOR) {
1064 mRecentQueue.push_back(entry);
1065 }
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001066 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001067 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001068 }
1069}
1070
Prabir Pradhandb326da2023-03-09 04:51:55 +00001071sp<WindowInfoHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, float x, float y,
1072 TouchState* touchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07001073 bool isStylus,
chaviw98318de2021-05-19 16:45:23 -05001074 bool addOutsideTargets,
1075 bool ignoreDragWindow) {
Siarhei Vishniakou64452932020-11-06 17:51:32 -06001076 if (addOutsideTargets && touchState == nullptr) {
1077 LOG_ALWAYS_FATAL("Must provide a valid touch state if adding outside targets");
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001078 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 // Traverse windows from front to back to find touched window.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001080 const auto& windowHandles = getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05001081 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
arthurhung6d4bed92021-03-17 11:59:33 +08001082 if (ignoreDragWindow && haveSameToken(windowHandle, mDragState->dragWindow)) {
arthurhungb89ccb02020-12-30 16:19:01 +08001083 continue;
1084 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001086 const WindowInfo& info = *windowHandle->getInfo();
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00001087 if (!info.isSpy() &&
1088 windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001089 return windowHandle;
1090 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001091
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001092 if (addOutsideTargets &&
1093 info.inputConfig.test(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08001094 touchState->addOrUpdateWindow(windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1095 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096 }
1097 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001098 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099}
1100
Prabir Pradhand65552b2021-10-07 11:23:50 -07001101std::vector<sp<WindowInfoHandle>> InputDispatcher::findTouchedSpyWindowsAtLocked(
Prabir Pradhandb326da2023-03-09 04:51:55 +00001102 int32_t displayId, float x, float y, bool isStylus) const {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001103 // Traverse windows from front to back and gather the touched spy windows.
1104 std::vector<sp<WindowInfoHandle>> spyWindows;
1105 const auto& windowHandles = getWindowHandlesLocked(displayId);
1106 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
1107 const WindowInfo& info = *windowHandle->getInfo();
1108
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00001109 if (!windowAcceptsTouchAt(info, displayId, x, y, isStylus, getTransformLocked(displayId))) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001110 continue;
1111 }
1112 if (!info.isSpy()) {
1113 // The first touched non-spy window was found, so return the spy windows touched so far.
1114 return spyWindows;
1115 }
1116 spyWindows.push_back(windowHandle);
1117 }
1118 return spyWindows;
1119}
1120
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001121void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 const char* reason;
1123 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001124 case DropReason::POLICY:
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001125 if (DEBUG_INBOUND_EVENT_DETAILS) {
1126 ALOGD("Dropped event because policy consumed it.");
1127 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 reason = "inbound event was dropped because the policy consumed it";
1129 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001130 case DropReason::DISABLED:
1131 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001132 ALOGI("Dropped event because input dispatch is disabled.");
1133 }
1134 reason = "inbound event was dropped because input dispatch is disabled";
1135 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001136 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001137 ALOGI("Dropped event because of pending overdue app switch.");
1138 reason = "inbound event was dropped because of pending overdue app switch";
1139 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001140 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001141 ALOGI("Dropped event because the current application is not responding and the user "
1142 "has started interacting with a different application.");
1143 reason = "inbound event was dropped because the current application is not responding "
1144 "and the user has started interacting with a different application";
1145 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001146 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001147 ALOGI("Dropped event because it is stale.");
1148 reason = "inbound event was dropped because it is stale";
1149 break;
Prabir Pradhan99987712020-11-10 18:43:05 -08001150 case DropReason::NO_POINTER_CAPTURE:
1151 ALOGI("Dropped event because there is no window with Pointer Capture.");
1152 reason = "inbound event was dropped because there is no window with Pointer Capture";
1153 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001154 case DropReason::NOT_DROPPED: {
1155 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001156 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 }
1159
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001160 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001161 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1163 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001164 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001166 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001167 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1168 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001169 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
1170 synthesizeCancelationEventsForAllConnectionsLocked(options);
1171 } else {
1172 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
1173 synthesizeCancelationEventsForAllConnectionsLocked(options);
1174 }
1175 break;
1176 }
Chris Yef59a2f42020-10-16 12:55:26 -07001177 case EventEntry::Type::SENSOR: {
1178 break;
1179 }
arthurhungb89ccb02020-12-30 16:19:01 +08001180 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
1181 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08001182 break;
1183 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001184 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001185 case EventEntry::Type::TOUCH_MODE_CHANGED:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001186 case EventEntry::Type::CONFIGURATION_CHANGED:
1187 case EventEntry::Type::DEVICE_RESET: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001188 LOG_ALWAYS_FATAL("Should not drop %s events", ftl::enum_string(entry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001189 break;
1190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 }
1192}
1193
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001194static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001195 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
1196 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197}
1198
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001199bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
1200 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
1201 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
1202 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203}
1204
1205bool InputDispatcher::isAppSwitchPendingLocked() {
1206 return mAppSwitchDueTime != LONG_LONG_MAX;
1207}
1208
1209void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
1210 mAppSwitchDueTime = LONG_LONG_MAX;
1211
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001212 if (DEBUG_APP_SWITCH) {
1213 if (handled) {
1214 ALOGD("App switch has arrived.");
1215 } else {
1216 ALOGD("App switch was abandoned.");
1217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219}
1220
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001222 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223}
1224
Prabir Pradhancef936d2021-07-21 16:17:52 +00001225bool InputDispatcher::runCommandsLockedInterruptable() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001226 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 return false;
1228 }
1229
1230 do {
Prabir Pradhancef936d2021-07-21 16:17:52 +00001231 auto command = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001232 mCommandQueue.pop_front();
Prabir Pradhancef936d2021-07-21 16:17:52 +00001233 // Commands are run with the lock held, but may release and re-acquire the lock from within.
1234 command();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001235 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 return true;
1237}
1238
Prabir Pradhancef936d2021-07-21 16:17:52 +00001239void InputDispatcher::postCommandLocked(Command&& command) {
1240 mCommandQueue.push_back(command);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241}
1242
1243void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001244 while (!mInboundQueue.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001245 std::shared_ptr<EventEntry> entry = mInboundQueue.front();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07001246 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 releaseInboundEventLocked(entry);
1248 }
1249 traceInboundQueueLengthLocked();
1250}
1251
1252void InputDispatcher::releasePendingEventLocked() {
1253 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -07001255 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256 }
1257}
1258
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001259void InputDispatcher::releaseInboundEventLocked(std::shared_ptr<EventEntry> entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 InjectionState* injectionState = entry->injectionState;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001261 if (injectionState && injectionState->injectionResult == InputEventInjectionResult::PENDING) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001262 if (DEBUG_DISPATCH_CYCLE) {
1263 ALOGD("Injected inbound event was dropped.");
1264 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001265 setInjectionResult(*entry, InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 }
1267 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001268 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269 }
1270 addRecentEventLocked(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271}
1272
1273void InputDispatcher::resetKeyRepeatLocked() {
1274 if (mKeyRepeatState.lastKeyEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001275 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 }
1277}
1278
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001279std::shared_ptr<KeyEntry> InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
1280 std::shared_ptr<KeyEntry> entry = mKeyRepeatState.lastKeyEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281
Michael Wright2e732952014-09-24 13:26:59 -07001282 uint32_t policyFlags = entry->policyFlags &
1283 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001285 std::shared_ptr<KeyEntry> newEntry =
1286 std::make_unique<KeyEntry>(mIdGenerator.nextId(), currentTime, entry->deviceId,
1287 entry->source, entry->displayId, policyFlags, entry->action,
1288 entry->flags, entry->keyCode, entry->scanCode,
1289 entry->metaState, entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001291 newEntry->syntheticRepeat = true;
1292 mKeyRepeatState.lastKeyEntry = newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001294 return newEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295}
1296
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001297bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001298 const ConfigurationChangedEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001299 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1300 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry.eventTime);
1301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302
1303 // Reset key repeating in case a keyboard device was added or removed or something.
1304 resetKeyRepeatLocked();
1305
1306 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Prabir Pradhancef936d2021-07-21 16:17:52 +00001307 auto command = [this, eventTime = entry.eventTime]() REQUIRES(mLock) {
1308 scoped_unlock unlock(mLock);
1309 mPolicy->notifyConfigurationChanged(eventTime);
1310 };
1311 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 return true;
1313}
1314
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001315bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime,
1316 const DeviceResetEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001317 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1318 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry.eventTime,
1319 entry.deviceId);
1320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321
liushenxiang42232912021-05-21 20:24:09 +08001322 // Reset key repeating in case a keyboard device was disabled or enabled.
1323 if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->deviceId == entry.deviceId) {
1324 resetKeyRepeatLocked();
1325 }
1326
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001327 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001328 options.deviceId = entry.deviceId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 synthesizeCancelationEventsForAllConnectionsLocked(options);
1330 return true;
1331}
1332
Vishnu Nairad321cd2020-08-20 16:40:21 -07001333void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nairc519ff72021-01-21 08:23:08 -08001334 const std::string& reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001335 if (mPendingEvent != nullptr) {
1336 // Move the pending event to the front of the queue. This will give the chance
1337 // for the pending event to get dispatched to the newly focused window
1338 mInboundQueue.push_front(mPendingEvent);
1339 mPendingEvent = nullptr;
1340 }
1341
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001342 std::unique_ptr<FocusEntry> focusEntry =
1343 std::make_unique<FocusEntry>(mIdGenerator.nextId(), now(), windowToken, hasFocus,
1344 reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001345
1346 // This event should go to the front of the queue, but behind all other focus events
1347 // Find the last focus event, and insert right after it
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001348 std::deque<std::shared_ptr<EventEntry>>::reverse_iterator it =
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001349 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001350 [](const std::shared_ptr<EventEntry>& event) {
1351 return event->type == EventEntry::Type::FOCUS;
1352 });
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001353
1354 // Maintain the order of focus events. Insert the entry after all other focus events.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001355 mInboundQueue.insert(it.base(), std::move(focusEntry));
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001356}
1357
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001358void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, std::shared_ptr<FocusEntry> entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001359 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001360 if (channel == nullptr) {
1361 return; // Window has gone away
1362 }
1363 InputTarget target;
1364 target.inputChannel = channel;
1365 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1366 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001367 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1368 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001369 std::string reason = std::string("reason=").append(entry->reason);
1370 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001371 dispatchEventLocked(currentTime, entry, {target});
1372}
1373
Prabir Pradhan99987712020-11-10 18:43:05 -08001374void InputDispatcher::dispatchPointerCaptureChangedLocked(
1375 nsecs_t currentTime, const std::shared_ptr<PointerCaptureChangedEntry>& entry,
1376 DropReason& dropReason) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001377 dropReason = DropReason::NOT_DROPPED;
1378
Prabir Pradhan99987712020-11-10 18:43:05 -08001379 const bool haveWindowWithPointerCapture = mWindowTokenWithPointerCapture != nullptr;
Prabir Pradhan99987712020-11-10 18:43:05 -08001380 sp<IBinder> token;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001381
1382 if (entry->pointerCaptureRequest.enable) {
1383 // Enable Pointer Capture.
1384 if (haveWindowWithPointerCapture &&
1385 (entry->pointerCaptureRequest == mCurrentPointerCaptureRequest)) {
Prabir Pradhan7092e262022-05-03 16:51:09 +00001386 // This can happen if pointer capture is disabled and re-enabled before we notify the
1387 // app of the state change, so there is no need to notify the app.
1388 ALOGI("Skipping dispatch of Pointer Capture being enabled: no state change.");
1389 return;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001390 }
1391 if (!mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08001392 // This can happen if a window requests capture and immediately releases capture.
1393 ALOGW("No window requested Pointer Capture.");
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001394 dropReason = DropReason::NO_POINTER_CAPTURE;
Prabir Pradhan99987712020-11-10 18:43:05 -08001395 return;
1396 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001397 if (entry->pointerCaptureRequest.seq != mCurrentPointerCaptureRequest.seq) {
1398 ALOGI("Skipping dispatch of Pointer Capture being enabled: sequence number mismatch.");
1399 return;
1400 }
1401
Vishnu Nairc519ff72021-01-21 08:23:08 -08001402 token = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08001403 LOG_ALWAYS_FATAL_IF(!token, "Cannot find focused window for Pointer Capture.");
1404 mWindowTokenWithPointerCapture = token;
1405 } else {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001406 // Disable Pointer Capture.
1407 // We do not check if the sequence number matches for requests to disable Pointer Capture
1408 // for two reasons:
1409 // 1. Pointer Capture can be disabled by a focus change, which means we can get two entries
1410 // to disable capture with the same sequence number: one generated by
1411 // disablePointerCaptureForcedLocked() and another as an acknowledgement of Pointer
1412 // Capture being disabled in InputReader.
1413 // 2. We respect any request to disable Pointer Capture generated by InputReader, since the
1414 // actual Pointer Capture state that affects events being generated by input devices is
1415 // in InputReader.
1416 if (!haveWindowWithPointerCapture) {
1417 // Pointer capture was already forcefully disabled because of focus change.
1418 dropReason = DropReason::NOT_DROPPED;
1419 return;
1420 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001421 token = mWindowTokenWithPointerCapture;
1422 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001423 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001424 setPointerCaptureLocked(false);
1425 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001426 }
1427
1428 auto channel = getInputChannelLocked(token);
1429 if (channel == nullptr) {
1430 // Window has gone away, clean up Pointer Capture state.
1431 mWindowTokenWithPointerCapture = nullptr;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001432 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan7d030382020-12-21 07:58:35 -08001433 setPointerCaptureLocked(false);
1434 }
Prabir Pradhan99987712020-11-10 18:43:05 -08001435 return;
1436 }
1437 InputTarget target;
1438 target.inputChannel = channel;
1439 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1440 entry->dispatchInProgress = true;
1441 dispatchEventLocked(currentTime, entry, {target});
1442
1443 dropReason = DropReason::NOT_DROPPED;
1444}
1445
Antonio Kantek7242d8b2021-08-05 16:07:20 -07001446void InputDispatcher::dispatchTouchModeChangeLocked(nsecs_t currentTime,
1447 const std::shared_ptr<TouchModeEntry>& entry) {
1448 const std::vector<sp<WindowInfoHandle>>& windowHandles =
1449 getWindowHandlesLocked(mFocusedDisplayId);
1450 if (windowHandles.empty()) {
1451 return;
1452 }
1453 const std::vector<InputTarget> inputTargets =
1454 getInputTargetsFromWindowHandlesLocked(windowHandles);
1455 if (inputTargets.empty()) {
1456 return;
1457 }
1458 entry->dispatchInProgress = true;
1459 dispatchEventLocked(currentTime, entry, inputTargets);
1460}
1461
1462std::vector<InputTarget> InputDispatcher::getInputTargetsFromWindowHandlesLocked(
1463 const std::vector<sp<WindowInfoHandle>>& windowHandles) const {
1464 std::vector<InputTarget> inputTargets;
1465 for (const sp<WindowInfoHandle>& handle : windowHandles) {
1466 // TODO(b/193718270): Due to performance concerns, consider notifying visible windows only.
1467 const sp<IBinder>& token = handle->getToken();
1468 if (token == nullptr) {
1469 continue;
1470 }
1471 std::shared_ptr<InputChannel> channel = getInputChannelLocked(token);
1472 if (channel == nullptr) {
1473 continue; // Window has gone away
1474 }
1475 InputTarget target;
1476 target.inputChannel = channel;
1477 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1478 inputTargets.push_back(target);
1479 }
1480 return inputTargets;
1481}
1482
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001483bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, std::shared_ptr<KeyEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001484 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001486 if (!entry->dispatchInProgress) {
1487 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1488 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1489 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1490 if (mKeyRepeatState.lastKeyEntry &&
Chris Ye2ad95392020-09-01 13:44:44 -07001491 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode &&
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 // We have seen two identical key downs in a row which indicates that the device
1493 // driver is automatically generating key repeats itself. We take note of the
1494 // repeat here, but we disable our own next key repeat timer since it is clear that
1495 // we will not need to synthesize key repeats ourselves.
Chris Ye2ad95392020-09-01 13:44:44 -07001496 mKeyRepeatState.lastKeyEntry->deviceId == entry->deviceId) {
1497 // Make sure we don't get key down from a different device. If a different
1498 // device Id has same key pressed down, the new device Id will replace the
1499 // current one to hold the key repeat with repeat count reset.
1500 // In the future when got a KEY_UP on the device id, drop it and do not
1501 // stop the key repeat on current device.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1503 resetKeyRepeatLocked();
1504 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1505 } else {
1506 // Not a repeat. Save key down state in case we do see a repeat later.
1507 resetKeyRepeatLocked();
1508 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1509 }
1510 mKeyRepeatState.lastKeyEntry = entry;
Chris Ye2ad95392020-09-01 13:44:44 -07001511 } else if (entry->action == AKEY_EVENT_ACTION_UP && mKeyRepeatState.lastKeyEntry &&
1512 mKeyRepeatState.lastKeyEntry->deviceId != entry->deviceId) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001513 // The key on device 'deviceId' is still down, do not stop key repeat
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001514 if (DEBUG_INBOUND_EVENT_DETAILS) {
1515 ALOGD("deviceId=%d got KEY_UP as stale", entry->deviceId);
1516 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001517 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 resetKeyRepeatLocked();
1519 }
1520
1521 if (entry->repeatCount == 1) {
1522 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1523 } else {
1524 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1525 }
1526
1527 entry->dispatchInProgress = true;
1528
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001529 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 }
1531
1532 // Handle case where the policy asked us to try again later last time.
1533 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1534 if (currentTime < entry->interceptKeyWakeupTime) {
1535 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1536 *nextWakeupTime = entry->interceptKeyWakeupTime;
1537 }
1538 return false; // wait until next wakeup
1539 }
1540 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1541 entry->interceptKeyWakeupTime = 0;
1542 }
1543
1544 // Give the policy a chance to intercept the key.
1545 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1546 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001547 sp<IBinder> focusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08001548 mFocusResolver.getFocusedWindowToken(getTargetDisplayId(*entry));
Prabir Pradhancef936d2021-07-21 16:17:52 +00001549
1550 auto command = [this, focusedWindowToken, entry]() REQUIRES(mLock) {
1551 doInterceptKeyBeforeDispatchingCommand(focusedWindowToken, *entry);
1552 };
1553 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 return false; // wait for the command to run
1555 } else {
1556 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1557 }
1558 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001559 if (*dropReason == DropReason::NOT_DROPPED) {
1560 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 }
1562 }
1563
1564 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001565 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001566 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001567 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1568 : InputEventInjectionResult::FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001569 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 return true;
1571 }
1572
1573 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001574 std::vector<InputTarget> inputTargets;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001575 InputEventInjectionResult injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001576 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001577 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 return false;
1579 }
1580
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001581 setInjectionResult(*entry, injectionResult);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001582 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 return true;
1584 }
1585
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001586 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001587 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588
1589 // Dispatch the key.
1590 dispatchEventLocked(currentTime, entry, inputTargets);
1591 return true;
1592}
1593
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001594void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001595 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1596 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
1597 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1598 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
1599 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
1600 entry.policyFlags, entry.action, entry.flags, entry.keyCode, entry.scanCode,
1601 entry.metaState, entry.repeatCount, entry.downTime);
1602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603}
1604
Prabir Pradhancef936d2021-07-21 16:17:52 +00001605void InputDispatcher::dispatchSensorLocked(nsecs_t currentTime,
1606 const std::shared_ptr<SensorEntry>& entry,
Chris Yef59a2f42020-10-16 12:55:26 -07001607 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001608 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1609 ALOGD("notifySensorEvent eventTime=%" PRId64 ", hwTimestamp=%" PRId64 ", deviceId=%d, "
1610 "source=0x%x, sensorType=%s",
1611 entry->eventTime, entry->hwTimestamp, entry->deviceId, entry->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08001612 ftl::enum_string(entry->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001613 }
Prabir Pradhancef936d2021-07-21 16:17:52 +00001614 auto command = [this, entry]() REQUIRES(mLock) {
1615 scoped_unlock unlock(mLock);
1616
1617 if (entry->accuracyChanged) {
1618 mPolicy->notifySensorAccuracy(entry->deviceId, entry->sensorType, entry->accuracy);
1619 }
1620 mPolicy->notifySensorEvent(entry->deviceId, entry->sensorType, entry->accuracy,
1621 entry->hwTimestamp, entry->values);
1622 };
1623 postCommandLocked(std::move(command));
Chris Yef59a2f42020-10-16 12:55:26 -07001624}
1625
1626bool InputDispatcher::flushSensor(int deviceId, InputDeviceSensorType sensorType) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001627 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1628 ALOGD("flushSensor deviceId=%d, sensorType=%s", deviceId,
Dominik Laskowski75788452021-02-09 18:51:25 -08001629 ftl::enum_string(sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001630 }
Chris Yef59a2f42020-10-16 12:55:26 -07001631 { // acquire lock
1632 std::scoped_lock _l(mLock);
1633
1634 for (auto it = mInboundQueue.begin(); it != mInboundQueue.end(); it++) {
1635 std::shared_ptr<EventEntry> entry = *it;
1636 if (entry->type == EventEntry::Type::SENSOR) {
1637 it = mInboundQueue.erase(it);
1638 releaseInboundEventLocked(entry);
1639 }
1640 }
1641 }
1642 return true;
1643}
1644
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001645bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, std::shared_ptr<MotionEntry> entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001646 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001647 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001649 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 entry->dispatchInProgress = true;
1651
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001652 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 }
1654
1655 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001656 if (*dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001657 setInjectionResult(*entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001658 *dropReason == DropReason::POLICY ? InputEventInjectionResult::SUCCEEDED
1659 : InputEventInjectionResult::FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 return true;
1661 }
1662
Prabir Pradhanaa561d12021-09-24 06:57:33 -07001663 const bool isPointerEvent = isFromSource(entry->source, AINPUT_SOURCE_CLASS_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664
1665 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001666 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667
1668 bool conflictingPointerActions = false;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001669 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 if (isPointerEvent) {
1671 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001672 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001673 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001674 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 } else {
1676 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001677 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001678 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001680 if (injectionResult == InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681 return false;
1682 }
1683
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001684 setInjectionResult(*entry, injectionResult);
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001685 if (injectionResult == InputEventInjectionResult::TARGET_MISMATCH) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001686 return true;
1687 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001688 if (injectionResult != InputEventInjectionResult::SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001689 CancelationOptions::Mode mode(isPointerEvent
1690 ? CancelationOptions::CANCEL_POINTER_EVENTS
1691 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1692 CancelationOptions options(mode, "input event injection failed");
1693 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 return true;
1695 }
1696
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001697 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001698 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001699
1700 // Dispatch the motion.
1701 if (conflictingPointerActions) {
1702 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001703 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001704 synthesizeCancelationEventsForAllConnectionsLocked(options);
1705 }
1706 dispatchEventLocked(currentTime, entry, inputTargets);
1707 return true;
1708}
1709
chaviw98318de2021-05-19 16:45:23 -05001710void InputDispatcher::enqueueDragEventLocked(const sp<WindowInfoHandle>& windowHandle,
Arthur Hung54745652022-04-20 07:17:41 +00001711 bool isExiting, const int32_t rawX,
1712 const int32_t rawY) {
1713 const vec2 xy = windowHandle->getInfo()->transform.transform(vec2(rawX, rawY));
arthurhungb89ccb02020-12-30 16:19:01 +08001714 std::unique_ptr<DragEntry> dragEntry =
Arthur Hung54745652022-04-20 07:17:41 +00001715 std::make_unique<DragEntry>(mIdGenerator.nextId(), now(), windowHandle->getToken(),
1716 isExiting, xy.x, xy.y);
arthurhungb89ccb02020-12-30 16:19:01 +08001717
1718 enqueueInboundEventLocked(std::move(dragEntry));
1719}
1720
1721void InputDispatcher::dispatchDragLocked(nsecs_t currentTime, std::shared_ptr<DragEntry> entry) {
1722 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
1723 if (channel == nullptr) {
1724 return; // Window has gone away
1725 }
1726 InputTarget target;
1727 target.inputChannel = channel;
1728 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1729 entry->dispatchInProgress = true;
1730 dispatchEventLocked(currentTime, entry, {target});
1731}
1732
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001733void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001734 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
1735 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1736 ", policyFlags=0x%x, "
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001737 "action=%s, actionButton=0x%x, flags=0x%x, "
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001738 "metaState=0x%x, buttonState=0x%x,"
1739 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1740 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId,
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001741 entry.policyFlags, MotionEvent::actionToString(entry.action).c_str(),
1742 entry.actionButton, entry.flags, entry.metaState, entry.buttonState, entry.edgeFlags,
1743 entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001745 for (uint32_t i = 0; i < entry.pointerCount; i++) {
1746 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1747 "x=%f, y=%f, pressure=%f, size=%f, "
1748 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1749 "orientation=%f",
1750 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1751 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1752 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1753 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1754 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1755 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1756 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1757 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1758 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1759 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
1760 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762}
1763
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07001764void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1765 std::shared_ptr<EventEntry> eventEntry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001766 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001767 ATRACE_CALL();
Prabir Pradhan61a5d242021-07-26 16:41:09 +00001768 if (DEBUG_DISPATCH_CYCLE) {
1769 ALOGD("dispatchEventToCurrentInputTargets");
1770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001772 updateInteractionTokensLocked(*eventEntry, inputTargets);
1773
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1775
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001776 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001778 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001779 sp<Connection> connection =
1780 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001781 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001782 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001784 if (DEBUG_FOCUS) {
1785 ALOGD("Dropping event delivery to target with channel '%s' because it "
1786 "is no longer registered with the input dispatcher.",
1787 inputTarget.inputChannel->getName().c_str());
1788 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 }
1790 }
1791}
1792
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001793void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1794 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1795 // If the policy decides to close the app, we will get a channel removal event via
1796 // unregisterInputChannel, and will clean up the connection that way. We are already not
1797 // sending new pointers to the connection when it blocked, but focused events will continue to
1798 // pile up.
1799 ALOGW("Canceling events for %s because it is unresponsive",
1800 connection->inputChannel->getName().c_str());
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08001801 if (connection->status == Connection::Status::NORMAL) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001802 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1803 "application not responding");
1804 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805 }
1806}
1807
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001808void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001809 if (DEBUG_FOCUS) {
1810 ALOGD("Resetting ANR timeouts.");
1811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812
1813 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001814 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001815 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816}
1817
Tiger Huang721e26f2018-07-24 22:26:19 +08001818/**
1819 * Get the display id that the given event should go to. If this event specifies a valid display id,
1820 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1821 * Focused display is the display that the user most recently interacted with.
1822 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001823int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001824 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001825 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001826 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001827 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1828 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001829 break;
1830 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001831 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001832 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1833 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001834 break;
1835 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00001836 case EventEntry::Type::TOUCH_MODE_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08001837 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001838 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001839 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07001840 case EventEntry::Type::DEVICE_RESET:
arthurhungb89ccb02020-12-30 16:19:01 +08001841 case EventEntry::Type::SENSOR:
1842 case EventEntry::Type::DRAG: {
Dominik Laskowski75788452021-02-09 18:51:25 -08001843 ALOGE("%s events do not have a target display", ftl::enum_string(entry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001844 return ADISPLAY_ID_NONE;
1845 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001846 }
1847 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1848}
1849
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001850bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1851 const char* focusedWindowName) {
1852 if (mAnrTracker.empty()) {
1853 // already processed all events that we waited for
1854 mKeyIsWaitingForEventsTimeout = std::nullopt;
1855 return false;
1856 }
1857
1858 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1859 // Start the timer
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00001860 // Wait to send key because there are unprocessed events that may cause focus to change
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001861 mKeyIsWaitingForEventsTimeout = currentTime +
1862 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1863 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001864 return true;
1865 }
1866
1867 // We still have pending events, and already started the timer
1868 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1869 return true; // Still waiting
1870 }
1871
1872 // Waited too long, and some connection still hasn't processed all motions
1873 // Just send the key to the focused window
1874 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1875 focusedWindowName);
1876 mKeyIsWaitingForEventsTimeout = std::nullopt;
1877 return false;
1878}
1879
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001880InputEventInjectionResult InputDispatcher::findFocusedWindowTargetsLocked(
1881 nsecs_t currentTime, const EventEntry& entry, std::vector<InputTarget>& inputTargets,
1882 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001883 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884
Tiger Huang721e26f2018-07-24 22:26:19 +08001885 int32_t displayId = getTargetDisplayId(entry);
chaviw98318de2021-05-19 16:45:23 -05001886 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001887 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001888 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1889
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 // If there is no currently focused window and no focused application
1891 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001892 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1893 ALOGI("Dropping %s event because there is no focused window or focused application in "
1894 "display %" PRId32 ".",
Dominik Laskowski75788452021-02-09 18:51:25 -08001895 ftl::enum_string(entry.type).c_str(), displayId);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001896 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001897 }
1898
Vishnu Nair062a8672021-09-03 16:07:44 -07001899 // Drop key events if requested by input feature
1900 if (focusedWindowHandle != nullptr && shouldDropInput(entry, focusedWindowHandle)) {
1901 return InputEventInjectionResult::FAILED;
1902 }
1903
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001904 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1905 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1906 // start interacting with another application via touch (app switch). This code can be removed
1907 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1908 // an app is expected to have a focused window.
1909 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1910 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1911 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001912 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1913 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1914 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001915 mAwaitedFocusedApplication = focusedApplicationHandle;
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05001916 mAwaitedApplicationDisplayId = displayId;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001917 ALOGW("Waiting because no window has focus but %s may eventually add a "
1918 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001919 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001920 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001921 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001922 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1923 // Already raised ANR. Drop the event
1924 ALOGE("Dropping %s event because there is no focused window",
Dominik Laskowski75788452021-02-09 18:51:25 -08001925 ftl::enum_string(entry.type).c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001926 return InputEventInjectionResult::FAILED;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001927 } else {
1928 // Still waiting for the focused window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001929 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001930 }
1931 }
1932
1933 // we have a valid, non-null focused window
1934 resetNoFocusedWindowTimeoutLocked();
1935
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00001936 // Verify targeted injection.
1937 if (const auto err = verifyTargetedInjection(focusedWindowHandle, entry); err) {
1938 ALOGW("Dropping injected event: %s", (*err).c_str());
1939 return InputEventInjectionResult::TARGET_MISMATCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 }
1941
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001942 if (focusedWindowHandle->getInfo()->inputConfig.test(
1943 WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001944 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001945 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001946 }
1947
1948 // If the event is a key event, then we must wait for all previous events to
1949 // complete before delivering it because previous events may have the
1950 // side-effect of transferring focus to a different window and we want to
1951 // ensure that the following keys are sent to the new window.
1952 //
1953 // Suppose the user touches a button in a window then immediately presses "A".
1954 // If the button causes a pop-up window to appear then we want to ensure that
1955 // the "A" key is delivered to the new pop-up window. This is because users
1956 // often anticipate pending UI changes when typing on a keyboard.
1957 // To obtain this behavior, we must serialize key events with respect to all
1958 // prior input events.
1959 if (entry.type == EventEntry::Type::KEY) {
1960 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1961 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001962 return InputEventInjectionResult::PENDING;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001963 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 }
1965
1966 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001967 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001968 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1969 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970
1971 // Done.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001972 return InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973}
1974
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001975/**
1976 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1977 * that are currently unresponsive.
1978 */
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001979std::vector<Monitor> InputDispatcher::selectResponsiveMonitorsLocked(
1980 const std::vector<Monitor>& monitors) const {
1981 std::vector<Monitor> responsiveMonitors;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001982 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001983 [this](const Monitor& monitor) REQUIRES(mLock) {
1984 sp<Connection> connection =
1985 getConnectionLocked(monitor.inputChannel->getConnectionToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001986 if (connection == nullptr) {
1987 ALOGE("Could not find connection for monitor %s",
Prabir Pradhan0a99c922021-09-03 08:27:53 -07001988 monitor.inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001989 return false;
1990 }
1991 if (!connection->responsive) {
1992 ALOGW("Unresponsive monitor %s will not get the new gesture",
1993 connection->inputChannel->getName().c_str());
1994 return false;
1995 }
1996 return true;
1997 });
1998 return responsiveMonitors;
1999}
2000
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002001InputEventInjectionResult InputDispatcher::findTouchedWindowTargetsLocked(
2002 nsecs_t currentTime, const MotionEntry& entry, std::vector<InputTarget>& inputTargets,
2003 nsecs_t* nextWakeupTime, bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002004 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 // For security reasons, we defer updating the touch state until we are sure that
2007 // event injection will be allowed.
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002008 const int32_t displayId = entry.displayId;
2009 const int32_t action = entry.action;
2010 const int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011
2012 // Update the touch state as needed based on the properties of the touch event.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002013 InputEventInjectionResult injectionResult = InputEventInjectionResult::PENDING;
chaviw98318de2021-05-19 16:45:23 -05002014 sp<WindowInfoHandle> newHoverWindowHandle(mLastHoverWindowHandle);
2015 sp<WindowInfoHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002017 // Copy current touch state into tempTouchState.
2018 // This state will be used to update mTouchStatesByDisplay at the end of this function.
2019 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07002020 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002021 TouchState tempTouchState;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002022 if (const auto it = mTouchStatesByDisplay.find(displayId); it != mTouchStatesByDisplay.end()) {
2023 oldState = &(it->second);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08002024 tempTouchState = *oldState;
Jeff Brownf086ddb2014-02-11 14:28:48 -08002025 }
2026
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002027 bool isSplit = tempTouchState.split;
2028 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
2029 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
2030 tempTouchState.displayId != displayId);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002031
2032 const bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
2033 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2034 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
2035 const bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
2036 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07002037 const bool isFromMouse = isFromSource(entry.source, AINPUT_SOURCE_MOUSE);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 bool wrongDevice = false;
2039 if (newGesture) {
2040 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002041 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002042 ALOGI("Dropping event because a pointer for a different device is already down "
2043 "in display %" PRId32,
2044 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002045 // TODO: test multiple simultaneous input streams.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002046 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 switchedDevice = false;
2048 wrongDevice = true;
2049 goto Failed;
2050 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002051 tempTouchState.reset();
2052 tempTouchState.down = down;
2053 tempTouchState.deviceId = entry.deviceId;
2054 tempTouchState.source = entry.source;
2055 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002057 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07002058 ALOGI("Dropping move event because a pointer for a different device is already active "
2059 "in display %" PRId32,
2060 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002061 // TODO: test multiple simultaneous input streams.
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002062 injectionResult = InputEventInjectionResult::FAILED;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04002063 switchedDevice = false;
2064 wrongDevice = true;
2065 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066 }
2067
2068 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
2069 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
2070
Prabir Pradhandb326da2023-03-09 04:51:55 +00002071 float x;
2072 float y;
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002073 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07002074 // Always dispatch mouse events to cursor position.
2075 if (isFromMouse) {
Prabir Pradhandb326da2023-03-09 04:51:55 +00002076 x = entry.xCursorPosition;
2077 y = entry.yCursorPosition;
Garfield Tan00f511d2019-06-12 16:55:40 -07002078 } else {
Prabir Pradhandb326da2023-03-09 04:51:55 +00002079 x = entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X);
2080 y = entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y);
Garfield Tan00f511d2019-06-12 16:55:40 -07002081 }
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002082 const bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Prabir Pradhand65552b2021-10-07 11:23:50 -07002083 const bool isStylus = isPointerFromStylus(entry, pointerIndex);
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002084 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
Prabir Pradhand65552b2021-10-07 11:23:50 -07002085 isStylus, isDown /*addOutsideTargets*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00002086
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07002088 if (newTouchedWindowHandle == nullptr) {
Prabir Pradhandb326da2023-03-09 04:51:55 +00002089 ALOGD("No new touched window at (%.1f, %.1f) in display %" PRId32, x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002091 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002092 }
2093
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002094 // Verify targeted injection.
2095 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2096 ALOGW("Dropping injected touch event: %s", (*err).c_str());
2097 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2098 newTouchedWindowHandle = nullptr;
2099 goto Failed;
2100 }
2101
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002102 // Figure out whether splitting will be allowed for this window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002103 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002104 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
2105 // New window supports splitting, but we should never split mouse events.
2106 isSplit = !isFromMouse;
2107 } else if (isSplit) {
2108 // New window does not support splitting but we have already split events.
2109 // Ignore the new window.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002110 newTouchedWindowHandle = nullptr;
2111 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002112 } else {
2113 // No window is touched, so set split to true. This will allow the next pointer down to
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002114 // be delivered to a new window which supports split touch. Pointers from a mouse device
2115 // should never be split.
2116 tempTouchState.split = isSplit = !isFromMouse;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002117 }
2118
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002119 // Update hover state.
Michael Wright3dd60e22019-03-27 22:06:44 +00002120 if (newTouchedWindowHandle != nullptr) {
Garfield Tandf26e862020-07-01 20:18:19 -07002121 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
2122 newHoverWindowHandle = nullptr;
2123 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002124 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00002125 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002126 }
2127
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002128 std::vector<sp<WindowInfoHandle>> newTouchedWindows =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002129 findTouchedSpyWindowsAtLocked(displayId, x, y, isStylus);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002130 if (newTouchedWindowHandle != nullptr) {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002131 // Process the foreground window first so that it is the first to receive the event.
2132 newTouchedWindows.insert(newTouchedWindows.begin(), newTouchedWindowHandle);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002133 }
2134
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002135 if (newTouchedWindows.empty()) {
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00002136 ALOGI("Dropping event because there is no touchable window at (%.1f, %.1f) on display "
2137 "%d.",
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002138 x, y, displayId);
2139 injectionResult = InputEventInjectionResult::FAILED;
2140 goto Failed;
2141 }
2142
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002143 for (const sp<WindowInfoHandle>& windowHandle : newTouchedWindows) {
2144 const WindowInfo& info = *windowHandle->getInfo();
2145
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002146 // Skip spy window targets that are not valid for targeted injection.
2147 if (const auto err = verifyTargetedInjection(windowHandle, entry); err) {
2148 continue;
2149 }
2150
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002151 if (info.inputConfig.test(WindowInfo::InputConfig::PAUSE_DISPATCHING)) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002152 ALOGI("Not sending touch event to %s because it is paused",
2153 windowHandle->getName().c_str());
2154 continue;
2155 }
2156
2157 // Ensure the window has a connection and the connection is responsive
2158 const bool isResponsive = hasResponsiveConnectionLocked(*windowHandle);
2159 if (!isResponsive) {
2160 ALOGW("Not sending touch gesture to %s because it is not responsive",
2161 windowHandle->getName().c_str());
2162 continue;
2163 }
2164
2165 // Drop events that can't be trusted due to occlusion
2166 if (mBlockUntrustedTouchesMode != BlockUntrustedTouchesMode::DISABLED) {
2167 TouchOcclusionInfo occlusionInfo =
2168 computeTouchOcclusionInfoLocked(windowHandle, x, y);
2169 if (!isTouchTrustedLocked(occlusionInfo)) {
2170 if (DEBUG_TOUCH_OCCLUSION) {
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00002171 ALOGD("Stack of obscuring windows during untrusted touch (%.1f, %.1f):", x,
2172 y);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002173 for (const auto& log : occlusionInfo.debugInfo) {
2174 ALOGD("%s", log.c_str());
2175 }
2176 }
2177 sendUntrustedTouchCommandLocked(occlusionInfo.obscuringPackage);
2178 if (mBlockUntrustedTouchesMode == BlockUntrustedTouchesMode::BLOCK) {
2179 ALOGW("Dropping untrusted touch event due to %s/%d",
2180 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid);
2181 continue;
2182 }
2183 }
2184 }
2185
2186 // Drop touch events if requested by input feature
2187 if (shouldDropInput(entry, windowHandle)) {
2188 continue;
2189 }
2190
2191 // Set target flags.
2192 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_IS;
2193
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002194 if (canReceiveForegroundTouches(*windowHandle->getInfo())) {
2195 // There should only be one touched window that can be "foreground" for the pointer.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08002196 targetFlags |= InputTarget::FLAG_FOREGROUND;
2197 }
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002198
2199 if (isSplit) {
2200 targetFlags |= InputTarget::FLAG_SPLIT;
2201 }
2202 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
2203 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
2204 } else if (isWindowObscuredLocked(windowHandle)) {
2205 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2206 }
Michael Wright3dd60e22019-03-27 22:06:44 +00002207
2208 // Update the temporary touch state.
2209 BitSet32 pointerIds;
Arthur Hung02701602022-07-15 09:35:36 +00002210 pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002211
2212 tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 } else {
2215 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
2216
2217 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002218 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002219 if (DEBUG_FOCUS) {
2220 ALOGD("Dropping event because the pointer is not down or we previously "
2221 "dropped the pointer down event in display %" PRId32,
2222 displayId);
2223 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002224 injectionResult = InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 goto Failed;
2226 }
2227
arthurhung6d4bed92021-03-17 11:59:33 +08002228 addDragEventLocked(entry);
arthurhungb89ccb02020-12-30 16:19:01 +08002229
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002231 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002232 tempTouchState.isSlippery()) {
Prabir Pradhandb326da2023-03-09 04:51:55 +00002233 const float x = entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X);
2234 const float y = entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235
Prabir Pradhand65552b2021-10-07 11:23:50 -07002236 const bool isStylus = isPointerFromStylus(entry, 0 /*pointerIndex*/);
chaviw98318de2021-05-19 16:45:23 -05002237 sp<WindowInfoHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002238 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhand65552b2021-10-07 11:23:50 -07002239 newTouchedWindowHandle =
2240 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState, isStylus);
Vishnu Nair062a8672021-09-03 16:07:44 -07002241
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002242 // Verify targeted injection.
2243 if (const auto err = verifyTargetedInjection(newTouchedWindowHandle, entry); err) {
2244 ALOGW("Dropping injected event: %s", (*err).c_str());
2245 injectionResult = os::InputEventInjectionResult::TARGET_MISMATCH;
2246 newTouchedWindowHandle = nullptr;
2247 goto Failed;
2248 }
2249
Vishnu Nair062a8672021-09-03 16:07:44 -07002250 // Drop touch events if requested by input feature
2251 if (newTouchedWindowHandle != nullptr &&
2252 shouldDropInput(entry, newTouchedWindowHandle)) {
2253 newTouchedWindowHandle = nullptr;
2254 }
2255
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002256 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
2257 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002258 if (DEBUG_FOCUS) {
2259 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
2260 oldTouchedWindowHandle->getName().c_str(),
2261 newTouchedWindowHandle->getName().c_str(), displayId);
2262 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002264 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
2265 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
2266 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267
2268 // Make a slippery entrance into the new window.
2269 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Prabir Pradhan713bb3e2021-12-20 02:07:40 -08002270 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 }
2272
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002273 int32_t targetFlags = InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
2274 if (canReceiveForegroundTouches(*newTouchedWindowHandle->getInfo())) {
2275 targetFlags |= InputTarget::FLAG_FOREGROUND;
2276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 if (isSplit) {
2278 targetFlags |= InputTarget::FLAG_SPLIT;
2279 }
2280 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
2281 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002282 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
2283 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 }
2285
2286 BitSet32 pointerIds;
Arthur Hung02701602022-07-15 09:35:36 +00002287 pointerIds.markBit(entry.pointerProperties[0].id);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002288 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 }
2290 }
Arthur Hung45f24342022-11-15 03:30:48 +00002291
2292 // Update the pointerIds for non-splittable when it received pointer down.
2293 if (!isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
2294 // If no split, we suppose all touched windows should receive pointer down.
2295 const int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2296 for (size_t i = 0; i < tempTouchState.windows.size(); i++) {
2297 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2298 // Ignore drag window for it should just track one pointer.
2299 if (mDragState && mDragState->dragWindow == touchedWindow.windowHandle) {
2300 continue;
2301 }
2302 touchedWindow.pointerIds.markBit(entry.pointerProperties[pointerIndex].id);
2303 }
2304 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
2306
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002307 // Update dispatching for hover enter and exit.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Prabir Pradhan3f90d312021-11-19 03:57:24 -08002309 // Let the previous window know that the hover sequence is over, unless we already did
2310 // it when dispatching it as is to newTouchedWindowHandle.
Garfield Tandf26e862020-07-01 20:18:19 -07002311 if (mLastHoverWindowHandle != nullptr &&
2312 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
2313 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002314 if (DEBUG_HOVER) {
2315 ALOGD("Sending hover exit event to window %s.",
2316 mLastHoverWindowHandle->getName().c_str());
2317 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002318 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
2319 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 }
2321
Garfield Tandf26e862020-07-01 20:18:19 -07002322 // Let the new window know that the hover sequence is starting, unless we already did it
2323 // when dispatching it as is to newTouchedWindowHandle.
2324 if (newHoverWindowHandle != nullptr &&
2325 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
2326 newHoverWindowHandle != newTouchedWindowHandle)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002327 if (DEBUG_HOVER) {
2328 ALOGD("Sending hover enter event to window %s.",
2329 newHoverWindowHandle->getName().c_str());
2330 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002331 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
2332 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
2333 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 }
2335 }
2336
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002337 // Ensure that we have at least one foreground window or at least one window that cannot be a
2338 // foreground target. If we only have windows that are not receiving foreground touches (e.g. we
2339 // only have windows getting ACTION_OUTSIDE), then drop the event, because there is no window
2340 // that is actually receiving the entire gesture.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002341 if (std::none_of(tempTouchState.windows.begin(), tempTouchState.windows.end(),
2342 [](const TouchedWindow& touchedWindow) {
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00002343 return !canReceiveForegroundTouches(
2344 *touchedWindow.windowHandle->getInfo()) ||
2345 (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) != 0;
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002346 })) {
Siarhei Vishniakou1fb18912022-03-08 10:31:39 -08002347 ALOGI("Dropping event because there is no touched window on display %d to receive it: %s",
2348 displayId, entry.getDescription().c_str());
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002349 injectionResult = InputEventInjectionResult::FAILED;
2350 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 }
2352
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00002353 // Ensure that all touched windows are valid for injection.
2354 if (entry.injectionState != nullptr) {
2355 std::string errs;
2356 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
2357 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2358 // Allow ACTION_OUTSIDE events generated by targeted injection to be
2359 // dispatched to any uid, since the coords will be zeroed out later.
2360 continue;
2361 }
2362 const auto err = verifyTargetedInjection(touchedWindow.windowHandle, entry);
2363 if (err) errs += "\n - " + *err;
2364 }
2365 if (!errs.empty()) {
2366 ALOGW("Dropping targeted injection: At least one touched window is not owned by uid "
2367 "%d:%s",
2368 *entry.injectionState->targetUid, errs.c_str());
2369 injectionResult = InputEventInjectionResult::TARGET_MISMATCH;
2370 goto Failed;
2371 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002372 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002373
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 // Check whether windows listening for outside touches are owned by the same UID. If it is
2375 // set the policy flag that we will not reveal coordinate information to this window.
2376 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002377 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002378 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00002379 if (foregroundWindowHandle) {
2380 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002381 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002382 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
chaviw98318de2021-05-19 16:45:23 -05002383 sp<WindowInfoHandle> windowInfoHandle = touchedWindow.windowHandle;
2384 if (windowInfoHandle->getInfo()->ownerUid != foregroundWindowUid) {
2385 tempTouchState.addOrUpdateWindow(windowInfoHandle,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002386 InputTarget::FLAG_ZERO_COORDS,
2387 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00002388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 }
2390 }
2391 }
2392 }
2393
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 // If this is the first pointer going down and the touched window has a wallpaper
2395 // then also add the touched wallpaper windows so they are locked in for the duration
2396 // of the touch gesture.
2397 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
2398 // engine only supports touch events. We would need to add a mechanism similar
2399 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
2400 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
chaviw98318de2021-05-19 16:45:23 -05002401 sp<WindowInfoHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002402 tempTouchState.getFirstForegroundWindowHandle();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002403 if (foregroundWindowHandle &&
2404 foregroundWindowHandle->getInfo()->inputConfig.test(
2405 WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
chaviw98318de2021-05-19 16:45:23 -05002406 const std::vector<sp<WindowInfoHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002407 getWindowHandlesLocked(displayId);
chaviw98318de2021-05-19 16:45:23 -05002408 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
2409 const WindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002410 if (info->displayId == displayId &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002411 windowHandle->getInfo()->inputConfig.test(
2412 WindowInfo::InputConfig::IS_WALLPAPER)) {
Arthur Hung45f24342022-11-15 03:30:48 +00002413 BitSet32 pointerIds;
2414 pointerIds.markBit(entry.pointerProperties[0].id);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002415 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002416 .addOrUpdateWindow(windowHandle,
2417 InputTarget::FLAG_WINDOW_IS_OBSCURED |
2418 InputTarget::
2419 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
2420 InputTarget::FLAG_DISPATCH_AS_IS,
Arthur Hung45f24342022-11-15 03:30:48 +00002421 pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
2423 }
2424 }
2425 }
2426
2427 // Success! Output targets.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002428 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002430 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002432 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 }
2434
2435 // Drop the outside or hover touch windows since we will not care about them
2436 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07002437 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438
2439Failed:
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002441 if (!wrongDevice) {
2442 if (switchedDevice) {
2443 if (DEBUG_FOCUS) {
2444 ALOGD("Conflicting pointer actions: Switched to a different device.");
2445 }
2446 *outConflictingPointerActions = true;
2447 }
2448
2449 if (isHoverAction) {
2450 // Started hovering, therefore no longer down.
2451 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002452 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002453 ALOGD("Conflicting pointer actions: Hover received while pointer was "
2454 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002455 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456 *outConflictingPointerActions = true;
2457 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002458 tempTouchState.reset();
2459 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
2460 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
2461 tempTouchState.deviceId = entry.deviceId;
2462 tempTouchState.source = entry.source;
2463 tempTouchState.displayId = displayId;
2464 }
2465 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
2466 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
2467 // All pointers up or canceled.
2468 tempTouchState.reset();
2469 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
2470 // First pointer went down.
2471 if (oldState && oldState->down) {
2472 if (DEBUG_FOCUS) {
2473 ALOGD("Conflicting pointer actions: Down received while already down.");
2474 }
2475 *outConflictingPointerActions = true;
2476 }
2477 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2478 // One pointer went up.
Arthur Hung02701602022-07-15 09:35:36 +00002479 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
2480 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481
Arthur Hung02701602022-07-15 09:35:36 +00002482 for (size_t i = 0; i < tempTouchState.windows.size();) {
2483 TouchedWindow& touchedWindow = tempTouchState.windows[i];
2484 touchedWindow.pointerIds.clearBit(pointerId);
2485 if (touchedWindow.pointerIds.isEmpty()) {
2486 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
2487 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 }
Arthur Hung02701602022-07-15 09:35:36 +00002489 i += 1;
2490 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002491 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08002492
Siarhei Vishniakou767917f2020-03-24 20:49:09 -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) {
2496 if (tempTouchState.displayId >= 0) {
2497 mTouchStatesByDisplay[displayId] = tempTouchState;
2498 } else {
2499 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002501 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07002503 // Update hover state.
2504 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 }
2506
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507 return injectionResult;
2508}
2509
arthurhung6d4bed92021-03-17 11:59:33 +08002510void InputDispatcher::finishDragAndDrop(int32_t displayId, float x, float y) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07002511 // Prevent stylus interceptor windows from affecting drag and drop behavior for now, until we
2512 // have an explicit reason to support it.
2513 constexpr bool isStylus = false;
2514
chaviw98318de2021-05-19 16:45:23 -05002515 const sp<WindowInfoHandle> dropWindow =
Prabir Pradhand65552b2021-10-07 11:23:50 -07002516 findTouchedWindowAtLocked(displayId, x, y, nullptr /*touchState*/, isStylus,
Siarhei Vishniakou64452932020-11-06 17:51:32 -06002517 false /*addOutsideTargets*/, true /*ignoreDragWindow*/);
arthurhung6d4bed92021-03-17 11:59:33 +08002518 if (dropWindow) {
2519 vec2 local = dropWindow->getInfo()->transform.transform(x, y);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002520 sendDropWindowCommandLocked(dropWindow->getToken(), local.x, local.y);
Arthur Hung6d0571e2021-04-09 20:18:16 +08002521 } else {
Arthur Hung54745652022-04-20 07:17:41 +00002522 ALOGW("No window found when drop.");
Prabir Pradhancef936d2021-07-21 16:17:52 +00002523 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002524 }
2525 mDragState.reset();
2526}
2527
2528void InputDispatcher::addDragEventLocked(const MotionEntry& entry) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00002529 if (!mDragState || mDragState->dragWindow->getInfo()->displayId != entry.displayId) {
arthurhungb89ccb02020-12-30 16:19:01 +08002530 return;
2531 }
2532
arthurhung6d4bed92021-03-17 11:59:33 +08002533 if (!mDragState->isStartDrag) {
2534 mDragState->isStartDrag = true;
2535 mDragState->isStylusButtonDownAtStart =
2536 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2537 }
2538
Arthur Hung54745652022-04-20 07:17:41 +00002539 // Find the pointer index by id.
2540 int32_t pointerIndex = 0;
2541 for (; static_cast<uint32_t>(pointerIndex) < entry.pointerCount; pointerIndex++) {
2542 const PointerProperties& pointerProperties = entry.pointerProperties[pointerIndex];
2543 if (pointerProperties.id == mDragState->pointerId) {
2544 break;
arthurhung6d4bed92021-03-17 11:59:33 +08002545 }
Arthur Hung54745652022-04-20 07:17:41 +00002546 }
arthurhung6d4bed92021-03-17 11:59:33 +08002547
Arthur Hung54745652022-04-20 07:17:41 +00002548 if (uint32_t(pointerIndex) == entry.pointerCount) {
2549 LOG_ALWAYS_FATAL("Should find a valid pointer index by id %d", mDragState->pointerId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00002550 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08002551 mDragState.reset();
Arthur Hung54745652022-04-20 07:17:41 +00002552 return;
2553 }
2554
2555 const int32_t maskedAction = entry.action & AMOTION_EVENT_ACTION_MASK;
Prabir Pradhandb326da2023-03-09 04:51:55 +00002556 const float x = entry.pointerCoords[pointerIndex].getX();
2557 const float y = entry.pointerCoords[pointerIndex].getY();
Arthur Hung54745652022-04-20 07:17:41 +00002558
2559 switch (maskedAction) {
2560 case AMOTION_EVENT_ACTION_MOVE: {
2561 // Handle the special case : stylus button no longer pressed.
2562 bool isStylusButtonDown =
2563 (entry.buttonState & AMOTION_EVENT_BUTTON_STYLUS_PRIMARY) != 0;
2564 if (mDragState->isStylusButtonDownAtStart && !isStylusButtonDown) {
2565 finishDragAndDrop(entry.displayId, x, y);
2566 return;
2567 }
2568
2569 // Prevent stylus interceptor windows from affecting drag and drop behavior for now,
2570 // until we have an explicit reason to support it.
2571 constexpr bool isStylus = false;
2572
2573 const sp<WindowInfoHandle> hoverWindowHandle =
2574 findTouchedWindowAtLocked(entry.displayId, x, y, nullptr /*touchState*/,
2575 isStylus, false /*addOutsideTargets*/,
2576 true /*ignoreDragWindow*/);
2577 // enqueue drag exit if needed.
2578 if (hoverWindowHandle != mDragState->dragHoverWindowHandle &&
2579 !haveSameToken(hoverWindowHandle, mDragState->dragHoverWindowHandle)) {
2580 if (mDragState->dragHoverWindowHandle != nullptr) {
2581 enqueueDragEventLocked(mDragState->dragHoverWindowHandle, true /*isExiting*/, x,
2582 y);
2583 }
2584 mDragState->dragHoverWindowHandle = hoverWindowHandle;
2585 }
2586 // enqueue drag location if needed.
2587 if (hoverWindowHandle != nullptr) {
2588 enqueueDragEventLocked(hoverWindowHandle, false /*isExiting*/, x, y);
2589 }
2590 break;
2591 }
2592
2593 case AMOTION_EVENT_ACTION_POINTER_UP:
2594 if (getMotionEventActionPointerIndex(entry.action) != pointerIndex) {
2595 break;
2596 }
2597 // The drag pointer is up.
2598 [[fallthrough]];
2599 case AMOTION_EVENT_ACTION_UP:
2600 finishDragAndDrop(entry.displayId, x, y);
2601 break;
2602 case AMOTION_EVENT_ACTION_CANCEL: {
2603 ALOGD("Receiving cancel when drag and drop.");
2604 sendDropWindowCommandLocked(nullptr, 0, 0);
2605 mDragState.reset();
2606 break;
2607 }
arthurhungb89ccb02020-12-30 16:19:01 +08002608 }
2609}
2610
chaviw98318de2021-05-19 16:45:23 -05002611void InputDispatcher::addWindowTargetLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002612 int32_t targetFlags, BitSet32 pointerIds,
2613 std::vector<InputTarget>& inputTargets) {
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;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002634 const auto& displayInfoIt = mDisplayInfos.find(windowInfo->displayId);
2635 if (displayInfoIt != mDisplayInfos.end()) {
Prabir Pradhanb9b18502021-08-26 12:30:32 -07002636 inputTarget.displayTransform = displayInfoIt->second.transform;
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002637 } else {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00002638 ALOGE("DisplayInfo not found for window on display: %d", windowInfo->displayId);
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07002639 }
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002640 inputTargets.push_back(inputTarget);
2641 it = inputTargets.end() - 1;
2642 }
2643
2644 ALOG_ASSERT(it->flags == targetFlags);
2645 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
2646
chaviw1ff3d1e2020-07-01 15:53:47 -07002647 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648}
2649
Michael Wright3dd60e22019-03-27 22:06:44 +00002650void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Prabir Pradhan0a99c922021-09-03 08:27:53 -07002651 int32_t displayId) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002652 auto monitorsIt = mGlobalMonitorsByDisplay.find(displayId);
2653 if (monitorsIt == mGlobalMonitorsByDisplay.end()) return;
Michael Wright3dd60e22019-03-27 22:06:44 +00002654
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002655 for (const Monitor& monitor : selectResponsiveMonitorsLocked(monitorsIt->second)) {
2656 InputTarget target;
2657 target.inputChannel = monitor.inputChannel;
2658 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2659 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
2660 target.displayTransform = it->second.transform;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002661 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002662 target.setDefaultPointerTransform(target.displayTransform);
2663 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664 }
2665}
2666
Robert Carrc9bf1d32020-04-13 17:21:08 -07002667/**
2668 * Indicate whether one window handle should be considered as obscuring
2669 * another window handle. We only check a few preconditions. Actually
2670 * checking the bounds is left to the caller.
2671 */
chaviw98318de2021-05-19 16:45:23 -05002672static bool canBeObscuredBy(const sp<WindowInfoHandle>& windowHandle,
2673 const sp<WindowInfoHandle>& otherHandle) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002674 // Compare by token so cloned layers aren't counted
2675 if (haveSameToken(windowHandle, otherHandle)) {
2676 return false;
2677 }
2678 auto info = windowHandle->getInfo();
2679 auto otherInfo = otherHandle->getInfo();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002680 if (otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002681 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002682 } else if (otherInfo->alpha == 0 &&
2683 otherInfo->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE)) {
Bernardo Rufino653d2e02020-10-20 17:32:40 +00002684 // Those act as if they were invisible, so we don't need to flag them.
2685 // We do want to potentially flag touchable windows even if they have 0
2686 // opacity, since they can consume touches and alter the effects of the
2687 // user interaction (eg. apps that rely on
2688 // FLAG_WINDOW_IS_PARTIALLY_OBSCURED should still be told about those
2689 // windows), hence we also check for FLAG_NOT_TOUCHABLE.
2690 return false;
Bernardo Rufino8007daf2020-09-22 09:40:01 +00002691 } else if (info->ownerUid == otherInfo->ownerUid) {
2692 // If ownerUid is the same we don't generate occlusion events as there
2693 // is no security boundary within an uid.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002694 return false;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002695 } else if (otherInfo->inputConfig.test(gui::WindowInfo::InputConfig::TRUSTED_OVERLAY)) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002696 return false;
2697 } else if (otherInfo->displayId != info->displayId) {
2698 return false;
2699 }
2700 return true;
2701}
2702
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002703/**
2704 * Returns touch occlusion information in the form of TouchOcclusionInfo. To check if the touch is
2705 * untrusted, one should check:
2706 *
2707 * 1. If result.hasBlockingOcclusion is true.
2708 * If it's, it means the touch should be blocked due to a window with occlusion mode of
2709 * BLOCK_UNTRUSTED.
2710 *
2711 * 2. If result.obscuringOpacity > mMaximumObscuringOpacityForTouch.
2712 * If it is (and 1 is false), then the touch should be blocked because a stack of windows
2713 * (possibly only one) with occlusion mode of USE_OPACITY from one UID resulted in a composed
2714 * obscuring opacity above the threshold. Note that if there was no window of occlusion mode
2715 * USE_OPACITY, result.obscuringOpacity would've been 0 and since
2716 * mMaximumObscuringOpacityForTouch >= 0, the condition above would never be true.
2717 *
2718 * If neither of those is true, then it means the touch can be allowed.
2719 */
2720InputDispatcher::TouchOcclusionInfo InputDispatcher::computeTouchOcclusionInfoLocked(
chaviw98318de2021-05-19 16:45:23 -05002721 const sp<WindowInfoHandle>& windowHandle, int32_t x, int32_t y) const {
2722 const WindowInfo* windowInfo = windowHandle->getInfo();
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002723 int32_t displayId = windowInfo->displayId;
chaviw98318de2021-05-19 16:45:23 -05002724 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002725 TouchOcclusionInfo info;
2726 info.hasBlockingOcclusion = false;
2727 info.obscuringOpacity = 0;
2728 info.obscuringUid = -1;
2729 std::map<int32_t, float> opacityByUid;
chaviw98318de2021-05-19 16:45:23 -05002730 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002731 if (windowHandle == otherHandle) {
2732 break; // All future windows are below us. Exit early.
2733 }
chaviw98318de2021-05-19 16:45:23 -05002734 const WindowInfo* otherInfo = otherHandle->getInfo();
Bernardo Rufino1ff9d592021-01-18 16:58:57 +00002735 if (canBeObscuredBy(windowHandle, otherHandle) && otherInfo->frameContainsPoint(x, y) &&
2736 !haveSameApplicationToken(windowInfo, otherInfo)) {
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002737 if (DEBUG_TOUCH_OCCLUSION) {
2738 info.debugInfo.push_back(
2739 dumpWindowForTouchOcclusion(otherInfo, /* isTouchedWindow */ false));
2740 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002741 // canBeObscuredBy() has returned true above, which means this window is untrusted, so
2742 // we perform the checks below to see if the touch can be propagated or not based on the
2743 // window's touch occlusion mode
2744 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::BLOCK_UNTRUSTED) {
2745 info.hasBlockingOcclusion = true;
2746 info.obscuringUid = otherInfo->ownerUid;
2747 info.obscuringPackage = otherInfo->packageName;
2748 break;
2749 }
2750 if (otherInfo->touchOcclusionMode == TouchOcclusionMode::USE_OPACITY) {
2751 uint32_t uid = otherInfo->ownerUid;
2752 float opacity =
2753 (opacityByUid.find(uid) == opacityByUid.end()) ? 0 : opacityByUid[uid];
2754 // Given windows A and B:
2755 // opacity(A, B) = 1 - [1 - opacity(A)] * [1 - opacity(B)]
2756 opacity = 1 - (1 - opacity) * (1 - otherInfo->alpha);
2757 opacityByUid[uid] = opacity;
2758 if (opacity > info.obscuringOpacity) {
2759 info.obscuringOpacity = opacity;
2760 info.obscuringUid = uid;
2761 info.obscuringPackage = otherInfo->packageName;
2762 }
2763 }
2764 }
2765 }
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002766 if (DEBUG_TOUCH_OCCLUSION) {
2767 info.debugInfo.push_back(
2768 dumpWindowForTouchOcclusion(windowInfo, /* isTouchedWindow */ true));
2769 }
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002770 return info;
2771}
2772
chaviw98318de2021-05-19 16:45:23 -05002773std::string InputDispatcher::dumpWindowForTouchOcclusion(const WindowInfo* info,
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002774 bool isTouchedWindow) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002775 return StringPrintf(INDENT2 "* %spackage=%s/%" PRId32 ", id=%" PRId32 ", mode=%s, alpha=%.2f, "
2776 "frame=[%" PRId32 ",%" PRId32 "][%" PRId32 ",%" PRId32
2777 "], touchableRegion=%s, window={%s}, inputConfig={%s}, "
2778 "hasToken=%s, applicationInfo.name=%s, applicationInfo.token=%s\n",
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002779 isTouchedWindow ? "[TOUCHED] " : "", info->packageName.c_str(),
2780 info->ownerUid, info->id, toString(info->touchOcclusionMode).c_str(),
2781 info->alpha, info->frameLeft, info->frameTop, info->frameRight,
2782 info->frameBottom, dumpRegion(info->touchableRegion).c_str(),
2783 info->name.c_str(), info->inputConfig.string().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002784 toString(info->token != nullptr), info->applicationInfo.name.c_str(),
Bernardo Rufino49d99e42021-01-18 15:16:59 +00002785 toString(info->applicationInfo.token).c_str());
Bernardo Rufino4bae0ac2020-10-14 18:33:46 +00002786}
2787
Bernardo Rufinoea97d182020-08-19 14:43:14 +01002788bool InputDispatcher::isTouchTrustedLocked(const TouchOcclusionInfo& occlusionInfo) const {
2789 if (occlusionInfo.hasBlockingOcclusion) {
2790 ALOGW("Untrusted touch due to occlusion by %s/%d", occlusionInfo.obscuringPackage.c_str(),
2791 occlusionInfo.obscuringUid);
2792 return false;
2793 }
2794 if (occlusionInfo.obscuringOpacity > mMaximumObscuringOpacityForTouch) {
2795 ALOGW("Untrusted touch due to occlusion by %s/%d (obscuring opacity = "
2796 "%.2f, maximum allowed = %.2f)",
2797 occlusionInfo.obscuringPackage.c_str(), occlusionInfo.obscuringUid,
2798 occlusionInfo.obscuringOpacity, mMaximumObscuringOpacityForTouch);
2799 return false;
2800 }
2801 return true;
2802}
2803
chaviw98318de2021-05-19 16:45:23 -05002804bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<WindowInfoHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002805 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002807 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2808 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002809 if (windowHandle == otherHandle) {
2810 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811 }
chaviw98318de2021-05-19 16:45:23 -05002812 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002813 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002814 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 return true;
2816 }
2817 }
2818 return false;
2819}
2820
chaviw98318de2021-05-19 16:45:23 -05002821bool InputDispatcher::isWindowObscuredLocked(const sp<WindowInfoHandle>& windowHandle) const {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002822 int32_t displayId = windowHandle->getInfo()->displayId;
chaviw98318de2021-05-19 16:45:23 -05002823 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
2824 const WindowInfo* windowInfo = windowHandle->getInfo();
2825 for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002826 if (windowHandle == otherHandle) {
2827 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002828 }
chaviw98318de2021-05-19 16:45:23 -05002829 const WindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002830 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002831 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002832 return true;
2833 }
2834 }
2835 return false;
2836}
2837
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002838std::string InputDispatcher::getApplicationWindowLabel(
chaviw98318de2021-05-19 16:45:23 -05002839 const InputApplicationHandle* applicationHandle, const sp<WindowInfoHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002840 if (applicationHandle != nullptr) {
2841 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002842 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 } else {
2844 return applicationHandle->getName();
2845 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002846 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002847 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002849 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 }
2851}
2852
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002853void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00002854 if (!isUserActivityEvent(eventEntry)) {
2855 // Not poking user activity if the event type does not represent a user activity
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002856 return;
2857 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002858 int32_t displayId = getTargetDisplayId(eventEntry);
chaviw98318de2021-05-19 16:45:23 -05002859 sp<WindowInfoHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002860 if (focusedWindowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05002861 const WindowInfo* info = focusedWindowHandle->getInfo();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08002862 if (info->inputConfig.test(WindowInfo::InputConfig::DISABLE_USER_ACTIVITY)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002863 if (DEBUG_DISPATCH_CYCLE) {
2864 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
2865 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 return;
2867 }
2868 }
2869
2870 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002871 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002872 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002873 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2874 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002875 return;
2876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002878 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002879 eventType = USER_ACTIVITY_EVENT_TOUCH;
2880 }
2881 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002883 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002884 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2885 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002886 return;
2887 }
2888 eventType = USER_ACTIVITY_EVENT_BUTTON;
2889 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00002891 default: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002892 LOG_ALWAYS_FATAL("%s events are not user activity",
Dominik Laskowski75788452021-02-09 18:51:25 -08002893 ftl::enum_string(eventEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002894 break;
2895 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002896 }
2897
Prabir Pradhancef936d2021-07-21 16:17:52 +00002898 auto command = [this, eventTime = eventEntry.eventTime, eventType, displayId]()
2899 REQUIRES(mLock) {
2900 scoped_unlock unlock(mLock);
2901 mPolicy->pokeUserActivity(eventTime, eventType, displayId);
2902 };
2903 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904}
2905
2906void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002907 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002908 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002909 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002910 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002911 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002912 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002913 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002914 ATRACE_NAME(message.c_str());
2915 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002916 if (DEBUG_DISPATCH_CYCLE) {
2917 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
2918 "globalScaleFactor=%f, pointerIds=0x%x %s",
2919 connection->getInputChannelName().c_str(), inputTarget.flags,
2920 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2921 inputTarget.getPointerInfoString().c_str());
2922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923
2924 // Skip this event if the connection status is not normal.
2925 // We don't want to enqueue additional outbound events if the connection is broken.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002926 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002927 if (DEBUG_DISPATCH_CYCLE) {
2928 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08002929 connection->getInputChannelName().c_str(),
2930 ftl::enum_string(connection->status).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00002931 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932 return;
2933 }
2934
2935 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002936 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2937 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2938 "Entry type %s should not have FLAG_SPLIT",
Dominik Laskowski75788452021-02-09 18:51:25 -08002939 ftl::enum_string(eventEntry->type).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002941 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002942 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002943 std::unique_ptr<MotionEntry> splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002944 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945 if (!splitMotionEntry) {
2946 return; // split event was dropped
2947 }
Arthur Hungb3307ee2021-10-14 10:57:37 +00002948 if (splitMotionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
2949 std::string reason = std::string("reason=pointer cancel on split window");
2950 android_log_event_list(LOGTAG_INPUT_CANCEL)
2951 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
2952 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002953 if (DEBUG_FOCUS) {
2954 ALOGD("channel '%s' ~ Split motion event.",
2955 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002956 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002957 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002958 enqueueDispatchEntriesLocked(currentTime, connection, std::move(splitMotionEntry),
2959 inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960 return;
2961 }
2962 }
2963
2964 // Not splitting. Enqueue dispatch entries for the event as is.
2965 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2966}
2967
2968void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002969 const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07002970 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002971 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002972 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002973 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002974 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002975 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002976 ATRACE_NAME(message.c_str());
2977 }
2978
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002979 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980
2981 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002982 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002983 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002984 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002985 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002986 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002987 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002988 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002989 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002990 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002991 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002992 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002993 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994
2995 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002996 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997 startDispatchCycleLocked(currentTime, connection);
2998 }
2999}
3000
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003002 std::shared_ptr<EventEntry> eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003003 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003005 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003006 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
3007 connection->getInputChannelName().c_str(),
3008 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003009 ATRACE_NAME(message.c_str());
3010 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003011 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012 if (!(inputTargetFlags & dispatchMode)) {
3013 return;
3014 }
3015 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
3016
3017 // This is a new event.
3018 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003019 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003020 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003022 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
3023 // different EventEntry than what was passed in.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003024 EventEntry& newEntry = *(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 // Apply target flags and update the connection's input state.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003026 switch (newEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003027 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003028 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003029 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003030 dispatchEntry->resolvedAction = keyEntry.action;
3031 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003033 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
3034 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003035 if (DEBUG_DISPATCH_CYCLE) {
3036 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key "
3037 "event",
3038 connection->getInputChannelName().c_str());
3039 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003040 return; // skip the inconsistent event
3041 }
3042 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003045 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003046 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003047 // Assign a default value to dispatchEntry that will never be generated by InputReader,
3048 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
3049 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
3050 static_cast<int32_t>(IdGenerator::Source::OTHER);
3051 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003052 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3053 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
3054 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
3055 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
3056 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
3057 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3058 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
3059 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
3060 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
3061 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
3062 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003063 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003064 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003065 }
3066 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003067 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
3068 motionEntry.displayId)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003069 if (DEBUG_DISPATCH_CYCLE) {
3070 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover "
3071 "enter event",
3072 connection->getInputChannelName().c_str());
3073 }
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003074 // We keep the 'resolvedEventId' here equal to the original 'motionEntry.id' because
3075 // this is a one-to-one event conversion.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003076 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
3077 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003079 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003080 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
3081 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
3082 }
3083 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
3084 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
3085 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003087 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
3088 dispatchEntry->resolvedFlags)) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003089 if (DEBUG_DISPATCH_CYCLE) {
3090 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
3091 "event",
3092 connection->getInputChannelName().c_str());
3093 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003094 return; // skip the inconsistent event
3095 }
3096
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003097 dispatchEntry->resolvedEventId =
3098 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
3099 ? mIdGenerator.nextId()
3100 : motionEntry.id;
3101 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
3102 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
3103 ") to MotionEvent(id=0x%" PRIx32 ").",
3104 motionEntry.id, dispatchEntry->resolvedEventId);
3105 ATRACE_NAME(message.c_str());
3106 }
3107
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003108 if ((motionEntry.flags & AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE) &&
3109 (motionEntry.policyFlags & POLICY_FLAG_TRUSTED)) {
3110 // Skip reporting pointer down outside focus to the policy.
3111 break;
3112 }
3113
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003114 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003115 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003116
3117 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003119 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003120 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003121 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3122 case EventEntry::Type::DRAG: {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003123 break;
3124 }
Chris Yef59a2f42020-10-16 12:55:26 -07003125 case EventEntry::Type::SENSOR: {
3126 LOG_ALWAYS_FATAL("SENSOR events should not go to apps via input channel");
3127 break;
3128 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003129 case EventEntry::Type::CONFIGURATION_CHANGED:
3130 case EventEntry::Type::DEVICE_RESET: {
3131 LOG_ALWAYS_FATAL("%s events should not go to apps",
Dominik Laskowski75788452021-02-09 18:51:25 -08003132 ftl::enum_string(newEntry.type).c_str());
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003133 break;
3134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135 }
3136
3137 // Remember that we are waiting for this dispatch to complete.
3138 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003139 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140 }
3141
3142 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08003143 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003144 traceOutboundQueueLength(*connection);
chaviw8c9cf542019-03-25 13:02:48 -07003145}
3146
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003147/**
3148 * This function is purely for debugging. It helps us understand where the user interaction
3149 * was taking place. For example, if user is touching launcher, we will see a log that user
3150 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
3151 * We will see both launcher and wallpaper in that list.
3152 * Once the interaction with a particular set of connections starts, no new logs will be printed
3153 * until the set of interacted connections changes.
3154 *
3155 * The following items are skipped, to reduce the logspam:
3156 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
3157 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
3158 * This includes situations like the soft BACK button key. When the user releases (lifts up the
3159 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
3160 * Both of those ACTION_UP events would not be logged
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003161 */
3162void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
3163 const std::vector<InputTarget>& targets) {
3164 // Skip ACTION_UP events, and all events other than keys and motions
3165 if (entry.type == EventEntry::Type::KEY) {
3166 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
3167 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
3168 return;
3169 }
3170 } else if (entry.type == EventEntry::Type::MOTION) {
3171 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
3172 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
3173 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
3174 return;
3175 }
3176 } else {
3177 return; // Not a key or a motion
3178 }
3179
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07003180 std::unordered_set<sp<IBinder>, StrongPointerHash<IBinder>> newConnectionTokens;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003181 std::vector<sp<Connection>> newConnections;
3182 for (const InputTarget& target : targets) {
3183 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
3184 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
3185 continue; // Skip windows that receive ACTION_OUTSIDE
3186 }
3187
3188 sp<IBinder> token = target.inputChannel->getConnectionToken();
3189 sp<Connection> connection = getConnectionLocked(token);
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003190 if (connection == nullptr) {
3191 continue;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003192 }
3193 newConnectionTokens.insert(std::move(token));
3194 newConnections.emplace_back(connection);
3195 }
3196 if (newConnectionTokens == mInteractionConnectionTokens) {
3197 return; // no change
3198 }
3199 mInteractionConnectionTokens = newConnectionTokens;
3200
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003201 std::string targetList;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003202 for (const sp<Connection>& connection : newConnections) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003203 targetList += connection->getWindowName() + ", ";
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003204 }
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00003205 std::string message = "Interaction with: " + targetList;
3206 if (targetList.empty()) {
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00003207 message += "<none>";
3208 }
3209 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
3210}
3211
chaviwfd6d3512019-03-25 13:23:49 -07003212void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07003213 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07003214 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07003215 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
3216 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07003217 return;
3218 }
3219
Vishnu Nairc519ff72021-01-21 08:23:08 -08003220 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003221 if (focusedToken == token) {
3222 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07003223 return;
3224 }
3225
Prabir Pradhancef936d2021-07-21 16:17:52 +00003226 auto command = [this, token]() REQUIRES(mLock) {
3227 scoped_unlock unlock(mLock);
3228 mPolicy->onPointerDownOutsideFocus(token);
3229 };
3230 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231}
3232
3233void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003234 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003235 if (ATRACE_ENABLED()) {
3236 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003237 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00003238 ATRACE_NAME(message.c_str());
3239 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003240 if (DEBUG_DISPATCH_CYCLE) {
3241 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
3242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003244 while (connection->status == Connection::Status::NORMAL && !connection->outboundQueue.empty()) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003245 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 dispatchEntry->deliveryTime = currentTime;
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003247 const std::chrono::nanoseconds timeout = getDispatchingTimeoutLocked(connection);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05003248 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249
3250 // Publish the event.
3251 status_t status;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003252 const EventEntry& eventEntry = *(dispatchEntry->eventEntry);
3253 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003254 case EventEntry::Type::KEY: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003255 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
3256 std::array<uint8_t, 32> hmac = getSignature(keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003258 // Publish the key event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003259 status = connection->inputPublisher
3260 .publishKeyEvent(dispatchEntry->seq,
3261 dispatchEntry->resolvedEventId, keyEntry.deviceId,
3262 keyEntry.source, keyEntry.displayId,
3263 std::move(hmac), dispatchEntry->resolvedAction,
3264 dispatchEntry->resolvedFlags, keyEntry.keyCode,
3265 keyEntry.scanCode, keyEntry.metaState,
3266 keyEntry.repeatCount, keyEntry.downTime,
3267 keyEntry.eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003268 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269 }
3270
Siarhei Vishniakou49483272019-10-22 13:13:47 -07003271 case EventEntry::Type::MOTION: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003272 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003274 PointerCoords scaledCoords[MAX_POINTERS];
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003275 const PointerCoords* usingCoords = motionEntry.pointerCoords;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003276
chaviw82357092020-01-28 13:13:06 -08003277 // Set the X and Y offset and X and Y scale depending on the input source.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003278 if ((motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) &&
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003279 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
3280 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08003281 if (globalScaleFactor != 1.0f) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003282 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
3283 scaledCoords[i] = motionEntry.pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08003284 // Don't apply window scale here since we don't want scale to affect raw
3285 // coordinates. The scale will be sent back to the client and applied
3286 // later when requesting relative coordinates.
3287 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
3288 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003289 }
3290 usingCoords = scaledCoords;
3291 }
3292 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003293 // We don't want the dispatch target to know.
3294 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003295 for (uint32_t i = 0; i < motionEntry.pointerCount; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003296 scaledCoords[i].clear();
3297 }
3298 usingCoords = scaledCoords;
3299 }
3300 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003301
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003302 std::array<uint8_t, 32> hmac = getSignature(motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003303
3304 // Publish the motion event.
3305 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003306 .publishMotionEvent(dispatchEntry->seq,
3307 dispatchEntry->resolvedEventId,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003308 motionEntry.deviceId, motionEntry.source,
3309 motionEntry.displayId, std::move(hmac),
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003310 dispatchEntry->resolvedAction,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003311 motionEntry.actionButton,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003312 dispatchEntry->resolvedFlags,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003313 motionEntry.edgeFlags, motionEntry.metaState,
3314 motionEntry.buttonState,
3315 motionEntry.classification,
chaviw9eaa22c2020-07-01 16:21:27 -07003316 dispatchEntry->transform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003317 motionEntry.xPrecision, motionEntry.yPrecision,
3318 motionEntry.xCursorPosition,
3319 motionEntry.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003320 dispatchEntry->rawTransform,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003321 motionEntry.downTime, motionEntry.eventTime,
3322 motionEntry.pointerCount,
3323 motionEntry.pointerProperties, usingCoords);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003324 break;
3325 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003326
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003327 case EventEntry::Type::FOCUS: {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003328 const FocusEntry& focusEntry = static_cast<const FocusEntry&>(eventEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003329 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003330 focusEntry.id,
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07003331 focusEntry.hasFocus);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003332 break;
3333 }
3334
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003335 case EventEntry::Type::TOUCH_MODE_CHANGED: {
3336 const TouchModeEntry& touchModeEntry =
3337 static_cast<const TouchModeEntry&>(eventEntry);
3338 status = connection->inputPublisher
3339 .publishTouchModeEvent(dispatchEntry->seq, touchModeEntry.id,
3340 touchModeEntry.inTouchMode);
3341
3342 break;
3343 }
3344
Prabir Pradhan99987712020-11-10 18:43:05 -08003345 case EventEntry::Type::POINTER_CAPTURE_CHANGED: {
3346 const auto& captureEntry =
3347 static_cast<const PointerCaptureChangedEntry&>(eventEntry);
3348 status = connection->inputPublisher
3349 .publishCaptureEvent(dispatchEntry->seq, captureEntry.id,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00003350 captureEntry.pointerCaptureRequest.enable);
Prabir Pradhan99987712020-11-10 18:43:05 -08003351 break;
3352 }
3353
arthurhungb89ccb02020-12-30 16:19:01 +08003354 case EventEntry::Type::DRAG: {
3355 const DragEntry& dragEntry = static_cast<const DragEntry&>(eventEntry);
3356 status = connection->inputPublisher.publishDragEvent(dispatchEntry->seq,
3357 dragEntry.id, dragEntry.x,
3358 dragEntry.y,
3359 dragEntry.isExiting);
3360 break;
3361 }
3362
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003363 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003364 case EventEntry::Type::DEVICE_RESET:
3365 case EventEntry::Type::SENSOR: {
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003366 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
Dominik Laskowski75788452021-02-09 18:51:25 -08003367 ftl::enum_string(eventEntry.type).c_str());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003368 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08003369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370 }
3371
3372 // Check the result.
3373 if (status) {
3374 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003375 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003377 "This is unexpected because the wait queue is empty, so the pipe "
3378 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003379 "event to it, status=%s(%d)",
3380 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3381 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3383 } else {
3384 // Pipe is full and we are waiting for the app to finish process some events
3385 // before sending more events to it.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003386 if (DEBUG_DISPATCH_CYCLE) {
3387 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
3388 "waiting for the application to catch up",
3389 connection->getInputChannelName().c_str());
3390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 }
3392 } else {
3393 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +00003394 "status=%s(%d)",
3395 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3396 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
3398 }
3399 return;
3400 }
3401
3402 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003403 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
3404 connection->outboundQueue.end(),
3405 dispatchEntry));
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003406 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003407 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003408 if (connection->responsive) {
3409 mAnrTracker.insert(dispatchEntry->timeoutTime,
3410 connection->inputChannel->getConnectionToken());
3411 }
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003412 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 }
3414}
3415
chaviw09c8d2d2020-08-24 15:48:26 -07003416std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
3417 size_t size;
3418 switch (event.type) {
3419 case VerifiedInputEvent::Type::KEY: {
3420 size = sizeof(VerifiedKeyEvent);
3421 break;
3422 }
3423 case VerifiedInputEvent::Type::MOTION: {
3424 size = sizeof(VerifiedMotionEvent);
3425 break;
3426 }
3427 }
3428 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
3429 return mHmacKeyManager.sign(start, size);
3430}
3431
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003432const std::array<uint8_t, 32> InputDispatcher::getSignature(
3433 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003434 const int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
3435 if (actionMasked != AMOTION_EVENT_ACTION_UP && actionMasked != AMOTION_EVENT_ACTION_DOWN) {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003436 // Only sign events up and down events as the purely move events
3437 // are tied to their up/down counterparts so signing would be redundant.
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003438 return INVALID_HMAC;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003439 }
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003440
3441 VerifiedMotionEvent verifiedEvent =
3442 verifiedMotionEventFromMotionEntry(motionEntry, dispatchEntry.rawTransform);
3443 verifiedEvent.actionMasked = actionMasked;
3444 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
3445 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003446}
3447
3448const std::array<uint8_t, 32> InputDispatcher::getSignature(
3449 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
3450 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
3451 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
3452 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07003453 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07003454}
3455
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003457 const sp<Connection>& connection, uint32_t seq,
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10003458 bool handled, nsecs_t consumeTime) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003459 if (DEBUG_DISPATCH_CYCLE) {
3460 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
3461 connection->getInputChannelName().c_str(), seq, toString(handled));
3462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003464 if (connection->status == Connection::Status::BROKEN ||
3465 connection->status == Connection::Status::ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466 return;
3467 }
3468
3469 // Notify other system components and prepare to start the next dispatch cycle.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003470 auto command = [this, currentTime, connection, seq, handled, consumeTime]() REQUIRES(mLock) {
3471 doDispatchCycleFinishedCommand(currentTime, connection, seq, handled, consumeTime);
3472 };
3473 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474}
3475
3476void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003477 const sp<Connection>& connection,
3478 bool notify) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003479 if (DEBUG_DISPATCH_CYCLE) {
3480 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
3481 connection->getInputChannelName().c_str(), toString(notify));
3482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483
3484 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003485 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003486 traceOutboundQueueLength(*connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003487 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00003488 traceWaitQueueLength(*connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489
3490 // The connection appears to be unrecoverably broken.
3491 // Ignore already broken or zombie connections.
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003492 if (connection->status == Connection::Status::NORMAL) {
3493 connection->status = Connection::Status::BROKEN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494
3495 if (notify) {
3496 // Notify other system components.
Prabir Pradhancef936d2021-07-21 16:17:52 +00003497 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3498 connection->getInputChannelName().c_str());
3499
3500 auto command = [this, connection]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003501 scoped_unlock unlock(mLock);
3502 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
3503 };
3504 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 }
3506 }
3507}
3508
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003509void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
3510 while (!queue.empty()) {
3511 DispatchEntry* dispatchEntry = queue.front();
3512 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003513 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514 }
3515}
3516
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003517void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003519 decrementPendingForegroundDispatches(*(dispatchEntry->eventEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520 }
3521 delete dispatchEntry;
3522}
3523
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003524int InputDispatcher::handleReceiveCallback(int events, sp<IBinder> connectionToken) {
3525 std::scoped_lock _l(mLock);
3526 sp<Connection> connection = getConnectionLocked(connectionToken);
3527 if (connection == nullptr) {
3528 ALOGW("Received looper callback for unknown input channel token %p. events=0x%x",
3529 connectionToken.get(), events);
3530 return 0; // remove the callback
3531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003533 bool notify;
3534 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
3535 if (!(events & ALOOPER_EVENT_INPUT)) {
3536 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
3537 "events=0x%x",
3538 connection->getInputChannelName().c_str(), events);
3539 return 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 }
3541
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003542 nsecs_t currentTime = now();
3543 bool gotOne = false;
3544 status_t status = OK;
3545 for (;;) {
3546 Result<InputPublisher::ConsumerResponse> result =
3547 connection->inputPublisher.receiveConsumerResponse();
3548 if (!result.ok()) {
3549 status = result.error().code();
3550 break;
3551 }
3552
3553 if (std::holds_alternative<InputPublisher::Finished>(*result)) {
3554 const InputPublisher::Finished& finish =
3555 std::get<InputPublisher::Finished>(*result);
3556 finishDispatchCycleLocked(currentTime, connection, finish.seq, finish.handled,
3557 finish.consumeTime);
3558 } else if (std::holds_alternative<InputPublisher::Timeline>(*result)) {
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00003559 if (shouldReportMetricsForConnection(*connection)) {
3560 const InputPublisher::Timeline& timeline =
3561 std::get<InputPublisher::Timeline>(*result);
3562 mLatencyTracker
3563 .trackGraphicsLatency(timeline.inputEventId,
3564 connection->inputChannel->getConnectionToken(),
3565 std::move(timeline.graphicsTimeline));
3566 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003567 }
3568 gotOne = true;
3569 }
3570 if (gotOne) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00003571 runCommandsLockedInterruptable();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003572 if (status == WOULD_BLOCK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573 return 1;
3574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575 }
3576
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003577 notify = status != DEAD_OBJECT || !connection->monitor;
3578 if (notify) {
3579 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%s(%d)",
3580 connection->getInputChannelName().c_str(), statusToString(status).c_str(),
3581 status);
3582 }
3583 } else {
3584 // Monitor channels are never explicitly unregistered.
3585 // We do it automatically when the remote endpoint is closed so don't warn about them.
3586 const bool stillHaveWindowHandle =
3587 getWindowHandleLocked(connection->inputChannel->getConnectionToken()) != nullptr;
3588 notify = !connection->monitor && stillHaveWindowHandle;
3589 if (notify) {
3590 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. events=0x%x",
3591 connection->getInputChannelName().c_str(), events);
3592 }
3593 }
3594
3595 // Remove the channel.
3596 removeInputChannelLocked(connection->inputChannel->getConnectionToken(), notify);
3597 return 0; // remove the callback
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598}
3599
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003600void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601 const CancelationOptions& options) {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00003602 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou2e2ea992020-12-15 02:57:19 +00003603 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 }
3605}
3606
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003607void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003608 const CancelationOptions& options) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003609 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003610 for (const Monitor& monitor : monitors) {
3611 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003612 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01003613 }
3614}
3615
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003617 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07003618 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003619 if (connection == nullptr) {
3620 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003622
3623 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624}
3625
3626void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
3627 const sp<Connection>& connection, const CancelationOptions& options) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003628 if (connection->status == Connection::Status::BROKEN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 return;
3630 }
3631
3632 nsecs_t currentTime = now();
3633
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003634 std::vector<std::unique_ptr<EventEntry>> cancelationEvents =
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07003635 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003637 if (cancelationEvents.empty()) {
3638 return;
3639 }
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003640 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
3641 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
3642 "with reality: %s, mode=%d.",
3643 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
3644 options.mode);
3645 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003646
Arthur Hungb3307ee2021-10-14 10:57:37 +00003647 std::string reason = std::string("reason=").append(options.reason);
3648 android_log_event_list(LOGTAG_INPUT_CANCEL)
3649 << connection->getInputChannelName().c_str() << reason << LOG_ID_EVENTS;
3650
Svet Ganov5d3bc372020-01-26 23:11:07 -08003651 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003652 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003653 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3654 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003655 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003656 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003657 target.globalScaleFactor = windowInfo->globalScaleFactor;
3658 }
3659 target.inputChannel = connection->inputChannel;
3660 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3661
hongzuo liu474c1672022-09-06 02:51:35 +00003662 const bool wasEmpty = connection->outboundQueue.empty();
3663
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003664 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003665 std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003666 switch (cancelationEventEntry->type) {
3667 case EventEntry::Type::KEY: {
3668 logOutboundKeyDetails("cancel - ",
3669 static_cast<const KeyEntry&>(*cancelationEventEntry));
3670 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003671 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003672 case EventEntry::Type::MOTION: {
3673 logOutboundMotionDetails("cancel - ",
3674 static_cast<const MotionEntry&>(*cancelationEventEntry));
3675 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 }
Prabir Pradhan99987712020-11-10 18:43:05 -08003677 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003678 case EventEntry::Type::TOUCH_MODE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003679 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
3680 case EventEntry::Type::DRAG: {
Prabir Pradhan99987712020-11-10 18:43:05 -08003681 LOG_ALWAYS_FATAL("Canceling %s events is not supported",
Dominik Laskowski75788452021-02-09 18:51:25 -08003682 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003683 break;
3684 }
3685 case EventEntry::Type::CONFIGURATION_CHANGED:
Chris Yef59a2f42020-10-16 12:55:26 -07003686 case EventEntry::Type::DEVICE_RESET:
3687 case EventEntry::Type::SENSOR: {
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003688 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003689 ftl::enum_string(cancelationEventEntry->type).c_str());
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003690 break;
3691 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692 }
3693
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003694 enqueueDispatchEntryLocked(connection, std::move(cancelationEventEntry), target,
3695 InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08003697
hongzuo liu474c1672022-09-06 02:51:35 +00003698 // If the outbound queue was previously empty, start the dispatch cycle going.
3699 if (wasEmpty && !connection->outboundQueue.empty()) {
3700 startDispatchCycleLocked(currentTime, connection);
3701 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702}
3703
Svet Ganov5d3bc372020-01-26 23:11:07 -08003704void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
3705 const sp<Connection>& connection) {
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08003706 if (connection->status == Connection::Status::BROKEN) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003707 return;
3708 }
3709
3710 nsecs_t currentTime = now();
3711
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003712 std::vector<std::unique_ptr<EventEntry>> downEvents =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003713 connection->inputState.synthesizePointerDownEvents(currentTime);
3714
3715 if (downEvents.empty()) {
3716 return;
3717 }
3718
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003719 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003720 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
3721 connection->getInputChannelName().c_str(), downEvents.size());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003722 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003723
3724 InputTarget target;
chaviw98318de2021-05-19 16:45:23 -05003725 sp<WindowInfoHandle> windowHandle =
Svet Ganov5d3bc372020-01-26 23:11:07 -08003726 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
3727 if (windowHandle != nullptr) {
chaviw98318de2021-05-19 16:45:23 -05003728 const WindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07003729 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003730 target.globalScaleFactor = windowInfo->globalScaleFactor;
3731 }
3732 target.inputChannel = connection->inputChannel;
3733 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
3734
hongzuo liu474c1672022-09-06 02:51:35 +00003735 const bool wasEmpty = connection->outboundQueue.empty();
3736
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003737 for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003738 switch (downEventEntry->type) {
3739 case EventEntry::Type::MOTION: {
3740 logOutboundMotionDetails("down - ",
3741 static_cast<const MotionEntry&>(*downEventEntry));
3742 break;
3743 }
3744
3745 case EventEntry::Type::KEY:
3746 case EventEntry::Type::FOCUS:
Antonio Kantek7242d8b2021-08-05 16:07:20 -07003747 case EventEntry::Type::TOUCH_MODE_CHANGED:
Svet Ganov5d3bc372020-01-26 23:11:07 -08003748 case EventEntry::Type::CONFIGURATION_CHANGED:
Prabir Pradhan99987712020-11-10 18:43:05 -08003749 case EventEntry::Type::DEVICE_RESET:
Chris Yef59a2f42020-10-16 12:55:26 -07003750 case EventEntry::Type::POINTER_CAPTURE_CHANGED:
arthurhungb89ccb02020-12-30 16:19:01 +08003751 case EventEntry::Type::SENSOR:
3752 case EventEntry::Type::DRAG: {
Svet Ganov5d3bc372020-01-26 23:11:07 -08003753 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
Dominik Laskowski75788452021-02-09 18:51:25 -08003754 ftl::enum_string(downEventEntry->type).c_str());
Svet Ganov5d3bc372020-01-26 23:11:07 -08003755 break;
3756 }
3757 }
3758
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003759 enqueueDispatchEntryLocked(connection, std::move(downEventEntry), target,
3760 InputTarget::FLAG_DISPATCH_AS_IS);
Svet Ganov5d3bc372020-01-26 23:11:07 -08003761 }
hongzuo liu474c1672022-09-06 02:51:35 +00003762 // If the outbound queue was previously empty, start the dispatch cycle going.
3763 if (wasEmpty && !connection->outboundQueue.empty()) {
3764 startDispatchCycleLocked(currentTime, connection);
3765 }
Svet Ganov5d3bc372020-01-26 23:11:07 -08003766}
3767
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003768std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
3769 const MotionEntry& originalMotionEntry, BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 ALOG_ASSERT(pointerIds.value != 0);
3771
3772 uint32_t splitPointerIndexMap[MAX_POINTERS];
3773 PointerProperties splitPointerProperties[MAX_POINTERS];
3774 PointerCoords splitPointerCoords[MAX_POINTERS];
3775
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003776 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777 uint32_t splitPointerCount = 0;
3778
3779 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003780 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003782 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 uint32_t pointerId = uint32_t(pointerProperties.id);
3784 if (pointerIds.hasBit(pointerId)) {
3785 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
3786 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
3787 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003788 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003789 splitPointerCount += 1;
3790 }
3791 }
3792
3793 if (splitPointerCount != pointerIds.count()) {
3794 // This is bad. We are missing some of the pointers that we expected to deliver.
3795 // Most likely this indicates that we received an ACTION_MOVE events that has
3796 // different pointer ids than we expected based on the previous ACTION_DOWN
3797 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
3798 // in this way.
3799 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003800 "we expected there to be %d pointers. This probably means we received "
3801 "a broken sequence of pointer ids from the input device.",
3802 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003803 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 }
3805
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003806 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003808 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3809 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3811 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003812 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 uint32_t pointerId = uint32_t(pointerProperties.id);
3814 if (pointerIds.hasBit(pointerId)) {
3815 if (pointerIds.count() == 1) {
3816 // The first/last pointer went down/up.
3817 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003818 ? AMOTION_EVENT_ACTION_DOWN
arthurhungea3f4fc2020-12-21 23:18:53 +08003819 : (originalMotionEntry.flags & AMOTION_EVENT_FLAG_CANCELED) != 0
3820 ? AMOTION_EVENT_ACTION_CANCEL
3821 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 } else {
3823 // A secondary pointer went down/up.
3824 uint32_t splitPointerIndex = 0;
3825 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3826 splitPointerIndex += 1;
3827 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003828 action = maskedAction |
3829 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 }
3831 } else {
3832 // An unrelated pointer changed.
3833 action = AMOTION_EVENT_ACTION_MOVE;
3834 }
3835 }
3836
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003837 int32_t newId = mIdGenerator.nextId();
3838 if (ATRACE_ENABLED()) {
3839 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3840 ") to MotionEvent(id=0x%" PRIx32 ").",
3841 originalMotionEntry.id, newId);
3842 ATRACE_NAME(message.c_str());
3843 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003844 std::unique_ptr<MotionEntry> splitMotionEntry =
3845 std::make_unique<MotionEntry>(newId, originalMotionEntry.eventTime,
3846 originalMotionEntry.deviceId, originalMotionEntry.source,
3847 originalMotionEntry.displayId,
3848 originalMotionEntry.policyFlags, action,
3849 originalMotionEntry.actionButton,
3850 originalMotionEntry.flags, originalMotionEntry.metaState,
3851 originalMotionEntry.buttonState,
3852 originalMotionEntry.classification,
3853 originalMotionEntry.edgeFlags,
3854 originalMotionEntry.xPrecision,
3855 originalMotionEntry.yPrecision,
3856 originalMotionEntry.xCursorPosition,
3857 originalMotionEntry.yCursorPosition,
3858 originalMotionEntry.downTime, splitPointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00003859 splitPointerProperties, splitPointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003860
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003861 if (originalMotionEntry.injectionState) {
3862 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 splitMotionEntry->injectionState->refCount += 1;
3864 }
3865
3866 return splitMotionEntry;
3867}
3868
3869void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003870 if (DEBUG_INBOUND_EVENT_DETAILS) {
3871 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
3872 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873
Antonio Kantekf16f2832021-09-28 04:39:20 +00003874 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003876 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003877
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003878 std::unique_ptr<ConfigurationChangedEntry> newEntry =
3879 std::make_unique<ConfigurationChangedEntry>(args->id, args->eventTime);
3880 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881 } // release lock
3882
3883 if (needWake) {
3884 mLooper->wake();
3885 }
3886}
3887
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003888/**
3889 * If one of the meta shortcuts is detected, process them here:
3890 * Meta + Backspace -> generate BACK
3891 * Meta + Enter -> generate HOME
3892 * This will potentially overwrite keyCode and metaState.
3893 */
3894void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003895 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003896 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3897 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3898 if (keyCode == AKEYCODE_DEL) {
3899 newKeyCode = AKEYCODE_BACK;
3900 } else if (keyCode == AKEYCODE_ENTER) {
3901 newKeyCode = AKEYCODE_HOME;
3902 }
3903 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003904 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003905 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003906 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003907 keyCode = newKeyCode;
3908 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3909 }
3910 } else if (action == AKEY_EVENT_ACTION_UP) {
3911 // In order to maintain a consistent stream of up and down events, check to see if the key
3912 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3913 // even if the modifier was released between the down and the up events.
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 auto replacementIt = mReplacedKeys.find(replacement);
3917 if (replacementIt != mReplacedKeys.end()) {
3918 keyCode = replacementIt->second;
3919 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003920 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3921 }
3922 }
3923}
3924
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00003926 if (DEBUG_INBOUND_EVENT_DETAILS) {
3927 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3928 "policyFlags=0x%x, action=0x%x, "
3929 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3930 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3931 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3932 args->downTime);
3933 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003934 if (!validateKeyEvent(args->action)) {
3935 return;
3936 }
3937
3938 uint32_t policyFlags = args->policyFlags;
3939 int32_t flags = args->flags;
3940 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003941 // InputDispatcher tracks and generates key repeats on behalf of
3942 // whatever notifies it, so repeatCount should always be set to 0
3943 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3945 policyFlags |= POLICY_FLAG_VIRTUAL;
3946 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948 if (policyFlags & POLICY_FLAG_FUNCTION) {
3949 metaState |= AMETA_FUNCTION_ON;
3950 }
3951
3952 policyFlags |= POLICY_FLAG_TRUSTED;
3953
Michael Wright78f24442014-08-06 15:55:28 -07003954 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003955 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003956
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003958 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003959 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3960 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961
Michael Wright2b3c3302018-03-02 17:19:13 +00003962 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003964 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3965 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003966 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968
Antonio Kantekf16f2832021-09-28 04:39:20 +00003969 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 { // acquire lock
3971 mLock.lock();
3972
3973 if (shouldSendKeyToInputFilterLocked(args)) {
3974 mLock.unlock();
3975
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003976 policyFlags |= POLICY_FLAG_FILTERED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3978 return; // event was consumed by the filter
3979 }
3980
3981 mLock.lock();
3982 }
3983
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003984 std::unique_ptr<KeyEntry> newEntry =
3985 std::make_unique<KeyEntry>(args->id, args->eventTime, args->deviceId, args->source,
3986 args->displayId, policyFlags, args->action, flags,
3987 keyCode, args->scanCode, metaState, repeatCount,
3988 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07003990 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991 mLock.unlock();
3992 } // release lock
3993
3994 if (needWake) {
3995 mLooper->wake();
3996 }
3997}
3998
3999bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
4000 return mInputFilterEnabled;
4001}
4002
4003void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004004 if (DEBUG_INBOUND_EVENT_DETAILS) {
4005 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4006 "displayId=%" PRId32 ", policyFlags=0x%x, "
4007 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
4008 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
4009 "yCursorPosition=%f, downTime=%" PRId64,
4010 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
4011 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
4012 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
4013 args->xCursorPosition, args->yCursorPosition, args->downTime);
4014 for (uint32_t i = 0; i < args->pointerCount; i++) {
4015 ALOGD(" Pointer %d: id=%d, toolType=%d, "
4016 "x=%f, y=%f, pressure=%f, size=%f, "
4017 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
4018 "orientation=%f",
4019 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
4020 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
4021 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
4022 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
4023 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
4024 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
4025 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
4026 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
4027 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
4028 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
4029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004031 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
4032 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033 return;
4034 }
4035
4036 uint32_t policyFlags = args->policyFlags;
4037 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004038
4039 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08004040 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004041 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4042 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004043 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004044 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045
Antonio Kantekf16f2832021-09-28 04:39:20 +00004046 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047 { // acquire lock
4048 mLock.lock();
4049
4050 if (shouldSendMotionToInputFilterLocked(args)) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004051 ui::Transform displayTransform;
4052 if (const auto it = mDisplayInfos.find(args->displayId); it != mDisplayInfos.end()) {
4053 displayTransform = it->second.transform;
4054 }
4055
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 mLock.unlock();
4057
4058 MotionEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004059 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
4060 args->action, args->actionButton, args->flags, args->edgeFlags,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004061 args->metaState, args->buttonState, args->classification,
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004062 displayTransform, args->xPrecision, args->yPrecision,
4063 args->xCursorPosition, args->yCursorPosition, displayTransform,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004064 args->downTime, args->eventTime, args->pointerCount,
4065 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066
4067 policyFlags |= POLICY_FLAG_FILTERED;
4068 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
4069 return; // event was consumed by the filter
4070 }
4071
4072 mLock.lock();
4073 }
4074
4075 // Just enqueue a new motion event.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004076 std::unique_ptr<MotionEntry> newEntry =
4077 std::make_unique<MotionEntry>(args->id, args->eventTime, args->deviceId,
4078 args->source, args->displayId, policyFlags,
4079 args->action, args->actionButton, args->flags,
4080 args->metaState, args->buttonState,
4081 args->classification, args->edgeFlags,
4082 args->xPrecision, args->yPrecision,
4083 args->xCursorPosition, args->yCursorPosition,
4084 args->downTime, args->pointerCount,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004085 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086
Siarhei Vishniakou363e7292021-07-09 03:22:42 +00004087 if (args->id != android::os::IInputConstants::INVALID_INPUT_EVENT_ID &&
4088 IdGenerator::getSource(args->id) == IdGenerator::Source::INPUT_READER &&
4089 !mInputFilterEnabled) {
4090 const bool isDown = args->action == AMOTION_EVENT_ACTION_DOWN;
4091 mLatencyTracker.trackListener(args->id, isDown, args->eventTime, args->readTime);
4092 }
4093
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004094 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095 mLock.unlock();
4096 } // release lock
4097
4098 if (needWake) {
4099 mLooper->wake();
4100 }
4101}
4102
Chris Yef59a2f42020-10-16 12:55:26 -07004103void InputDispatcher::notifySensor(const NotifySensorArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004104 if (DEBUG_INBOUND_EVENT_DETAILS) {
4105 ALOGD("notifySensor - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
4106 " sensorType=%s",
4107 args->id, args->eventTime, args->deviceId, args->source,
Dominik Laskowski75788452021-02-09 18:51:25 -08004108 ftl::enum_string(args->sensorType).c_str());
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004109 }
Chris Yef59a2f42020-10-16 12:55:26 -07004110
Antonio Kantekf16f2832021-09-28 04:39:20 +00004111 bool needWake = false;
Chris Yef59a2f42020-10-16 12:55:26 -07004112 { // acquire lock
4113 mLock.lock();
4114
4115 // Just enqueue a new sensor event.
4116 std::unique_ptr<SensorEntry> newEntry =
4117 std::make_unique<SensorEntry>(args->id, args->eventTime, args->deviceId,
4118 args->source, 0 /* policyFlags*/, args->hwTimestamp,
4119 args->sensorType, args->accuracy,
4120 args->accuracyChanged, args->values);
4121
4122 needWake = enqueueInboundEventLocked(std::move(newEntry));
4123 mLock.unlock();
4124 } // release lock
4125
4126 if (needWake) {
4127 mLooper->wake();
4128 }
4129}
4130
Chris Yefb552902021-02-03 17:18:37 -08004131void InputDispatcher::notifyVibratorState(const NotifyVibratorStateArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004132 if (DEBUG_INBOUND_EVENT_DETAILS) {
4133 ALOGD("notifyVibratorState - eventTime=%" PRId64 ", device=%d, isOn=%d", args->eventTime,
4134 args->deviceId, args->isOn);
4135 }
Chris Yefb552902021-02-03 17:18:37 -08004136 mPolicy->notifyVibratorState(args->deviceId, args->isOn);
4137}
4138
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08004140 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141}
4142
4143void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004144 if (DEBUG_INBOUND_EVENT_DETAILS) {
4145 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
4146 "switchMask=0x%08x",
4147 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
4148 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149
4150 uint32_t policyFlags = args->policyFlags;
4151 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004152 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153}
4154
4155void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004156 if (DEBUG_INBOUND_EVENT_DETAILS) {
4157 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
4158 args->deviceId);
4159 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160
Antonio Kantekf16f2832021-09-28 04:39:20 +00004161 bool needWake = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004163 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004165 std::unique_ptr<DeviceResetEntry> newEntry =
4166 std::make_unique<DeviceResetEntry>(args->id, args->eventTime, args->deviceId);
4167 needWake = enqueueInboundEventLocked(std::move(newEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 } // release lock
4169
4170 if (needWake) {
4171 mLooper->wake();
4172 }
4173}
4174
Prabir Pradhan7e186182020-11-10 13:56:45 -08004175void InputDispatcher::notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004176 if (DEBUG_INBOUND_EVENT_DETAILS) {
4177 ALOGD("notifyPointerCaptureChanged - eventTime=%" PRId64 ", enabled=%s", args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004178 args->request.enable ? "true" : "false");
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004179 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004180
Antonio Kantekf16f2832021-09-28 04:39:20 +00004181 bool needWake = false;
Prabir Pradhan99987712020-11-10 18:43:05 -08004182 { // acquire lock
4183 std::scoped_lock _l(mLock);
4184 auto entry = std::make_unique<PointerCaptureChangedEntry>(args->id, args->eventTime,
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004185 args->request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004186 needWake = enqueueInboundEventLocked(std::move(entry));
4187 } // release lock
4188
4189 if (needWake) {
4190 mLooper->wake();
4191 }
Prabir Pradhan7e186182020-11-10 13:56:45 -08004192}
4193
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004194InputEventInjectionResult InputDispatcher::injectInputEvent(const InputEvent* event,
4195 std::optional<int32_t> targetUid,
4196 InputEventInjectionSync syncMode,
4197 std::chrono::milliseconds timeout,
4198 uint32_t policyFlags) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004199 if (DEBUG_INBOUND_EVENT_DETAILS) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004200 ALOGD("injectInputEvent - eventType=%d, targetUid=%s, syncMode=%d, timeout=%lld, "
4201 "policyFlags=0x%08x",
4202 event->getType(), targetUid ? std::to_string(*targetUid).c_str() : "none", syncMode,
4203 timeout.count(), policyFlags);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004204 }
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07004205 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004207 policyFlags |= POLICY_FLAG_INJECTED | POLICY_FLAG_TRUSTED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004209 // For all injected events, set device id = VIRTUAL_KEYBOARD_ID. The only exception is events
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004210 // that have gone through the InputFilter. If the event passed through the InputFilter, assign
4211 // the provided device id. If the InputFilter is accessibility, and it modifies or synthesizes
4212 // the injected event, it is responsible for setting POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY.
4213 // For those events, we will set FLAG_IS_ACCESSIBILITY_EVENT to allow apps to distinguish them
4214 // from events that originate from actual hardware.
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004215 int32_t resolvedDeviceId = VIRTUAL_KEYBOARD_ID;
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004216 if (policyFlags & POLICY_FLAG_FILTERED) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004217 resolvedDeviceId = event->getDeviceId();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004218 }
4219
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004220 std::queue<std::unique_ptr<EventEntry>> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004222 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004223 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
4224 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004225 if (!validateKeyEvent(action)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004226 return InputEventInjectionResult::FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00004227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004229 int32_t flags = incomingKey.getFlags();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004230 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4231 flags |= AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4232 }
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004233 int32_t keyCode = incomingKey.getKeyCode();
4234 int32_t metaState = incomingKey.getMetaState();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004235 accelerateMetaShortcuts(resolvedDeviceId, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004236 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004237 KeyEvent keyEvent;
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004238 keyEvent.initialize(incomingKey.getId(), resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08004239 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
4240 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
4241 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004243 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
4244 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00004245 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004246
4247 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
4248 android::base::Timer t;
4249 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
4250 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4251 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
4252 std::to_string(t.duration().count()).c_str());
4253 }
4254 }
4255
4256 mLock.lock();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004257 std::unique_ptr<KeyEntry> injectedEntry =
4258 std::make_unique<KeyEntry>(incomingKey.getId(), incomingKey.getEventTime(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004259 resolvedDeviceId, incomingKey.getSource(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004260 incomingKey.getDisplayId(), policyFlags, action,
4261 flags, keyCode, incomingKey.getScanCode(), metaState,
4262 incomingKey.getRepeatCount(),
4263 incomingKey.getDownTime());
4264 injectedEntries.push(std::move(injectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004265 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 }
4267
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004268 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004269 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004270 const int32_t action = motionEvent.getAction();
4271 const bool isPointerEvent =
4272 isFromSource(event->getSource(), AINPUT_SOURCE_CLASS_POINTER);
4273 // If a pointer event has no displayId specified, inject it to the default display.
4274 const uint32_t displayId = isPointerEvent && (event->getDisplayId() == ADISPLAY_ID_NONE)
4275 ? ADISPLAY_ID_DEFAULT
4276 : event->getDisplayId();
4277 const size_t pointerCount = motionEvent.getPointerCount();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004278 const PointerProperties* pointerProperties = motionEvent.getPointerProperties();
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004279 const int32_t actionButton = motionEvent.getActionButton();
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004280 int32_t flags = motionEvent.getFlags();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004281 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004282 return InputEventInjectionResult::FAILED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004283 }
4284
4285 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004286 nsecs_t eventTime = motionEvent.getEventTime();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004287 android::base::Timer t;
4288 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
4289 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4290 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
4291 std::to_string(t.duration().count()).c_str());
4292 }
4293 }
4294
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004295 if (policyFlags & POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY) {
4296 flags |= AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
4297 }
4298
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004299 mLock.lock();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004300 const nsecs_t* sampleEventTimes = motionEvent.getSampleEventTimes();
4301 const PointerCoords* samplePointerCoords = motionEvent.getSamplePointerCoords();
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004302 std::unique_ptr<MotionEntry> injectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004303 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4304 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004305 displayId, policyFlags, action, actionButton,
4306 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004307 motionEvent.getButtonState(),
4308 motionEvent.getClassification(),
4309 motionEvent.getEdgeFlags(),
4310 motionEvent.getXPrecision(),
4311 motionEvent.getYPrecision(),
4312 motionEvent.getRawXCursorPosition(),
4313 motionEvent.getRawYCursorPosition(),
4314 motionEvent.getDownTime(), uint32_t(pointerCount),
Prabir Pradhan5beda762021-12-10 09:30:08 +00004315 pointerProperties, samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004316 transformMotionEntryForInjectionLocked(*injectedEntry, motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004317 injectedEntries.push(std::move(injectedEntry));
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004318 for (size_t i = motionEvent.getHistorySize(); i > 0; i--) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004319 sampleEventTimes += 1;
4320 samplePointerCoords += pointerCount;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004321 std::unique_ptr<MotionEntry> nextInjectedEntry =
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004322 std::make_unique<MotionEntry>(motionEvent.getId(), *sampleEventTimes,
4323 resolvedDeviceId, motionEvent.getSource(),
Prabir Pradhanaa561d12021-09-24 06:57:33 -07004324 displayId, policyFlags, action, actionButton,
4325 flags, motionEvent.getMetaState(),
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004326 motionEvent.getButtonState(),
4327 motionEvent.getClassification(),
4328 motionEvent.getEdgeFlags(),
4329 motionEvent.getXPrecision(),
4330 motionEvent.getYPrecision(),
4331 motionEvent.getRawXCursorPosition(),
4332 motionEvent.getRawYCursorPosition(),
4333 motionEvent.getDownTime(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004334 uint32_t(pointerCount), pointerProperties,
Prabir Pradhan5beda762021-12-10 09:30:08 +00004335 samplePointerCoords);
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004336 transformMotionEntryForInjectionLocked(*nextInjectedEntry,
4337 motionEvent.getTransform());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004338 injectedEntries.push(std::move(nextInjectedEntry));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004339 }
4340 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004343 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08004344 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004345 return InputEventInjectionResult::FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346 }
4347
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004348 InjectionState* injectionState = new InjectionState(targetUid);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004349 if (syncMode == InputEventInjectionSync::NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 injectionState->injectionIsAsync = true;
4351 }
4352
4353 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004354 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355
4356 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004357 while (!injectedEntries.empty()) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004358 needWake |= enqueueInboundEventLocked(std::move(injectedEntries.front()));
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004359 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 }
4361
4362 mLock.unlock();
4363
4364 if (needWake) {
4365 mLooper->wake();
4366 }
4367
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004368 InputEventInjectionResult injectionResult;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004370 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004372 if (syncMode == InputEventInjectionSync::NONE) {
4373 injectionResult = InputEventInjectionResult::SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 } else {
4375 for (;;) {
4376 injectionResult = injectionState->injectionResult;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004377 if (injectionResult != InputEventInjectionResult::PENDING) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 break;
4379 }
4380
4381 nsecs_t remainingTimeout = endTime - now();
4382 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004383 if (DEBUG_INJECTION) {
4384 ALOGD("injectInputEvent - Timed out waiting for injection result "
4385 "to become available.");
4386 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004387 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 break;
4389 }
4390
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004391 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 }
4393
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004394 if (injectionResult == InputEventInjectionResult::SUCCEEDED &&
4395 syncMode == InputEventInjectionSync::WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 while (injectionState->pendingForegroundDispatches != 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004397 if (DEBUG_INJECTION) {
4398 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
4399 injectionState->pendingForegroundDispatches);
4400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 nsecs_t remainingTimeout = endTime - now();
4402 if (remainingTimeout <= 0) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004403 if (DEBUG_INJECTION) {
4404 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
4405 "dispatches to finish.");
4406 }
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004407 injectionResult = InputEventInjectionResult::TIMED_OUT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 break;
4409 }
4410
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004411 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412 }
4413 }
4414 }
4415
4416 injectionState->release();
4417 } // release lock
4418
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004419 if (DEBUG_INJECTION) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004420 ALOGD("injectInputEvent - Finished with result %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422
4423 return injectionResult;
4424}
4425
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004426std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05004427 std::array<uint8_t, 32> calculatedHmac;
4428 std::unique_ptr<VerifiedInputEvent> result;
4429 switch (event.getType()) {
4430 case AINPUT_EVENT_TYPE_KEY: {
4431 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
4432 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
4433 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004434 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05004435 break;
4436 }
4437 case AINPUT_EVENT_TYPE_MOTION: {
4438 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
4439 VerifiedMotionEvent verifiedMotionEvent =
4440 verifiedMotionEventFromMotionEvent(motionEvent);
4441 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07004442 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05004443 break;
4444 }
4445 default: {
4446 ALOGE("Cannot verify events of type %" PRId32, event.getType());
4447 return nullptr;
4448 }
4449 }
4450 if (calculatedHmac == INVALID_HMAC) {
4451 return nullptr;
4452 }
4453 if (calculatedHmac != event.getHmac()) {
4454 return nullptr;
4455 }
4456 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08004457}
4458
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004459void InputDispatcher::setInjectionResult(EventEntry& entry,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004460 InputEventInjectionResult injectionResult) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004461 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462 if (injectionState) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004463 if (DEBUG_INJECTION) {
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004464 ALOGD("Setting input event injection result to %d.", injectionResult);
Prabir Pradhan61a5d242021-07-26 16:41:09 +00004465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004467 if (injectionState->injectionIsAsync && !(entry.policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468 // Log the outcome since the injector did not wait for the injection result.
4469 switch (injectionResult) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004470 case InputEventInjectionResult::SUCCEEDED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004471 ALOGV("Asynchronous input event injection succeeded.");
4472 break;
Prabir Pradhan8a2b1a42022-04-11 17:23:34 +00004473 case InputEventInjectionResult::TARGET_MISMATCH:
4474 ALOGV("Asynchronous input event injection target mismatch.");
4475 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004476 case InputEventInjectionResult::FAILED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004477 ALOGW("Asynchronous input event injection failed.");
4478 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004479 case InputEventInjectionResult::TIMED_OUT:
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004480 ALOGW("Asynchronous input event injection timed out.");
4481 break;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004482 case InputEventInjectionResult::PENDING:
4483 ALOGE("Setting result to 'PENDING' for asynchronous injection");
4484 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485 }
4486 }
4487
4488 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004489 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490 }
4491}
4492
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004493void InputDispatcher::transformMotionEntryForInjectionLocked(
4494 MotionEntry& entry, const ui::Transform& injectedTransform) const {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004495 // Input injection works in the logical display coordinate space, but the input pipeline works
4496 // display space, so we need to transform the injected events accordingly.
4497 const auto it = mDisplayInfos.find(entry.displayId);
4498 if (it == mDisplayInfos.end()) return;
Prabir Pradhandaa2f142021-12-10 09:30:08 +00004499 const auto& transformToDisplay = it->second.transform.inverse() * injectedTransform;
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004500
Prabir Pradhand9a2ebe2022-07-20 19:25:13 +00004501 if (entry.xCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
4502 entry.yCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
4503 const vec2 cursor =
4504 MotionEvent::calculateTransformedXY(entry.source, transformToDisplay,
4505 {entry.xCursorPosition, entry.yCursorPosition});
4506 entry.xCursorPosition = cursor.x;
4507 entry.yCursorPosition = cursor.y;
4508 }
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004509 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Prabir Pradhan8e6ce222022-02-24 09:08:54 -08004510 entry.pointerCoords[i] =
4511 MotionEvent::calculateTransformedCoords(entry.source, transformToDisplay,
4512 entry.pointerCoords[i]);
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004513 }
4514}
4515
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004516void InputDispatcher::incrementPendingForegroundDispatches(EventEntry& entry) {
4517 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 if (injectionState) {
4519 injectionState->pendingForegroundDispatches += 1;
4520 }
4521}
4522
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07004523void InputDispatcher::decrementPendingForegroundDispatches(EventEntry& entry) {
4524 InjectionState* injectionState = entry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525 if (injectionState) {
4526 injectionState->pendingForegroundDispatches -= 1;
4527
4528 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004529 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530 }
4531 }
4532}
4533
chaviw98318de2021-05-19 16:45:23 -05004534const std::vector<sp<WindowInfoHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004535 int32_t displayId) const {
chaviw98318de2021-05-19 16:45:23 -05004536 static const std::vector<sp<WindowInfoHandle>> EMPTY_WINDOW_HANDLES;
Vishnu Nairad321cd2020-08-20 16:40:21 -07004537 auto it = mWindowHandlesByDisplay.find(displayId);
4538 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08004539}
4540
chaviw98318de2021-05-19 16:45:23 -05004541sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08004542 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08004543 if (windowHandleToken == nullptr) {
4544 return nullptr;
4545 }
4546
Arthur Hungb92218b2018-08-14 12:00:21 +08004547 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004548 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4549 for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004550 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004551 return windowHandle;
4552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 }
4554 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004555 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004556}
4557
chaviw98318de2021-05-19 16:45:23 -05004558sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
4559 int displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004560 if (windowHandleToken == nullptr) {
4561 return nullptr;
4562 }
4563
chaviw98318de2021-05-19 16:45:23 -05004564 for (const sp<WindowInfoHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004565 if (windowHandle->getToken() == windowHandleToken) {
4566 return windowHandle;
4567 }
4568 }
4569 return nullptr;
4570}
4571
chaviw98318de2021-05-19 16:45:23 -05004572sp<WindowInfoHandle> InputDispatcher::getWindowHandleLocked(
4573 const sp<WindowInfoHandle>& windowHandle) const {
Mady Mellor017bcd12020-06-23 19:12:00 +00004574 for (auto& it : mWindowHandlesByDisplay) {
chaviw98318de2021-05-19 16:45:23 -05004575 const std::vector<sp<WindowInfoHandle>>& windowHandles = it.second;
4576 for (const sp<WindowInfoHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08004577 if (handle->getId() == windowHandle->getId() &&
4578 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00004579 if (windowHandle->getInfo()->displayId != it.first) {
4580 ALOGE("Found window %s in display %" PRId32
4581 ", but it should belong to display %" PRId32,
4582 windowHandle->getName().c_str(), it.first,
4583 windowHandle->getInfo()->displayId);
4584 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004585 return handle;
Arthur Hungb92218b2018-08-14 12:00:21 +08004586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 }
4588 }
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004589 return nullptr;
4590}
4591
chaviw98318de2021-05-19 16:45:23 -05004592sp<WindowInfoHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004593 sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(displayId);
4594 return getWindowHandleLocked(focusedToken, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595}
4596
Prabir Pradhanc093bbe2022-12-06 20:30:22 +00004597ui::Transform InputDispatcher::getTransformLocked(int32_t displayId) const {
4598 auto displayInfoIt = mDisplayInfos.find(displayId);
4599 return displayInfoIt != mDisplayInfos.end() ? displayInfoIt->second.transform
4600 : kIdentityTransform;
4601}
4602
chaviw98318de2021-05-19 16:45:23 -05004603bool InputDispatcher::hasResponsiveConnectionLocked(WindowInfoHandle& windowHandle) const {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004604 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
4605 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004606 windowHandle.getInfo()->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004607 if (connection != nullptr && noInputChannel) {
4608 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
4609 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
4610 return false;
4611 }
4612
4613 if (connection == nullptr) {
4614 if (!noInputChannel) {
4615 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
4616 }
4617 return false;
4618 }
4619 if (!connection->responsive) {
4620 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
4621 return false;
4622 }
4623 return true;
4624}
4625
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004626std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
4627 const sp<IBinder>& token) const {
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004628 auto connectionIt = mConnectionsByToken.find(token);
4629 if (connectionIt == mConnectionsByToken.end()) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004630 return nullptr;
4631 }
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00004632 return connectionIt->second->inputChannel;
Robert Carr5c8a0262018-10-03 16:30:44 -07004633}
4634
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004635void InputDispatcher::updateWindowHandlesForDisplayLocked(
chaviw98318de2021-05-19 16:45:23 -05004636 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
4637 if (windowInfoHandles.empty()) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004638 // Remove all handles on a display if there are no windows left.
4639 mWindowHandlesByDisplay.erase(displayId);
4640 return;
4641 }
4642
4643 // Since we compare the pointer of input window handles across window updates, we need
4644 // to make sure the handle object for the same window stays unchanged across updates.
chaviw98318de2021-05-19 16:45:23 -05004645 const std::vector<sp<WindowInfoHandle>>& oldHandles = getWindowHandlesLocked(displayId);
4646 std::unordered_map<int32_t /*id*/, sp<WindowInfoHandle>> oldHandlesById;
4647 for (const sp<WindowInfoHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07004648 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004649 }
4650
chaviw98318de2021-05-19 16:45:23 -05004651 std::vector<sp<WindowInfoHandle>> newHandles;
4652 for (const sp<WindowInfoHandle>& handle : windowInfoHandles) {
chaviw98318de2021-05-19 16:45:23 -05004653 const WindowInfo* info = handle->getInfo();
Siarhei Vishniakou64452932020-11-06 17:51:32 -06004654 if (getInputChannelLocked(handle->getToken()) == nullptr) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004655 const bool noInputChannel =
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004656 info->inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004657 const bool canReceiveInput =
4658 !info->inputConfig.test(WindowInfo::InputConfig::NOT_TOUCHABLE) ||
4659 !info->inputConfig.test(WindowInfo::InputConfig::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004660 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07004661 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004662 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07004663 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004664 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004665 }
4666
4667 if (info->displayId != displayId) {
4668 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
4669 handle->getName().c_str(), displayId, info->displayId);
4670 continue;
4671 }
4672
Robert Carredd13602020-04-13 17:24:34 -07004673 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
4674 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviw98318de2021-05-19 16:45:23 -05004675 const sp<WindowInfoHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004676 oldHandle->updateFrom(handle);
4677 newHandles.push_back(oldHandle);
4678 } else {
4679 newHandles.push_back(handle);
4680 }
4681 }
4682
4683 // Insert or replace
4684 mWindowHandlesByDisplay[displayId] = newHandles;
4685}
4686
Arthur Hung72d8dc32020-03-28 00:48:39 +00004687void InputDispatcher::setInputWindows(
chaviw98318de2021-05-19 16:45:23 -05004688 const std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>>& handlesPerDisplay) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07004689 // TODO(b/198444055): Remove setInputWindows from InputDispatcher.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004690 { // acquire lock
4691 std::scoped_lock _l(mLock);
Siarhei Vishniakou2508b872020-12-03 16:33:53 -10004692 for (const auto& [displayId, handles] : handlesPerDisplay) {
4693 setInputWindowsLocked(handles, displayId);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004694 }
4695 }
4696 // Wake up poll loop since it may need to make new input dispatching choices.
4697 mLooper->wake();
4698}
4699
Arthur Hungb92218b2018-08-14 12:00:21 +08004700/**
4701 * Called from InputManagerService, update window handle list by displayId that can receive input.
4702 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
4703 * If set an empty list, remove all handles from the specific display.
4704 * For focused handle, check if need to change and send a cancel event to previous one.
4705 * For removed handle, check if need to send a cancel event if already in touch.
4706 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00004707void InputDispatcher::setInputWindowsLocked(
chaviw98318de2021-05-19 16:45:23 -05004708 const std::vector<sp<WindowInfoHandle>>& windowInfoHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004709 if (DEBUG_FOCUS) {
4710 std::string windowList;
chaviw98318de2021-05-19 16:45:23 -05004711 for (const sp<WindowInfoHandle>& iwh : windowInfoHandles) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004712 windowList += iwh->getName() + " ";
4713 }
4714 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
4715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716
Prabir Pradhand65552b2021-10-07 11:23:50 -07004717 // Check preconditions for new input windows
chaviw98318de2021-05-19 16:45:23 -05004718 for (const sp<WindowInfoHandle>& window : windowInfoHandles) {
Prabir Pradhand65552b2021-10-07 11:23:50 -07004719 const WindowInfo& info = *window->getInfo();
4720
4721 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004722 const bool noInputWindow = info.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004723 if (noInputWindow && window->getToken() != nullptr) {
4724 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
4725 window->getName().c_str());
4726 window->releaseChannel();
4727 }
Prabir Pradhand65552b2021-10-07 11:23:50 -07004728
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004729 // Ensure all spy windows are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004730 LOG_ALWAYS_FATAL_IF(info.isSpy() &&
4731 !info.inputConfig.test(
4732 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhan5c85e052021-12-22 02:27:12 -08004733 "%s has feature SPY, but is not a trusted overlay.",
4734 window->getName().c_str());
4735
Prabir Pradhand65552b2021-10-07 11:23:50 -07004736 // Ensure all stylus interceptors are trusted overlays
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004737 LOG_ALWAYS_FATAL_IF(info.interceptsStylus() &&
4738 !info.inputConfig.test(
4739 WindowInfo::InputConfig::TRUSTED_OVERLAY),
Prabir Pradhand65552b2021-10-07 11:23:50 -07004740 "%s has feature INTERCEPTS_STYLUS, but is not a trusted overlay.",
4741 window->getName().c_str());
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004742 }
4743
Arthur Hung72d8dc32020-03-28 00:48:39 +00004744 // Copy old handles for release if they are no longer present.
chaviw98318de2021-05-19 16:45:23 -05004745 const std::vector<sp<WindowInfoHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004747 // Save the old windows' orientation by ID before it gets updated.
4748 std::unordered_map<int32_t, uint32_t> oldWindowOrientations;
chaviw98318de2021-05-19 16:45:23 -05004749 for (const sp<WindowInfoHandle>& handle : oldWindowHandles) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004750 oldWindowOrientations.emplace(handle->getId(),
4751 handle->getInfo()->transform.getOrientation());
4752 }
4753
chaviw98318de2021-05-19 16:45:23 -05004754 updateWindowHandlesForDisplayLocked(windowInfoHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07004755
chaviw98318de2021-05-19 16:45:23 -05004756 const std::vector<sp<WindowInfoHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Tommy Nordgrenab0cedb2022-10-13 11:25:57 +02004757 if (mLastHoverWindowHandle) {
4758 const WindowInfo* lastHoverWindowInfo = mLastHoverWindowHandle->getInfo();
4759 if (lastHoverWindowInfo->displayId == displayId &&
4760 std::find(windowHandles.begin(), windowHandles.end(), mLastHoverWindowHandle) ==
4761 windowHandles.end()) {
4762 mLastHoverWindowHandle = nullptr;
4763 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004764 }
4765
Vishnu Nairc519ff72021-01-21 08:23:08 -08004766 std::optional<FocusResolver::FocusChanges> changes =
4767 mFocusResolver.setInputWindows(displayId, windowHandles);
4768 if (changes) {
4769 onFocusChangedLocked(*changes);
Arthur Hung72d8dc32020-03-28 00:48:39 +00004770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004772 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4773 mTouchStatesByDisplay.find(displayId);
4774 if (stateIt != mTouchStatesByDisplay.end()) {
4775 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00004776 for (size_t i = 0; i < state.windows.size();) {
4777 TouchedWindow& touchedWindow = state.windows[i];
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004778 if (getWindowHandleLocked(touchedWindow.windowHandle) == nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004779 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004780 ALOGD("Touched window was removed: %s in display %" PRId32,
4781 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004782 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004783 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00004784 getInputChannelLocked(touchedWindow.windowHandle->getToken());
4785 if (touchedInputChannel != nullptr) {
4786 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4787 "touched window was removed");
4788 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004789 // Since we are about to drop the touch, cancel the events for the wallpaper as
4790 // well.
4791 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND &&
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004792 touchedWindow.windowHandle->getInfo()->inputConfig.test(
4793 gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004794 sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
4795 if (wallpaper != nullptr) {
4796 sp<Connection> wallpaperConnection =
4797 getConnectionLocked(wallpaper->getToken());
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08004798 if (wallpaperConnection != nullptr) {
4799 synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
4800 options);
4801 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004802 }
4803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004805 state.windows.erase(state.windows.begin() + i);
4806 } else {
4807 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 }
4809 }
arthurhungb89ccb02020-12-30 16:19:01 +08004810
arthurhung6d4bed92021-03-17 11:59:33 +08004811 // If drag window is gone, it would receive a cancel event and broadcast the DRAG_END. We
arthurhungb89ccb02020-12-30 16:19:01 +08004812 // could just clear the state here.
Arthur Hung3915c1f2022-05-31 07:17:17 +00004813 if (mDragState && mDragState->dragWindow->getInfo()->displayId == displayId &&
arthurhung6d4bed92021-03-17 11:59:33 +08004814 std::find(windowHandles.begin(), windowHandles.end(), mDragState->dragWindow) ==
arthurhungb89ccb02020-12-30 16:19:01 +08004815 windowHandles.end()) {
Arthur Hung3915c1f2022-05-31 07:17:17 +00004816 ALOGI("Drag window went away: %s", mDragState->dragWindow->getName().c_str());
4817 sendDropWindowCommandLocked(nullptr, 0, 0);
arthurhung6d4bed92021-03-17 11:59:33 +08004818 mDragState.reset();
arthurhungb89ccb02020-12-30 16:19:01 +08004819 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004820 }
Arthur Hung25e2af12020-03-26 12:58:37 +00004821
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004822 // Determine if the orientation of any of the input windows have changed, and cancel all
4823 // pointer events if necessary.
4824 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
4825 const sp<WindowInfoHandle> newWindowHandle = getWindowHandleLocked(oldWindowHandle);
4826 if (newWindowHandle != nullptr &&
4827 newWindowHandle->getInfo()->transform.getOrientation() !=
4828 oldWindowOrientations[oldWindowHandle->getId()]) {
4829 std::shared_ptr<InputChannel> inputChannel =
4830 getInputChannelLocked(newWindowHandle->getToken());
4831 if (inputChannel != nullptr) {
4832 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4833 "touched window's orientation changed");
4834 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
Prabir Pradhan93a0f912021-04-21 13:47:42 -07004835 }
4836 }
4837 }
4838
Arthur Hung72d8dc32020-03-28 00:48:39 +00004839 // Release information for windows that are no longer present.
4840 // This ensures that unused input channels are released promptly.
4841 // Otherwise, they might stick around until the window handle is destroyed
4842 // which might not happen until the next GC.
chaviw98318de2021-05-19 16:45:23 -05004843 for (const sp<WindowInfoHandle>& oldWindowHandle : oldWindowHandles) {
Prabir Pradhan6a9a8312021-04-23 11:59:31 -07004844 if (getWindowHandleLocked(oldWindowHandle) == nullptr) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00004845 if (DEBUG_FOCUS) {
4846 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00004847 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00004848 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00004849 }
chaviw291d88a2019-02-14 10:33:58 -08004850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851}
4852
4853void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07004854 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004855 if (DEBUG_FOCUS) {
4856 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
4857 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
4858 }
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004859 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004860 std::scoped_lock _l(mLock);
Vishnu Nair599f1412021-06-21 10:39:58 -07004861 setFocusedApplicationLocked(displayId, inputApplicationHandle);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 } // release lock
4863
4864 // Wake up poll loop since it may need to make new input dispatching choices.
4865 mLooper->wake();
4866}
4867
Vishnu Nair599f1412021-06-21 10:39:58 -07004868void InputDispatcher::setFocusedApplicationLocked(
4869 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
4870 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
4871 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
4872
4873 if (sharedPointersEqual(oldFocusedApplicationHandle, inputApplicationHandle)) {
4874 return; // This application is already focused. No need to wake up or change anything.
4875 }
4876
4877 // Set the new application handle.
4878 if (inputApplicationHandle != nullptr) {
4879 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
4880 } else {
4881 mFocusedApplicationHandlesByDisplay.erase(displayId);
4882 }
4883
4884 // No matter what the old focused application was, stop waiting on it because it is
4885 // no longer focused.
4886 resetNoFocusedWindowTimeoutLocked();
4887}
4888
Tiger Huang721e26f2018-07-24 22:26:19 +08004889/**
4890 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
4891 * the display not specified.
4892 *
4893 * We track any unreleased events for each window. If a window loses the ability to receive the
4894 * released event, we will send a cancel event to it. So when the focused display is changed, we
4895 * cancel all the unreleased display-unspecified events for the focused window on the old focused
4896 * display. The display-specified events won't be affected.
4897 */
4898void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004899 if (DEBUG_FOCUS) {
4900 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
4901 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004902 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004903 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08004904
4905 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004906 sp<IBinder> oldFocusedWindowToken =
Vishnu Nairc519ff72021-01-21 08:23:08 -08004907 mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07004908 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004909 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07004910 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08004911 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004912 CancelationOptions
4913 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
4914 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004915 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08004916 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
4917 }
4918 }
4919 mFocusedDisplayId = displayId;
4920
Chris Ye3c2d6f52020-08-09 10:39:48 -07004921 // Find new focused window and validate
Vishnu Nairc519ff72021-01-21 08:23:08 -08004922 sp<IBinder> newFocusedWindowToken = mFocusResolver.getFocusedWindowToken(displayId);
Prabir Pradhancef936d2021-07-21 16:17:52 +00004923 sendFocusChangedCommandLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08004924
Vishnu Nairad321cd2020-08-20 16:40:21 -07004925 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08004926 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairc519ff72021-01-21 08:23:08 -08004927 if (mFocusResolver.hasFocusedWindowTokens()) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07004928 ALOGE("But another display has a focused window\n%s",
Vishnu Nairc519ff72021-01-21 08:23:08 -08004929 mFocusResolver.dumpFocusedWindows().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004930 }
4931 }
4932 }
4933
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004934 if (DEBUG_FOCUS) {
4935 logDispatchStateLocked();
4936 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004937 } // release lock
4938
4939 // Wake up poll loop since it may need to make new input dispatching choices.
4940 mLooper->wake();
4941}
4942
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004944 if (DEBUG_FOCUS) {
4945 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
4946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947
4948 bool changed;
4949 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004950 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951
4952 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
4953 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004954 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955 }
4956
4957 if (mDispatchEnabled && !enabled) {
4958 resetAndDropEverythingLocked("dispatcher is being disabled");
4959 }
4960
4961 mDispatchEnabled = enabled;
4962 mDispatchFrozen = frozen;
4963 changed = true;
4964 } else {
4965 changed = false;
4966 }
4967
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004968 if (DEBUG_FOCUS) {
4969 logDispatchStateLocked();
4970 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971 } // release lock
4972
4973 if (changed) {
4974 // Wake up poll loop since it may need to make new input dispatching choices.
4975 mLooper->wake();
4976 }
4977}
4978
4979void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004980 if (DEBUG_FOCUS) {
4981 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
4982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983
4984 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004985 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986
4987 if (mInputFilterEnabled == enabled) {
4988 return;
4989 }
4990
4991 mInputFilterEnabled = enabled;
4992 resetAndDropEverythingLocked("input filter is being enabled or disabled");
4993 } // release lock
4994
4995 // Wake up poll loop since there might be work to do to drop everything.
4996 mLooper->wake();
4997}
4998
Antonio Kantekea47acb2021-12-23 12:41:25 -08004999bool InputDispatcher::setInTouchMode(bool inTouchMode, int32_t pid, int32_t uid,
5000 bool hasPermission) {
Antonio Kantekf16f2832021-09-28 04:39:20 +00005001 bool needWake = false;
5002 {
5003 std::scoped_lock lock(mLock);
5004 if (mInTouchMode == inTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005005 return false;
Antonio Kantekf16f2832021-09-28 04:39:20 +00005006 }
5007 if (DEBUG_TOUCH_MODE) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08005008 ALOGD("Request to change touch mode from %s to %s (calling pid=%d, uid=%d, "
5009 "hasPermission=%s)",
5010 toString(mInTouchMode), toString(inTouchMode), pid, uid, toString(hasPermission));
5011 }
5012 if (!hasPermission) {
Antonio Kantek48710e42022-03-24 14:19:30 -07005013 if (!focusedWindowIsOwnedByLocked(pid, uid) &&
5014 !recentWindowsAreOwnedByLocked(pid, uid)) {
5015 ALOGD("Touch mode switch rejected, caller (pid=%d, uid=%d) doesn't own the focused "
5016 "window nor none of the previously interacted window",
5017 pid, uid);
Antonio Kantekea47acb2021-12-23 12:41:25 -08005018 return false;
5019 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00005020 }
5021
5022 // TODO(b/198499018): Store touch mode per display.
5023 mInTouchMode = inTouchMode;
5024
Antonio Kantekf16f2832021-09-28 04:39:20 +00005025 auto entry = std::make_unique<TouchModeEntry>(mIdGenerator.nextId(), now(), inTouchMode);
5026 needWake = enqueueInboundEventLocked(std::move(entry));
5027 } // release lock
5028
5029 if (needWake) {
5030 mLooper->wake();
5031 }
Antonio Kantekea47acb2021-12-23 12:41:25 -08005032 return true;
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08005033}
5034
Antonio Kantek48710e42022-03-24 14:19:30 -07005035bool InputDispatcher::focusedWindowIsOwnedByLocked(int32_t pid, int32_t uid) {
5036 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
5037 if (focusedToken == nullptr) {
5038 return false;
5039 }
5040 sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(focusedToken);
5041 return isWindowOwnedBy(windowHandle, pid, uid);
5042}
5043
5044bool InputDispatcher::recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) {
5045 return std::find_if(mInteractionConnectionTokens.begin(), mInteractionConnectionTokens.end(),
5046 [&](const sp<IBinder>& connectionToken) REQUIRES(mLock) {
5047 const sp<WindowInfoHandle> windowHandle =
5048 getWindowHandleLocked(connectionToken);
5049 return isWindowOwnedBy(windowHandle, pid, uid);
5050 }) != mInteractionConnectionTokens.end();
5051}
5052
Bernardo Rufinoea97d182020-08-19 14:43:14 +01005053void InputDispatcher::setMaximumObscuringOpacityForTouch(float opacity) {
5054 if (opacity < 0 || opacity > 1) {
5055 LOG_ALWAYS_FATAL("Maximum obscuring opacity for touch should be >= 0 and <= 1");
5056 return;
5057 }
5058
5059 std::scoped_lock lock(mLock);
5060 mMaximumObscuringOpacityForTouch = opacity;
5061}
5062
5063void InputDispatcher::setBlockUntrustedTouchesMode(BlockUntrustedTouchesMode mode) {
5064 std::scoped_lock lock(mLock);
5065 mBlockUntrustedTouchesMode = mode;
5066}
5067
Arthur Hungabbb9d82021-09-01 14:52:30 +00005068std::pair<TouchState*, TouchedWindow*> InputDispatcher::findTouchStateAndWindowLocked(
5069 const sp<IBinder>& token) {
5070 for (auto& [displayId, state] : mTouchStatesByDisplay) {
5071 for (TouchedWindow& w : state.windows) {
5072 if (w.windowHandle->getToken() == token) {
5073 return std::make_pair(&state, &w);
5074 }
5075 }
5076 }
5077 return std::make_pair(nullptr, nullptr);
5078}
5079
arthurhungb89ccb02020-12-30 16:19:01 +08005080bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken,
5081 bool isDragDrop) {
chaviwfbe5d9c2018-12-26 12:23:37 -08005082 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005083 if (DEBUG_FOCUS) {
5084 ALOGD("Trivial transfer to same window.");
5085 }
chaviwfbe5d9c2018-12-26 12:23:37 -08005086 return true;
5087 }
5088
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005090 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091
Arthur Hungabbb9d82021-09-01 14:52:30 +00005092 // Find the target touch state and touched window by fromToken.
5093 auto [state, touchedWindow] = findTouchStateAndWindowLocked(fromToken);
5094 if (state == nullptr || touchedWindow == nullptr) {
5095 ALOGD("Focus transfer failed because from window is not being touched.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 return false;
5097 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005098
5099 const int32_t displayId = state->displayId;
5100 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(toToken, displayId);
5101 if (toWindowHandle == nullptr) {
5102 ALOGW("Cannot transfer focus because to window not found.");
5103 return false;
5104 }
5105
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005106 if (DEBUG_FOCUS) {
5107 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Arthur Hungabbb9d82021-09-01 14:52:30 +00005108 touchedWindow->windowHandle->getName().c_str(),
5109 toWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 }
5111
Arthur Hungabbb9d82021-09-01 14:52:30 +00005112 // Erase old window.
5113 int32_t oldTargetFlags = touchedWindow->targetFlags;
5114 BitSet32 pointerIds = touchedWindow->pointerIds;
5115 state->removeWindowByToken(fromToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116
Arthur Hungabbb9d82021-09-01 14:52:30 +00005117 // Add new window.
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00005118 int32_t newTargetFlags =
5119 oldTargetFlags & (InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
5120 if (canReceiveForegroundTouches(*toWindowHandle->getInfo())) {
5121 newTargetFlags |= InputTarget::FLAG_FOREGROUND;
5122 }
Arthur Hungabbb9d82021-09-01 14:52:30 +00005123 state->addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124
Arthur Hungabbb9d82021-09-01 14:52:30 +00005125 // Store the dragging window.
5126 if (isDragDrop) {
Arthur Hung02701602022-07-15 09:35:36 +00005127 if (pointerIds.count() != 1) {
5128 ALOGW("The drag and drop cannot be started when there is no pointer or more than 1"
5129 " pointer on the window.");
Arthur Hung54745652022-04-20 07:17:41 +00005130 return false;
5131 }
Arthur Hung02701602022-07-15 09:35:36 +00005132 // Track the pointer id for drag window and generate the drag state.
5133 const int32_t id = pointerIds.firstMarkedBit();
Arthur Hung54745652022-04-20 07:17:41 +00005134 mDragState = std::make_unique<DragState>(toWindowHandle, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135 }
5136
Arthur Hungabbb9d82021-09-01 14:52:30 +00005137 // Synthesize cancel for old window and down for new window.
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005138 sp<Connection> fromConnection = getConnectionLocked(fromToken);
5139 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005140 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08005141 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005142 CancelationOptions
5143 options(CancelationOptions::CANCEL_POINTER_EVENTS,
5144 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08005146 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005147 }
5148
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005149 if (DEBUG_FOCUS) {
5150 logDispatchStateLocked();
5151 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 } // release lock
5153
5154 // Wake up poll loop since it may need to make new input dispatching choices.
5155 mLooper->wake();
5156 return true;
5157}
5158
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005159/**
5160 * Get the touched foreground window on the given display.
5161 * Return null if there are no windows touched on that display, or if more than one foreground
5162 * window is being touched.
5163 */
5164sp<WindowInfoHandle> InputDispatcher::findTouchedForegroundWindowLocked(int32_t displayId) const {
5165 auto stateIt = mTouchStatesByDisplay.find(displayId);
5166 if (stateIt == mTouchStatesByDisplay.end()) {
5167 ALOGI("No touch state on display %" PRId32, displayId);
5168 return nullptr;
5169 }
5170
5171 const TouchState& state = stateIt->second;
5172 sp<WindowInfoHandle> touchedForegroundWindow;
5173 // If multiple foreground windows are touched, return nullptr
5174 for (const TouchedWindow& window : state.windows) {
5175 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5176 if (touchedForegroundWindow != nullptr) {
5177 ALOGI("Two or more foreground windows: %s and %s",
5178 touchedForegroundWindow->getName().c_str(),
5179 window.windowHandle->getName().c_str());
5180 return nullptr;
5181 }
5182 touchedForegroundWindow = window.windowHandle;
5183 }
5184 }
5185 return touchedForegroundWindow;
5186}
5187
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005188// Binder call
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005189bool InputDispatcher::transferTouch(const sp<IBinder>& destChannelToken, int32_t displayId) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005190 sp<IBinder> fromToken;
5191 { // acquire lock
5192 std::scoped_lock _l(mLock);
Arthur Hungabbb9d82021-09-01 14:52:30 +00005193 sp<WindowInfoHandle> toWindowHandle = getWindowHandleLocked(destChannelToken, displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005194 if (toWindowHandle == nullptr) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005195 ALOGW("Could not find window associated with token=%p on display %" PRId32,
5196 destChannelToken.get(), displayId);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005197 return false;
5198 }
5199
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07005200 sp<WindowInfoHandle> from = findTouchedForegroundWindowLocked(displayId);
5201 if (from == nullptr) {
5202 ALOGE("Could not find a source window in %s for %p", __func__, destChannelToken.get());
5203 return false;
5204 }
5205
5206 fromToken = from->getToken();
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00005207 } // release lock
5208
5209 return transferTouchFocus(fromToken, destChannelToken);
5210}
5211
Michael Wrightd02c5b62014-02-10 15:10:22 -08005212void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01005213 if (DEBUG_FOCUS) {
5214 ALOGD("Resetting and dropping all events (%s).", reason);
5215 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005216
5217 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
5218 synthesizeCancelationEventsForAllConnectionsLocked(options);
5219
5220 resetKeyRepeatLocked();
5221 releasePendingEventLocked();
5222 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005223 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005224
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005225 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08005226 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005227 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07005228 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229}
5230
5231void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005232 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005233 dumpDispatchStateLocked(dump);
5234
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005235 std::istringstream stream(dump);
5236 std::string line;
5237
5238 while (std::getline(stream, line, '\n')) {
5239 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005240 }
5241}
5242
Prabir Pradhan99987712020-11-10 18:43:05 -08005243std::string InputDispatcher::dumpPointerCaptureStateLocked() {
5244 std::string dump;
5245
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005246 dump += StringPrintf(INDENT "Pointer Capture Requested: %s\n",
5247 toString(mCurrentPointerCaptureRequest.enable));
Prabir Pradhan99987712020-11-10 18:43:05 -08005248
5249 std::string windowName = "None";
5250 if (mWindowTokenWithPointerCapture) {
chaviw98318de2021-05-19 16:45:23 -05005251 const sp<WindowInfoHandle> captureWindowHandle =
Prabir Pradhan99987712020-11-10 18:43:05 -08005252 getWindowHandleLocked(mWindowTokenWithPointerCapture);
5253 windowName = captureWindowHandle ? captureWindowHandle->getName().c_str()
5254 : "token has capture without window";
5255 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005256 dump += StringPrintf(INDENT "Current Window with Pointer Capture: %s\n", windowName.c_str());
Prabir Pradhan99987712020-11-10 18:43:05 -08005257
5258 return dump;
5259}
5260
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005261void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07005262 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
5263 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
5264 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08005265 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266
Tiger Huang721e26f2018-07-24 22:26:19 +08005267 if (!mFocusedApplicationHandlesByDisplay.empty()) {
5268 dump += StringPrintf(INDENT "FocusedApplications:\n");
5269 for (auto& it : mFocusedApplicationHandlesByDisplay) {
5270 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07005271 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005272 const std::chrono::duration timeout =
5273 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005274 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005275 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05005276 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08005277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08005279 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280 }
Tiger Huang721e26f2018-07-24 22:26:19 +08005281
Vishnu Nairc519ff72021-01-21 08:23:08 -08005282 dump += mFocusResolver.dump();
Prabir Pradhan99987712020-11-10 18:43:05 -08005283 dump += dumpPointerCaptureStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005285 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005286 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005287 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
5288 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005289 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005290 state.displayId, toString(state.down), toString(state.split),
5291 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005292 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005293 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005294 for (size_t i = 0; i < state.windows.size(); i++) {
5295 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005296 dump += StringPrintf(INDENT4
5297 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
5298 i, touchedWindow.windowHandle->getName().c_str(),
5299 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08005300 }
5301 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005302 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08005303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304 }
5305 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005306 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307 }
5308
arthurhung6d4bed92021-03-17 11:59:33 +08005309 if (mDragState) {
5310 dump += StringPrintf(INDENT "DragState:\n");
5311 mDragState->dump(dump, INDENT2);
5312 }
5313
Arthur Hungb92218b2018-08-14 12:00:21 +08005314 if (!mWindowHandlesByDisplay.empty()) {
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005315 for (const auto& [displayId, windowHandles] : mWindowHandlesByDisplay) {
5316 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", displayId);
5317 if (const auto& it = mDisplayInfos.find(displayId); it != mDisplayInfos.end()) {
5318 const auto& displayInfo = it->second;
5319 dump += StringPrintf(INDENT2 "logicalSize=%dx%d\n", displayInfo.logicalWidth,
5320 displayInfo.logicalHeight);
5321 displayInfo.transform.dump(dump, "transform", INDENT4);
5322 } else {
5323 dump += INDENT2 "No DisplayInfo found!\n";
5324 }
5325
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005326 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08005327 dump += INDENT2 "Windows:\n";
5328 for (size_t i = 0; i < windowHandles.size(); i++) {
chaviw98318de2021-05-19 16:45:23 -05005329 const sp<WindowInfoHandle>& windowHandle = windowHandles[i];
5330 const WindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005332 dump += StringPrintf(INDENT3 "%zu: name='%s', id=%" PRId32 ", displayId=%d, "
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005333 "inputConfig=%s, alpha=%.2f, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005334 "frame=[%d,%d][%d,%d], globalScale=%f, "
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005335 "applicationInfo.name=%s, "
5336 "applicationInfo.token=%s, "
chaviw1ff3d1e2020-07-01 15:53:47 -07005337 "touchableRegion=",
Bernardo Rufino0f6a36e2020-11-11 10:10:59 +00005338 i, windowInfo->name.c_str(), windowInfo->id,
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005339 windowInfo->displayId,
5340 windowInfo->inputConfig.string().c_str(),
5341 windowInfo->alpha, windowInfo->frameLeft,
5342 windowInfo->frameTop, windowInfo->frameRight,
5343 windowInfo->frameBottom, windowInfo->globalScaleFactor,
Bernardo Rufino49d99e42021-01-18 15:16:59 +00005344 windowInfo->applicationInfo.name.c_str(),
5345 toString(windowInfo->applicationInfo.token).c_str());
Bernardo Rufino53fc31e2020-11-03 11:01:07 +00005346 dump += dumpRegion(windowInfo->touchableRegion);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005347 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005348 "ms, hasToken=%s, "
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005349 "touchOcclusionMode=%s\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005350 windowInfo->ownerPid, windowInfo->ownerUid,
Bernardo Rufinoc2f1fad2020-11-04 17:30:57 +00005351 millis(windowInfo->dispatchingTimeout),
Bernardo Rufino5fd822d2020-11-13 16:11:39 +00005352 toString(windowInfo->token != nullptr),
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07005353 toString(windowInfo->touchOcclusionMode).c_str());
chaviw85b44202020-07-24 11:46:21 -07005354 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08005355 }
5356 } else {
5357 dump += INDENT2 "Windows: <none>\n";
5358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 }
5360 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08005361 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005362 }
5363
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005364 if (!mGlobalMonitorsByDisplay.empty()) {
5365 for (const auto& [displayId, monitors] : mGlobalMonitorsByDisplay) {
5366 dump += StringPrintf(INDENT "Global monitors on display %d:\n", displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00005367 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005369 } else {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005370 dump += INDENT "Global Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371 }
5372
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005373 const nsecs_t currentTime = now();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374
5375 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005376 if (!mRecentQueue.empty()) {
5377 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005378 for (std::shared_ptr<EventEntry>& entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005379 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005380 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005381 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382 }
5383 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005384 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005385 }
5386
5387 // Dump event currently being dispatched.
5388 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005389 dump += INDENT "PendingEvent:\n";
5390 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005391 dump += mPendingEvent->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005392 dump += StringPrintf(", age=%" PRId64 "ms\n",
5393 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005394 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005395 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396 }
5397
5398 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005399 if (!mInboundQueue.empty()) {
5400 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005401 for (std::shared_ptr<EventEntry>& entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005402 dump += INDENT2;
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005403 dump += entry->getDescription();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005404 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405 }
5406 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005407 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 }
5409
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005410 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005411 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07005412 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
5413 const KeyReplacement& replacement = pair.first;
5414 int32_t newKeyCode = pair.second;
5415 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005416 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07005417 }
5418 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005419 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07005420 }
5421
Prabir Pradhancef936d2021-07-21 16:17:52 +00005422 if (!mCommandQueue.empty()) {
5423 dump += StringPrintf(INDENT "CommandQueue: size=%zu\n", mCommandQueue.size());
5424 } else {
5425 dump += INDENT "CommandQueue: <empty>\n";
5426 }
5427
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005428 if (!mConnectionsByToken.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005429 dump += INDENT "Connections:\n";
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005430 for (const auto& [token, connection] : mConnectionsByToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005431 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005432 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005433 connection->inputChannel->getFd().get(),
5434 connection->getInputChannelName().c_str(),
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005435 connection->getWindowName().c_str(),
5436 ftl::enum_string(connection->status).c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005437 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005438
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005439 if (!connection->outboundQueue.empty()) {
5440 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
5441 connection->outboundQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005442 dump += dumpQueue(connection->outboundQueue, currentTime);
5443
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005445 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 }
5447
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005448 if (!connection->waitQueue.empty()) {
5449 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
5450 connection->waitQueue.size());
Siarhei Vishniakou14411c92020-09-18 21:15:05 -05005451 dump += dumpQueue(connection->waitQueue, currentTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005452 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005453 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454 }
5455 }
5456 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005457 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 }
5459
5460 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005461 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
5462 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005464 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 }
5466
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005467 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005468 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
5469 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
5470 ns2ms(mConfig.keyRepeatTimeout));
Siarhei Vishniakouf2652122021-03-05 21:39:46 +00005471 dump += mLatencyTracker.dump(INDENT2);
Siarhei Vishniakoua04181f2021-03-26 05:56:49 +00005472 dump += mLatencyAggregator.dump(INDENT2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005473}
5474
Michael Wright3dd60e22019-03-27 22:06:44 +00005475void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
5476 const size_t numMonitors = monitors.size();
5477 for (size_t i = 0; i < numMonitors; i++) {
5478 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05005479 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005480 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
5481 dump += "\n";
5482 }
5483}
5484
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005485class LooperEventCallback : public LooperCallback {
5486public:
5487 LooperEventCallback(std::function<int(int events)> callback) : mCallback(callback) {}
5488 int handleEvent(int /*fd*/, int events, void* /*data*/) override { return mCallback(events); }
5489
5490private:
5491 std::function<int(int events)> mCallback;
5492};
5493
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005494Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputChannel(const std::string& name) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00005495 if (DEBUG_CHANNEL_CREATION) {
5496 ALOGD("channel '%s' ~ createInputChannel", name.c_str());
5497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005499 std::unique_ptr<InputChannel> serverChannel;
Garfield Tan15601662020-09-22 15:32:38 -07005500 std::unique_ptr<InputChannel> clientChannel;
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005501 status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Garfield Tan15601662020-09-22 15:32:38 -07005502
5503 if (result) {
5504 return base::Error(result) << "Failed to open input channel pair with name " << name;
5505 }
5506
Michael Wrightd02c5b62014-02-10 15:10:22 -08005507 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005508 std::scoped_lock _l(mLock);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005509 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005510 int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005511 sp<Connection> connection =
5512 new Connection(std::move(serverChannel), false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005514 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5515 ALOGE("Created a new connection, but the token %p is already known", token.get());
5516 }
5517 mConnectionsByToken.emplace(token, connection);
5518
5519 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5520 this, std::placeholders::_1, token);
5521
5522 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005523 } // release lock
5524
5525 // Wake the looper because some connections have changed.
5526 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005527 return clientChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528}
5529
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005530Result<std::unique_ptr<InputChannel>> InputDispatcher::createInputMonitor(int32_t displayId,
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +00005531 const std::string& name,
5532 int32_t pid) {
Garfield Tan15601662020-09-22 15:32:38 -07005533 std::shared_ptr<InputChannel> serverChannel;
5534 std::unique_ptr<InputChannel> clientChannel;
5535 status_t result = openInputChannelPair(name, serverChannel, clientChannel);
5536 if (result) {
5537 return base::Error(result) << "Failed to open input channel pair with name " << name;
5538 }
5539
Michael Wright3dd60e22019-03-27 22:06:44 +00005540 { // acquire lock
5541 std::scoped_lock _l(mLock);
5542
5543 if (displayId < 0) {
Garfield Tan15601662020-09-22 15:32:38 -07005544 return base::Error(BAD_VALUE) << "Attempted to create input monitor with name " << name
5545 << " without a specified display.";
Michael Wright3dd60e22019-03-27 22:06:44 +00005546 }
5547
Garfield Tan15601662020-09-22 15:32:38 -07005548 sp<Connection> connection = new Connection(serverChannel, true /*monitor*/, mIdGenerator);
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005549 const sp<IBinder>& token = serverChannel->getConnectionToken();
Garfield Tan15601662020-09-22 15:32:38 -07005550 const int fd = serverChannel->getFd();
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005551
5552 if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
5553 ALOGE("Created a new connection, but the token %p is already known", token.get());
5554 }
5555 mConnectionsByToken.emplace(token, connection);
5556 std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
5557 this, std::placeholders::_1, token);
Michael Wright3dd60e22019-03-27 22:06:44 +00005558
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005559 mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
Michael Wright3dd60e22019-03-27 22:06:44 +00005560
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005561 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, new LooperEventCallback(callback), nullptr);
Michael Wright3dd60e22019-03-27 22:06:44 +00005562 }
Garfield Tan15601662020-09-22 15:32:38 -07005563
Michael Wright3dd60e22019-03-27 22:06:44 +00005564 // Wake the looper because some connections have changed.
5565 mLooper->wake();
Garfield Tan15601662020-09-22 15:32:38 -07005566 return clientChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00005567}
5568
Garfield Tan15601662020-09-22 15:32:38 -07005569status_t InputDispatcher::removeInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005571 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572
Garfield Tan15601662020-09-22 15:32:38 -07005573 status_t status = removeInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574 if (status) {
5575 return status;
5576 }
5577 } // release lock
5578
5579 // Wake the poll loop because removing the connection may have changed the current
5580 // synchronization state.
5581 mLooper->wake();
5582 return OK;
5583}
5584
Garfield Tan15601662020-09-22 15:32:38 -07005585status_t InputDispatcher::removeInputChannelLocked(const sp<IBinder>& connectionToken,
5586 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005587 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005588 if (connection == nullptr) {
Siarhei Vishniakoud706a282021-02-13 00:08:48 +00005589 // Connection can be removed via socket hang up or an explicit call to 'removeInputChannel'
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590 return BAD_VALUE;
5591 }
5592
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005593 removeConnectionLocked(connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07005594
Michael Wrightd02c5b62014-02-10 15:10:22 -08005595 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005596 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597 }
5598
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005599 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600
5601 nsecs_t currentTime = now();
5602 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
5603
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005604 connection->status = Connection::Status::ZOMBIE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 return OK;
5606}
5607
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05005608void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005609 for (auto it = mGlobalMonitorsByDisplay.begin(); it != mGlobalMonitorsByDisplay.end();) {
5610 auto& [displayId, monitors] = *it;
5611 std::erase_if(monitors, [connectionToken](const Monitor& monitor) {
5612 return monitor.inputChannel->getConnectionToken() == connectionToken;
5613 });
Michael Wright3dd60e22019-03-27 22:06:44 +00005614
Michael Wright3dd60e22019-03-27 22:06:44 +00005615 if (monitors.empty()) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005616 it = mGlobalMonitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08005617 } else {
5618 ++it;
5619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620 }
5621}
5622
Michael Wright3dd60e22019-03-27 22:06:44 +00005623status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005624 std::scoped_lock _l(mLock);
Michael Wright3dd60e22019-03-27 22:06:44 +00005625
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005626 const std::shared_ptr<InputChannel> requestingChannel = getInputChannelLocked(token);
5627 if (!requestingChannel) {
5628 ALOGW("Attempted to pilfer pointers from an un-registered channel or invalid token");
5629 return BAD_VALUE;
Michael Wright3dd60e22019-03-27 22:06:44 +00005630 }
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005631
5632 auto [statePtr, windowPtr] = findTouchStateAndWindowLocked(token);
5633 if (statePtr == nullptr || windowPtr == nullptr || !statePtr->down) {
5634 ALOGW("Attempted to pilfer points from a channel without any on-going pointer streams."
5635 " Ignoring.");
5636 return BAD_VALUE;
5637 }
5638
5639 TouchState& state = *statePtr;
5640
5641 // Send cancel events to all the input channels we're stealing from.
5642 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
5643 "input channel stole pointer stream");
5644 options.deviceId = state.deviceId;
5645 options.displayId = state.displayId;
5646 std::string canceledWindows;
5647 for (const TouchedWindow& window : state.windows) {
5648 const std::shared_ptr<InputChannel> channel =
5649 getInputChannelLocked(window.windowHandle->getToken());
5650 if (channel != nullptr && channel->getConnectionToken() != token) {
5651 synthesizeCancelationEventsForInputChannelLocked(channel, options);
5652 canceledWindows += canceledWindows.empty() ? "[" : ", ";
5653 canceledWindows += channel->getName();
5654 }
5655 }
5656 canceledWindows += canceledWindows.empty() ? "[]" : "]";
5657 ALOGI("Channel %s is stealing touch from %s", requestingChannel->getName().c_str(),
5658 canceledWindows.c_str());
5659
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005660 // Prevent the gesture from being sent to any other windows.
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005661 state.filterWindowsExcept(token);
Prabir Pradhane680f9b2022-02-04 04:24:00 -08005662 state.preventNewTargets = true;
Michael Wright3dd60e22019-03-27 22:06:44 +00005663 return OK;
5664}
5665
Prabir Pradhan99987712020-11-10 18:43:05 -08005666void InputDispatcher::requestPointerCapture(const sp<IBinder>& windowToken, bool enabled) {
5667 { // acquire lock
5668 std::scoped_lock _l(mLock);
5669 if (DEBUG_FOCUS) {
chaviw98318de2021-05-19 16:45:23 -05005670 const sp<WindowInfoHandle> windowHandle = getWindowHandleLocked(windowToken);
Prabir Pradhan99987712020-11-10 18:43:05 -08005671 ALOGI("Request to %s Pointer Capture from: %s.", enabled ? "enable" : "disable",
5672 windowHandle != nullptr ? windowHandle->getName().c_str()
5673 : "token without window");
5674 }
5675
Vishnu Nairc519ff72021-01-21 08:23:08 -08005676 const sp<IBinder> focusedToken = mFocusResolver.getFocusedWindowToken(mFocusedDisplayId);
Prabir Pradhan99987712020-11-10 18:43:05 -08005677 if (focusedToken != windowToken) {
5678 ALOGW("Ignoring request to %s Pointer Capture: window does not have focus.",
5679 enabled ? "enable" : "disable");
5680 return;
5681 }
5682
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005683 if (enabled == mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005684 ALOGW("Ignoring request to %s Pointer Capture: "
5685 "window has %s requested pointer capture.",
5686 enabled ? "enable" : "disable", enabled ? "already" : "not");
5687 return;
5688 }
5689
Christine Franksb768bb42021-11-29 12:11:31 -08005690 if (enabled) {
5691 if (std::find(mIneligibleDisplaysForPointerCapture.begin(),
5692 mIneligibleDisplaysForPointerCapture.end(),
5693 mFocusedDisplayId) != mIneligibleDisplaysForPointerCapture.end()) {
5694 ALOGW("Ignoring request to enable Pointer Capture: display is not eligible");
5695 return;
5696 }
5697 }
5698
Prabir Pradhan99987712020-11-10 18:43:05 -08005699 setPointerCaptureLocked(enabled);
5700 } // release lock
5701
5702 // Wake the thread to process command entries.
5703 mLooper->wake();
5704}
5705
Christine Franksb768bb42021-11-29 12:11:31 -08005706void InputDispatcher::setDisplayEligibilityForPointerCapture(int32_t displayId, bool isEligible) {
5707 { // acquire lock
5708 std::scoped_lock _l(mLock);
5709 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
5710 if (!isEligible) {
5711 mIneligibleDisplaysForPointerCapture.push_back(displayId);
5712 }
5713 } // release lock
5714}
5715
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005716std::optional<int32_t> InputDispatcher::findMonitorPidByTokenLocked(const sp<IBinder>& token) {
5717 for (const auto& [_, monitors] : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005718 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07005719 if (monitor.inputChannel->getConnectionToken() == token) {
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005720 return monitor.pid;
Michael Wright3dd60e22019-03-27 22:06:44 +00005721 }
5722 }
5723 }
5724 return std::nullopt;
5725}
5726
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005727sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07005728 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005729 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08005730 }
5731
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005732 for (const auto& [token, connection] : mConnectionsByToken) {
5733 if (token == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005734 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005735 }
5736 }
Robert Carr4e670e52018-08-15 13:26:12 -07005737
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07005738 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005739}
5740
Siarhei Vishniakouad991402020-10-28 11:40:09 -05005741std::string InputDispatcher::getConnectionNameLocked(const sp<IBinder>& connectionToken) const {
5742 sp<Connection> connection = getConnectionLocked(connectionToken);
5743 if (connection == nullptr) {
5744 return "<nullptr>";
5745 }
5746 return connection->getInputChannelName();
5747}
5748
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005749void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005750 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakouae02a1f2021-05-01 23:14:04 +00005751 mConnectionsByToken.erase(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07005752}
5753
Prabir Pradhancef936d2021-07-21 16:17:52 +00005754void InputDispatcher::doDispatchCycleFinishedCommand(nsecs_t finishTime,
5755 const sp<Connection>& connection, uint32_t seq,
5756 bool handled, nsecs_t consumeTime) {
5757 // Handle post-event policy actions.
5758 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
5759 if (dispatchEntryIt == connection->waitQueue.end()) {
5760 return;
5761 }
5762 DispatchEntry* dispatchEntry = *dispatchEntryIt;
5763 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
5764 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
5765 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
5766 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
5767 }
5768 if (shouldReportFinishedEvent(*dispatchEntry, *connection)) {
5769 mLatencyTracker.trackFinishedEvent(dispatchEntry->eventEntry->id,
5770 connection->inputChannel->getConnectionToken(),
5771 dispatchEntry->deliveryTime, consumeTime, finishTime);
5772 }
5773
5774 bool restartEvent;
5775 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
5776 KeyEntry& keyEntry = static_cast<KeyEntry&>(*(dispatchEntry->eventEntry));
5777 restartEvent =
5778 afterKeyEventLockedInterruptable(connection, dispatchEntry, keyEntry, handled);
5779 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
5780 MotionEntry& motionEntry = static_cast<MotionEntry&>(*(dispatchEntry->eventEntry));
5781 restartEvent = afterMotionEventLockedInterruptable(connection, dispatchEntry, motionEntry,
5782 handled);
5783 } else {
5784 restartEvent = false;
5785 }
5786
5787 // Dequeue the event and start the next cycle.
5788 // Because the lock might have been released, it is possible that the
5789 // contents of the wait queue to have been drained, so we need to double-check
5790 // a few things.
5791 dispatchEntryIt = connection->findWaitQueueEntry(seq);
5792 if (dispatchEntryIt != connection->waitQueue.end()) {
5793 dispatchEntry = *dispatchEntryIt;
5794 connection->waitQueue.erase(dispatchEntryIt);
5795 const sp<IBinder>& connectionToken = connection->inputChannel->getConnectionToken();
5796 mAnrTracker.erase(dispatchEntry->timeoutTime, connectionToken);
5797 if (!connection->responsive) {
5798 connection->responsive = isConnectionResponsive(*connection);
5799 if (connection->responsive) {
5800 // The connection was unresponsive, and now it's responsive.
5801 processConnectionResponsiveLocked(*connection);
5802 }
5803 }
5804 traceWaitQueueLength(*connection);
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08005805 if (restartEvent && connection->status == Connection::Status::NORMAL) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005806 connection->outboundQueue.push_front(dispatchEntry);
5807 traceOutboundQueueLength(*connection);
5808 } else {
5809 releaseDispatchEntry(dispatchEntry);
5810 }
5811 }
5812
5813 // Start the next dispatch cycle for this connection.
5814 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005815}
5816
Prabir Pradhancef936d2021-07-21 16:17:52 +00005817void InputDispatcher::sendFocusChangedCommandLocked(const sp<IBinder>& oldToken,
5818 const sp<IBinder>& newToken) {
5819 auto command = [this, oldToken, newToken]() REQUIRES(mLock) {
5820 scoped_unlock unlock(mLock);
5821 mPolicy->notifyFocusChanged(oldToken, newToken);
5822 };
5823 postCommandLocked(std::move(command));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005824}
5825
Prabir Pradhancef936d2021-07-21 16:17:52 +00005826void InputDispatcher::sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) {
5827 auto command = [this, token, x, y]() REQUIRES(mLock) {
5828 scoped_unlock unlock(mLock);
5829 mPolicy->notifyDropWindow(token, x, y);
5830 };
5831 postCommandLocked(std::move(command));
Robert Carrf759f162018-11-13 12:57:11 -08005832}
5833
Prabir Pradhancef936d2021-07-21 16:17:52 +00005834void InputDispatcher::sendUntrustedTouchCommandLocked(const std::string& obscuringPackage) {
5835 auto command = [this, obscuringPackage]() REQUIRES(mLock) {
5836 scoped_unlock unlock(mLock);
5837 mPolicy->notifyUntrustedTouch(obscuringPackage);
5838 };
5839 postCommandLocked(std::move(command));
arthurhungf452d0b2021-01-06 00:19:52 +08005840}
5841
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005842void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
5843 if (connection == nullptr) {
5844 LOG_ALWAYS_FATAL("Caller must check for nullness");
5845 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005846 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
5847 // is already healthy again. Don't raise ANR in this situation
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005848 if (connection->waitQueue.empty()) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005849 ALOGI("Not raising ANR because the connection %s has recovered",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005850 connection->inputChannel->getName().c_str());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005851 return;
5852 }
5853 /**
5854 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
5855 * may not be the one that caused the timeout to occur. One possibility is that window timeout
5856 * has changed. This could cause newer entries to time out before the already dispatched
5857 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
5858 * processes the events linearly. So providing information about the oldest entry seems to be
5859 * most useful.
5860 */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005861 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005862 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
5863 std::string reason =
5864 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005865 connection->inputChannel->getName().c_str(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005866 ns2ms(currentWait),
5867 oldestEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005868 sp<IBinder> connectionToken = connection->inputChannel->getConnectionToken();
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -06005869 updateLastAnrStateLocked(getWindowHandleLocked(connectionToken), reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005870
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005871 processConnectionUnresponsiveLocked(*connection, std::move(reason));
5872
5873 // Stop waking up for events on this connection, it is already unresponsive
5874 cancelEventsForAnrLocked(connection);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005875}
5876
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005877void InputDispatcher::onAnrLocked(std::shared_ptr<InputApplicationHandle> application) {
5878 std::string reason =
5879 StringPrintf("%s does not have a focused window", application->getName().c_str());
5880 updateLastAnrStateLocked(*application, reason);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005881
Yabin Cui8eb9c552023-06-08 18:05:07 +00005882 auto command = [this, app = std::move(application)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005883 scoped_unlock unlock(mLock);
Yabin Cui8eb9c552023-06-08 18:05:07 +00005884 mPolicy->notifyNoFocusedWindowAnr(app);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005885 };
5886 postCommandLocked(std::move(command));
Bernardo Rufino2e1f6512020-10-08 13:42:07 +00005887}
5888
chaviw98318de2021-05-19 16:45:23 -05005889void InputDispatcher::updateLastAnrStateLocked(const sp<WindowInfoHandle>& window,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005890 const std::string& reason) {
5891 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
5892 updateLastAnrStateLocked(windowLabel, reason);
5893}
5894
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005895void InputDispatcher::updateLastAnrStateLocked(const InputApplicationHandle& application,
5896 const std::string& reason) {
5897 const std::string windowLabel = getApplicationWindowLabel(&application, nullptr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005898 updateLastAnrStateLocked(windowLabel, reason);
5899}
5900
5901void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
5902 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005903 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07005904 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005905 struct tm tm;
5906 localtime_r(&t, &tm);
5907 char timestr[64];
5908 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005909 mLastAnrState.clear();
5910 mLastAnrState += INDENT "ANR:\n";
5911 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005912 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
5913 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005914 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005915}
5916
Prabir Pradhancef936d2021-07-21 16:17:52 +00005917void InputDispatcher::doInterceptKeyBeforeDispatchingCommand(const sp<IBinder>& focusedWindowToken,
5918 KeyEntry& entry) {
5919 const KeyEvent event = createKeyEvent(entry);
5920 nsecs_t delay = 0;
5921 { // release lock
5922 scoped_unlock unlock(mLock);
5923 android::base::Timer t;
5924 delay = mPolicy->interceptKeyBeforeDispatching(focusedWindowToken, &event,
5925 entry.policyFlags);
5926 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
5927 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
5928 std::to_string(t.duration().count()).c_str());
5929 }
5930 } // acquire lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931
5932 if (delay < 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005933 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
Prabir Pradhancef936d2021-07-21 16:17:52 +00005934 } else if (delay == 0) {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005935 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936 } else {
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07005937 entry.interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
5938 entry.interceptKeyWakeupTime = now() + delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005940}
5941
Prabir Pradhancef936d2021-07-21 16:17:52 +00005942void InputDispatcher::sendWindowUnresponsiveCommandLocked(const sp<IBinder>& token,
Prabir Pradhanedd96402022-02-15 01:46:16 -08005943 std::optional<int32_t> pid,
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005944 std::string reason) {
Yabin Cui8eb9c552023-06-08 18:05:07 +00005945 auto command = [this, token, pid, r = std::move(reason)]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005946 scoped_unlock unlock(mLock);
Yabin Cui8eb9c552023-06-08 18:05:07 +00005947 mPolicy->notifyWindowUnresponsive(token, pid, r);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005948 };
5949 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005950}
5951
Prabir Pradhanedd96402022-02-15 01:46:16 -08005952void InputDispatcher::sendWindowResponsiveCommandLocked(const sp<IBinder>& token,
5953 std::optional<int32_t> pid) {
5954 auto command = [this, token, pid]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00005955 scoped_unlock unlock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005956 mPolicy->notifyWindowResponsive(token, pid);
Prabir Pradhancef936d2021-07-21 16:17:52 +00005957 };
5958 postCommandLocked(std::move(command));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005959}
5960
5961/**
5962 * Tell the policy that a connection has become unresponsive so that it can start ANR.
5963 * Check whether the connection of interest is a monitor or a window, and add the corresponding
5964 * command entry to the command queue.
5965 */
5966void InputDispatcher::processConnectionUnresponsiveLocked(const Connection& connection,
5967 std::string reason) {
5968 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005969 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005970 if (connection.monitor) {
5971 ALOGW("Monitor %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5972 reason.c_str());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005973 pid = findMonitorPidByTokenLocked(connectionToken);
5974 } else {
5975 // The connection is a window
5976 ALOGW("Window %s is unresponsive: %s", connection.inputChannel->getName().c_str(),
5977 reason.c_str());
5978 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5979 if (handle != nullptr) {
5980 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005981 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005982 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08005983 sendWindowUnresponsiveCommandLocked(connectionToken, pid, std::move(reason));
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005984}
5985
5986/**
5987 * Tell the policy that a connection has become responsive so that it can stop ANR.
5988 */
5989void InputDispatcher::processConnectionResponsiveLocked(const Connection& connection) {
5990 const sp<IBinder>& connectionToken = connection.inputChannel->getConnectionToken();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005991 std::optional<int32_t> pid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005992 if (connection.monitor) {
Prabir Pradhanedd96402022-02-15 01:46:16 -08005993 pid = findMonitorPidByTokenLocked(connectionToken);
5994 } else {
5995 // The connection is a window
5996 const sp<WindowInfoHandle> handle = getWindowHandleLocked(connectionToken);
5997 if (handle != nullptr) {
5998 pid = handle->getInfo()->ownerPid;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005999 }
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006000 }
Prabir Pradhanedd96402022-02-15 01:46:16 -08006001 sendWindowResponsiveCommandLocked(connectionToken, pid);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00006002}
6003
Prabir Pradhancef936d2021-07-21 16:17:52 +00006004bool InputDispatcher::afterKeyEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006005 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006006 KeyEntry& keyEntry, bool handled) {
6007 if (keyEntry.flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006008 if (!handled) {
6009 // Report the key as unhandled, since the fallback was not handled.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006010 mReporter->reportUnhandledKey(keyEntry.id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006011 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006012 return false;
6013 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006014
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006015 // Get the fallback key state.
6016 // Clear it out after dispatching the UP.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006017 int32_t originalKeyCode = keyEntry.keyCode;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006018 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006019 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006020 connection->inputState.removeFallbackKey(originalKeyCode);
6021 }
6022
6023 if (handled || !dispatchEntry->hasForegroundTarget()) {
6024 // If the application handles the original key for which we previously
6025 // generated a fallback or if the window is not a foreground window,
6026 // then cancel the associated fallback key, if any.
6027 if (fallbackKeyCode != -1) {
6028 // Dispatch the unhandled key to the policy with the cancel flag.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006029 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6030 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
6031 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6032 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount,
6033 keyEntry.policyFlags);
6034 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006035 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006036 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006037
6038 mLock.unlock();
6039
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006040 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006041 keyEntry.policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006042
6043 mLock.lock();
6044
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006045 // Cancel the fallback key.
6046 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006047 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006048 "application handled the original non-fallback key "
6049 "or is no longer a foreground target, "
6050 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08006051 options.keyCode = fallbackKeyCode;
6052 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006053 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006054 connection->inputState.removeFallbackKey(originalKeyCode);
6055 }
6056 } else {
6057 // If the application did not handle a non-fallback key, first check
6058 // that we are in a good state to perform unhandled key event processing
6059 // Then ask the policy what to do with it.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006060 bool initialDown = keyEntry.action == AKEY_EVENT_ACTION_DOWN && keyEntry.repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006061 if (fallbackKeyCode == -1 && !initialDown) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006062 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6063 ALOGD("Unhandled key event: Skipping unhandled key event processing "
6064 "since this is not an initial down. "
6065 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6066 originalKeyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6067 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006068 return false;
6069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006070
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006071 // Dispatch the unhandled key to the policy.
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006072 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6073 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
6074 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
6075 keyEntry.keyCode, keyEntry.action, keyEntry.repeatCount, keyEntry.policyFlags);
6076 }
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006077 KeyEvent event = createKeyEvent(keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006078
6079 mLock.unlock();
6080
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07006081 bool fallback =
6082 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006083 &event, keyEntry.policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006084
6085 mLock.lock();
6086
Siarhei Vishniakouf12f2f72021-11-17 17:49:45 -08006087 if (connection->status != Connection::Status::NORMAL) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006088 connection->inputState.removeFallbackKey(originalKeyCode);
6089 return false;
6090 }
6091
6092 // Latch the fallback keycode for this key on an initial down.
6093 // The fallback keycode cannot change at any other point in the lifecycle.
6094 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006095 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006096 fallbackKeyCode = event.getKeyCode();
6097 } else {
6098 fallbackKeyCode = AKEYCODE_UNKNOWN;
6099 }
6100 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
6101 }
6102
6103 ALOG_ASSERT(fallbackKeyCode != -1);
6104
6105 // Cancel the fallback key if the policy decides not to send it anymore.
6106 // We will continue to dispatch the key to the policy but we will no
6107 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006108 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
6109 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006110 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6111 if (fallback) {
6112 ALOGD("Unhandled key event: Policy requested to send key %d"
6113 "as a fallback for %d, but on the DOWN it had requested "
6114 "to send %d instead. Fallback canceled.",
6115 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
6116 } else {
6117 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
6118 "but on the DOWN it had requested to send %d. "
6119 "Fallback canceled.",
6120 originalKeyCode, fallbackKeyCode);
6121 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006122 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006123
6124 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
6125 "canceling fallback, policy no longer desires it");
6126 options.keyCode = fallbackKeyCode;
6127 synthesizeCancelationEventsForConnectionLocked(connection, options);
6128
6129 fallback = false;
6130 fallbackKeyCode = AKEYCODE_UNKNOWN;
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006131 if (keyEntry.action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006132 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006133 }
6134 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006135
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006136 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6137 {
6138 std::string msg;
6139 const KeyedVector<int32_t, int32_t>& fallbackKeys =
6140 connection->inputState.getFallbackKeys();
6141 for (size_t i = 0; i < fallbackKeys.size(); i++) {
6142 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
6143 }
6144 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
6145 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006146 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006147 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006148
6149 if (fallback) {
6150 // Restart the dispatch cycle using the fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006151 keyEntry.eventTime = event.getEventTime();
6152 keyEntry.deviceId = event.getDeviceId();
6153 keyEntry.source = event.getSource();
6154 keyEntry.displayId = event.getDisplayId();
6155 keyEntry.flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
6156 keyEntry.keyCode = fallbackKeyCode;
6157 keyEntry.scanCode = event.getScanCode();
6158 keyEntry.metaState = event.getMetaState();
6159 keyEntry.repeatCount = event.getRepeatCount();
6160 keyEntry.downTime = event.getDownTime();
6161 keyEntry.syntheticRepeat = false;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006162
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006163 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6164 ALOGD("Unhandled key event: Dispatching fallback key. "
6165 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
6166 originalKeyCode, fallbackKeyCode, keyEntry.metaState);
6167 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08006168 return true; // restart the event
6169 } else {
Prabir Pradhan61a5d242021-07-26 16:41:09 +00006170 if (DEBUG_OUTBOUND_EVENT_DETAILS) {
6171 ALOGD("Unhandled key event: No fallback key.");
6172 }
Prabir Pradhanf93562f2018-11-29 12:13:37 -08006173
6174 // Report the key as unhandled, since there is no fallback key.
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006175 mReporter->reportUnhandledKey(keyEntry.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006176 }
6177 }
6178 return false;
6179}
6180
Prabir Pradhancef936d2021-07-21 16:17:52 +00006181bool InputDispatcher::afterMotionEventLockedInterruptable(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07006182 DispatchEntry* dispatchEntry,
Siarhei Vishniakoua9a7ee82019-10-14 16:28:19 -07006183 MotionEntry& motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006184 return false;
6185}
6186
Michael Wrightd02c5b62014-02-10 15:10:22 -08006187void InputDispatcher::traceInboundQueueLengthLocked() {
6188 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07006189 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006190 }
6191}
6192
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006193void InputDispatcher::traceOutboundQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006194 if (ATRACE_ENABLED()) {
6195 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006196 snprintf(counterName, sizeof(counterName), "oq:%s", connection.getWindowName().c_str());
6197 ATRACE_INT(counterName, connection.outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006198 }
6199}
6200
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006201void InputDispatcher::traceWaitQueueLength(const Connection& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006202 if (ATRACE_ENABLED()) {
6203 char counterName[40];
Siarhei Vishniakou060a7272021-02-03 19:40:10 +00006204 snprintf(counterName, sizeof(counterName), "wq:%s", connection.getWindowName().c_str());
6205 ATRACE_INT(counterName, connection.waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08006206 }
6207}
6208
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006209void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006210 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006211
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006212 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08006213 dumpDispatchStateLocked(dump);
6214
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006215 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006216 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07006217 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218 }
6219}
6220
6221void InputDispatcher::monitor() {
6222 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006223 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006224 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08006225 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226}
6227
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08006228/**
6229 * Wake up the dispatcher and wait until it processes all events and commands.
6230 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
6231 * this method can be safely called from any thread, as long as you've ensured that
6232 * the work you are interested in completing has already been queued.
6233 */
6234bool InputDispatcher::waitForIdle() {
6235 /**
6236 * Timeout should represent the longest possible time that a device might spend processing
6237 * events and commands.
6238 */
6239 constexpr std::chrono::duration TIMEOUT = 100ms;
6240 std::unique_lock lock(mLock);
6241 mLooper->wake();
6242 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
6243 return result == std::cv_status::no_timeout;
6244}
6245
Vishnu Naire798b472020-07-23 13:52:21 -07006246/**
6247 * Sets focus to the window identified by the token. This must be called
6248 * after updating any input window handles.
6249 *
6250 * Params:
6251 * request.token - input channel token used to identify the window that should gain focus.
6252 * request.focusedToken - the token that the caller expects currently to be focused. If the
6253 * specified token does not match the currently focused window, this request will be dropped.
6254 * If the specified focused token matches the currently focused window, the call will succeed.
6255 * Set this to "null" if this call should succeed no matter what the currently focused token is.
6256 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
6257 * when requesting the focus change. This determines which request gets
6258 * precedence if there is a focus change request from another source such as pointer down.
6259 */
Vishnu Nair958da932020-08-21 17:12:37 -07006260void InputDispatcher::setFocusedWindow(const FocusRequest& request) {
6261 { // acquire lock
6262 std::scoped_lock _l(mLock);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006263 std::optional<FocusResolver::FocusChanges> changes =
6264 mFocusResolver.setFocusedWindow(request, getWindowHandlesLocked(request.displayId));
6265 if (changes) {
6266 onFocusChangedLocked(*changes);
Vishnu Nair958da932020-08-21 17:12:37 -07006267 }
6268 } // release lock
6269 // Wake up poll loop since it may need to make new input dispatching choices.
6270 mLooper->wake();
6271}
6272
Vishnu Nairc519ff72021-01-21 08:23:08 -08006273void InputDispatcher::onFocusChangedLocked(const FocusResolver::FocusChanges& changes) {
6274 if (changes.oldFocus) {
6275 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(changes.oldFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006276 if (focusedInputChannel) {
6277 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
6278 "focus left window");
6279 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairc519ff72021-01-21 08:23:08 -08006280 enqueueFocusEventLocked(changes.oldFocus, false /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006281 }
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006282 }
Vishnu Nairc519ff72021-01-21 08:23:08 -08006283 if (changes.newFocus) {
6284 enqueueFocusEventLocked(changes.newFocus, true /*hasFocus*/, changes.reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006285 }
6286
Prabir Pradhan99987712020-11-10 18:43:05 -08006287 // If a window has pointer capture, then it must have focus. We need to ensure that this
6288 // contract is upheld when pointer capture is being disabled due to a loss of window focus.
6289 // If the window loses focus before it loses pointer capture, then the window can be in a state
6290 // where it has pointer capture but not focus, violating the contract. Therefore we must
6291 // dispatch the pointer capture event before the focus event. Since focus events are added to
6292 // the front of the queue (above), we add the pointer capture event to the front of the queue
6293 // after the focus events are added. This ensures the pointer capture event ends up at the
6294 // front.
6295 disablePointerCaptureForcedLocked();
6296
Vishnu Nairc519ff72021-01-21 08:23:08 -08006297 if (mFocusedDisplayId == changes.displayId) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006298 sendFocusChangedCommandLocked(changes.oldFocus, changes.newFocus);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07006299 }
6300}
Vishnu Nair958da932020-08-21 17:12:37 -07006301
Prabir Pradhan99987712020-11-10 18:43:05 -08006302void InputDispatcher::disablePointerCaptureForcedLocked() {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006303 if (!mCurrentPointerCaptureRequest.enable && !mWindowTokenWithPointerCapture) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006304 return;
6305 }
6306
6307 ALOGD_IF(DEBUG_FOCUS, "Disabling Pointer Capture because the window lost focus.");
6308
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006309 if (mCurrentPointerCaptureRequest.enable) {
Prabir Pradhan99987712020-11-10 18:43:05 -08006310 setPointerCaptureLocked(false);
6311 }
6312
6313 if (!mWindowTokenWithPointerCapture) {
6314 // No need to send capture changes because no window has capture.
6315 return;
6316 }
6317
6318 if (mPendingEvent != nullptr) {
6319 // Move the pending event to the front of the queue. This will give the chance
6320 // for the pending event to be dropped if it is a captured event.
6321 mInboundQueue.push_front(mPendingEvent);
6322 mPendingEvent = nullptr;
6323 }
6324
6325 auto entry = std::make_unique<PointerCaptureChangedEntry>(mIdGenerator.nextId(), now(),
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006326 mCurrentPointerCaptureRequest);
Prabir Pradhan99987712020-11-10 18:43:05 -08006327 mInboundQueue.push_front(std::move(entry));
6328}
6329
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006330void InputDispatcher::setPointerCaptureLocked(bool enable) {
6331 mCurrentPointerCaptureRequest.enable = enable;
6332 mCurrentPointerCaptureRequest.seq++;
6333 auto command = [this, request = mCurrentPointerCaptureRequest]() REQUIRES(mLock) {
Prabir Pradhancef936d2021-07-21 16:17:52 +00006334 scoped_unlock unlock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00006335 mPolicy->setPointerCapture(request);
Prabir Pradhancef936d2021-07-21 16:17:52 +00006336 };
6337 postCommandLocked(std::move(command));
Prabir Pradhan99987712020-11-10 18:43:05 -08006338}
6339
Vishnu Nair599f1412021-06-21 10:39:58 -07006340void InputDispatcher::displayRemoved(int32_t displayId) {
6341 { // acquire lock
6342 std::scoped_lock _l(mLock);
6343 // Set an empty list to remove all handles from the specific display.
6344 setInputWindowsLocked(/* window handles */ {}, displayId);
6345 setFocusedApplicationLocked(displayId, nullptr);
6346 // Call focus resolver to clean up stale requests. This must be called after input windows
6347 // have been removed for the removed display.
6348 mFocusResolver.displayRemoved(displayId);
Christine Franksb768bb42021-11-29 12:11:31 -08006349 // Reset pointer capture eligibility, regardless of previous state.
6350 std::erase(mIneligibleDisplaysForPointerCapture, displayId);
Vishnu Nair599f1412021-06-21 10:39:58 -07006351 } // release lock
6352
6353 // Wake up poll loop since it may need to make new input dispatching choices.
6354 mLooper->wake();
6355}
6356
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006357void InputDispatcher::onWindowInfosChanged(const std::vector<WindowInfo>& windowInfos,
6358 const std::vector<DisplayInfo>& displayInfos) {
chaviw15fab6f2021-06-07 14:15:52 -05006359 // The listener sends the windows as a flattened array. Separate the windows by display for
6360 // more convenient parsing.
6361 std::unordered_map<int32_t, std::vector<sp<WindowInfoHandle>>> handlesPerDisplay;
chaviw15fab6f2021-06-07 14:15:52 -05006362 for (const auto& info : windowInfos) {
6363 handlesPerDisplay.emplace(info.displayId, std::vector<sp<WindowInfoHandle>>());
6364 handlesPerDisplay[info.displayId].push_back(new WindowInfoHandle(info));
6365 }
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006366
6367 { // acquire lock
6368 std::scoped_lock _l(mLock);
Prabir Pradhan73fe4812022-07-22 20:22:18 +00006369
6370 // Ensure that we have an entry created for all existing displays so that if a displayId has
6371 // no windows, we can tell that the windows were removed from the display.
6372 for (const auto& [displayId, _] : mWindowHandlesByDisplay) {
6373 handlesPerDisplay[displayId];
6374 }
6375
Prabir Pradhan48f8cb92021-08-26 14:05:36 -07006376 mDisplayInfos.clear();
6377 for (const auto& displayInfo : displayInfos) {
6378 mDisplayInfos.emplace(displayInfo.displayId, displayInfo);
6379 }
6380
6381 for (const auto& [displayId, handles] : handlesPerDisplay) {
6382 setInputWindowsLocked(handles, displayId);
6383 }
6384 }
6385 // Wake up poll loop since it may need to make new input dispatching choices.
6386 mLooper->wake();
chaviw15fab6f2021-06-07 14:15:52 -05006387}
6388
Vishnu Nair062a8672021-09-03 16:07:44 -07006389bool InputDispatcher::shouldDropInput(
6390 const EventEntry& entry, const sp<android::gui::WindowInfoHandle>& windowHandle) const {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006391 if (windowHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::DROP_INPUT) ||
6392 (windowHandle->getInfo()->inputConfig.test(
6393 WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED) &&
Vishnu Nair062a8672021-09-03 16:07:44 -07006394 isWindowObscuredLocked(windowHandle))) {
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006395 ALOGW("Dropping %s event targeting %s as requested by the input configuration {%s} on "
6396 "display %" PRId32 ".",
Vishnu Nair062a8672021-09-03 16:07:44 -07006397 ftl::enum_string(entry.type).c_str(), windowHandle->getName().c_str(),
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006398 windowHandle->getInfo()->inputConfig.string().c_str(),
Vishnu Nair062a8672021-09-03 16:07:44 -07006399 windowHandle->getInfo()->displayId);
6400 return true;
6401 }
6402 return false;
6403}
6404
Siarhei Vishniakou18050092021-09-01 13:32:49 -07006405void InputDispatcher::DispatcherWindowListener::onWindowInfosChanged(
6406 const std::vector<gui::WindowInfo>& windowInfos,
6407 const std::vector<DisplayInfo>& displayInfos) {
6408 mDispatcher.onWindowInfosChanged(windowInfos, displayInfos);
6409}
6410
Arthur Hungdfd528e2021-12-08 13:23:04 +00006411void InputDispatcher::cancelCurrentTouch() {
6412 {
6413 std::scoped_lock _l(mLock);
6414 ALOGD("Canceling all ongoing pointer gestures on all displays.");
6415 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
6416 "cancel current touch");
6417 synthesizeCancelationEventsForAllConnectionsLocked(options);
6418
6419 mTouchStatesByDisplay.clear();
6420 mLastHoverWindowHandle.clear();
6421 }
6422 // Wake up poll loop since there might be work to do.
6423 mLooper->wake();
6424}
6425
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006426void InputDispatcher::setMonitorDispatchingTimeoutForTest(std::chrono::nanoseconds timeout) {
6427 std::scoped_lock _l(mLock);
6428 mMonitorDispatchingTimeout = timeout;
6429}
6430
Garfield Tane84e6f92019-08-29 17:28:41 -07006431} // namespace android::inputdispatcher