blob: b428c4ec1f2a0e65c8c012e5f4a97f0b16b4ade2 [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
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wright2b3c3302018-03-02 17:19:13 +000048#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080049#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050050#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070051#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080052#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010053#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070054#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000055#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070056#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <statslog.h>
58#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
Michael Wright44753b12020-07-08 13:48:11 +010061#include <cerrno>
62#include <cinttypes>
63#include <climits>
64#include <cstddef>
65#include <ctime>
66#include <queue>
67#include <sstream>
68
69#include "Connection.h"
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071#define INDENT " "
72#define INDENT2 " "
73#define INDENT3 " "
74#define INDENT4 " "
75
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076using android::base::StringPrintf;
77
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Default input dispatching timeout if there is no focused application or paused window
81// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050082constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
83 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow for all pending events to be processed when an app switch
86// key is on the way. This is used to preempt input dispatch and drop input events
87// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for an event to be dispatched (measured since its eventTime)
91// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Michael Wrightd02c5b62014-02-10 15:10:22 -080094// 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 +000095constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
96
97// Log a warning when an interception call takes longer than this to process.
98constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700100// Additional key latency in case a connection is still processing some motion events.
101// This will help with the case when a user touched a button that opens a new window,
102// and gives us the chance to dispatch the key to this new window.
103constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
107
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108// Event log tags. See EventLogTags.logtags for reference
109constexpr int LOGTAG_INPUT_INTERACTION = 62000;
110constexpr int LOGTAG_INPUT_FOCUS = 62001;
111
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112static inline nsecs_t now() {
113 return systemTime(SYSTEM_TIME_MONOTONIC);
114}
115
116static inline const char* toString(bool value) {
117 return value ? "true" : "false";
118}
119
120static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700121 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
122 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123}
124
125static bool isValidKeyAction(int32_t action) {
126 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700127 case AKEY_EVENT_ACTION_DOWN:
128 case AKEY_EVENT_ACTION_UP:
129 return true;
130 default:
131 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 }
133}
134
135static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700136 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137 ALOGE("Key event has invalid action code 0x%x", action);
138 return false;
139 }
140 return true;
141}
142
Michael Wright7b159c92015-05-14 14:48:03 +0100143static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700145 case AMOTION_EVENT_ACTION_DOWN:
146 case AMOTION_EVENT_ACTION_UP:
147 case AMOTION_EVENT_ACTION_CANCEL:
148 case AMOTION_EVENT_ACTION_MOVE:
149 case AMOTION_EVENT_ACTION_OUTSIDE:
150 case AMOTION_EVENT_ACTION_HOVER_ENTER:
151 case AMOTION_EVENT_ACTION_HOVER_MOVE:
152 case AMOTION_EVENT_ACTION_HOVER_EXIT:
153 case AMOTION_EVENT_ACTION_SCROLL:
154 return true;
155 case AMOTION_EVENT_ACTION_POINTER_DOWN:
156 case AMOTION_EVENT_ACTION_POINTER_UP: {
157 int32_t index = getMotionEventActionPointerIndex(action);
158 return index >= 0 && index < pointerCount;
159 }
160 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
161 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
162 return actionButton != 0;
163 default:
164 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 }
166}
167
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500168static int64_t millis(std::chrono::nanoseconds t) {
169 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
170}
171
Michael Wright7b159c92015-05-14 14:48:03 +0100172static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 const PointerProperties* pointerProperties) {
174 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 ALOGE("Motion event has invalid action code 0x%x", action);
176 return false;
177 }
178 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000179 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700180 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 return false;
182 }
183 BitSet32 pointerIdBits;
184 for (size_t i = 0; i < pointerCount; i++) {
185 int32_t id = pointerProperties[i].id;
186 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700187 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
188 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 return false;
190 }
191 if (pointerIdBits.hasBit(id)) {
192 ALOGE("Motion event has duplicate pointer id %d", id);
193 return false;
194 }
195 pointerIdBits.markBit(id);
196 }
197 return true;
198}
199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800200static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800202 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 return;
204 }
205
206 bool first = true;
207 Region::const_iterator cur = region.begin();
208 Region::const_iterator const tail = region.end();
209 while (cur != tail) {
210 if (first) {
211 first = false;
212 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800213 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800215 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 cur++;
217 }
218}
219
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700220/**
221 * Find the entry in std::unordered_map by key, and return it.
222 * If the entry is not found, return a default constructed entry.
223 *
224 * Useful when the entries are vectors, since an empty vector will be returned
225 * if the entry is not found.
226 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
227 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700228template <typename K, typename V>
229static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700230 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700231 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800232}
233
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700234/**
235 * Find the entry in std::unordered_map by value, and remove it.
236 * If more than one entry has the same value, then all matching
237 * key-value pairs will be removed.
238 *
239 * Return true if at least one value has been removed.
240 */
241template <typename K, typename V>
242static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
243 bool removed = false;
244 for (auto it = map.begin(); it != map.end();) {
245 if (it->second == value) {
246 it = map.erase(it);
247 removed = true;
248 } else {
249 it++;
250 }
251 }
252 return removed;
253}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254
chaviwaf87b3e2019-10-01 16:59:28 -0700255static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
256 if (first == second) {
257 return true;
258 }
259
260 if (first == nullptr || second == nullptr) {
261 return false;
262 }
263
264 return first->getToken() == second->getToken();
265}
266
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800267static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
268 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
269}
270
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000271static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
272 EventEntry* eventEntry,
273 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700274 if (inputTarget.useDefaultPointerTransform()) {
275 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000276 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700277 inputTargetFlags, transform,
278 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000279 }
280
281 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
282 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
283
284 PointerCoords pointerCoords[motionEntry.pointerCount];
285
286 // Use the first pointer information to normalize all other pointers. This could be any pointer
287 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700288 // uses the transform for the normalized pointer.
289 const ui::Transform& firstPointerTransform =
290 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
291 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000292
293 // Iterate through all pointers in the event to normalize against the first.
294 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
295 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
296 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700297 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000298
299 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700300 // First, apply the current pointer's transform to update the coordinates into
301 // window space.
302 pointerCoords[pointerIndex].transform(currTransform);
303 // Next, apply the inverse transform of the normalized coordinates so the
304 // current coordinates are transformed into the normalized coordinate space.
305 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000306 }
307
308 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800309 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000310 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
311 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
312 motionEntry.metaState, motionEntry.buttonState,
313 motionEntry.classification, motionEntry.edgeFlags,
314 motionEntry.xPrecision, motionEntry.yPrecision,
315 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
316 motionEntry.downTime, motionEntry.pointerCount,
317 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
318 0 /* yOffset */);
319
320 if (motionEntry.injectionState) {
321 combinedMotionEntry->injectionState = motionEntry.injectionState;
322 combinedMotionEntry->injectionState->refCount += 1;
323 }
324
325 std::unique_ptr<DispatchEntry> dispatchEntry =
326 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700327 inputTargetFlags, firstPointerTransform,
328 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000329 combinedMotionEntry->release();
330 return dispatchEntry;
331}
332
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700333static void addGestureMonitors(const std::vector<Monitor>& monitors,
334 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
335 float yOffset = 0) {
336 if (monitors.empty()) {
337 return;
338 }
339 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
340 for (const Monitor& monitor : monitors) {
341 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
342 }
343}
344
Michael Wrightd02c5b62014-02-10 15:10:22 -0800345// --- InputDispatcher ---
346
Garfield Tan00f511d2019-06-12 16:55:40 -0700347InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
348 : mPolicy(policy),
349 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700350 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800351 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700352 mAppSwitchSawKeyDown(false),
353 mAppSwitchDueTime(LONG_LONG_MAX),
354 mNextUnblockedEvent(nullptr),
355 mDispatchEnabled(false),
356 mDispatchFrozen(false),
357 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800358 // mInTouchMode will be initialized by the WindowManager to the default device config.
359 // To avoid leaking stack in case that call never comes, and for tests,
360 // initialize it here anyways.
361 mInTouchMode(true),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700362 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800363 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800364 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800365
Yi Kong9b14ac62018-07-17 13:48:38 -0700366 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800367
368 policy->getDispatcherConfiguration(&mConfig);
369}
370
371InputDispatcher::~InputDispatcher() {
372 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800373 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800374
375 resetKeyRepeatLocked();
376 releasePendingEventLocked();
377 drainInboundQueueLocked();
378 }
379
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700380 while (!mConnectionsByFd.empty()) {
381 sp<Connection> connection = mConnectionsByFd.begin()->second;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500382 unregisterInputChannel(*connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800383 }
384}
385
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700386status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700387 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700388 return ALREADY_EXISTS;
389 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700390 mThread = std::make_unique<InputThread>(
391 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
392 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700393}
394
395status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700396 if (mThread && mThread->isCallingThread()) {
397 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700398 return INVALID_OPERATION;
399 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700400 mThread.reset();
401 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700402}
403
Michael Wrightd02c5b62014-02-10 15:10:22 -0800404void InputDispatcher::dispatchOnce() {
405 nsecs_t nextWakeupTime = LONG_LONG_MAX;
406 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800407 std::scoped_lock _l(mLock);
408 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409
410 // Run a dispatch loop if there are no pending commands.
411 // The dispatch loop might enqueue commands to run afterwards.
412 if (!haveCommandsLocked()) {
413 dispatchOnceInnerLocked(&nextWakeupTime);
414 }
415
416 // Run all pending commands if there are any.
417 // If any commands were run then force the next poll to wake up immediately.
418 if (runCommandsLockedInterruptible()) {
419 nextWakeupTime = LONG_LONG_MIN;
420 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800421
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700422 // If we are still waiting for ack on some events,
423 // we might have to wake up earlier to check if an app is anr'ing.
424 const nsecs_t nextAnrCheck = processAnrsLocked();
425 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
426
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800427 // We are about to enter an infinitely long sleep, because we have no commands or
428 // pending or queued events
429 if (nextWakeupTime == LONG_LONG_MAX) {
430 mDispatcherEnteredIdle.notify_all();
431 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800432 } // release lock
433
434 // Wait for callback or timeout or wake. (make sure we round up, not down)
435 nsecs_t currentTime = now();
436 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
437 mLooper->pollOnce(timeoutMillis);
438}
439
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700440/**
441 * Check if any of the connections' wait queues have events that are too old.
442 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
443 * Return the time at which we should wake up next.
444 */
445nsecs_t InputDispatcher::processAnrsLocked() {
446 const nsecs_t currentTime = now();
447 nsecs_t nextAnrCheck = LONG_LONG_MAX;
448 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
449 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
450 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
451 onAnrLocked(mAwaitedFocusedApplication);
Chris Yea209fde2020-07-22 13:54:51 -0700452 mAwaitedFocusedApplication.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700453 return LONG_LONG_MIN;
454 } else {
455 // Keep waiting
456 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
457 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
458 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
459 }
460 }
461
462 // Check if any connection ANRs are due
463 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
464 if (currentTime < nextAnrCheck) { // most likely scenario
465 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
466 }
467
468 // If we reached here, we have an unresponsive connection.
469 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
470 if (connection == nullptr) {
471 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
472 return nextAnrCheck;
473 }
474 connection->responsive = false;
475 // Stop waking up for this unresponsive connection
476 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
477 onAnrLocked(connection);
478 return LONG_LONG_MIN;
479}
480
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500481std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700482 sp<InputWindowHandle> window = getWindowHandleLocked(token);
483 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500484 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700485 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500486 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700487}
488
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
490 nsecs_t currentTime = now();
491
Jeff Browndc5992e2014-04-11 01:27:26 -0700492 // Reset the key repeat timer whenever normal dispatch is suspended while the
493 // device is in a non-interactive state. This is to ensure that we abort a key
494 // repeat if the device is just coming out of sleep.
495 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496 resetKeyRepeatLocked();
497 }
498
499 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
500 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100501 if (DEBUG_FOCUS) {
502 ALOGD("Dispatch frozen. Waiting some more.");
503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800504 return;
505 }
506
507 // Optimize latency of app switches.
508 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
509 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
510 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
511 if (mAppSwitchDueTime < *nextWakeupTime) {
512 *nextWakeupTime = mAppSwitchDueTime;
513 }
514
515 // Ready to start a new event.
516 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700517 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700518 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519 if (isAppSwitchDue) {
520 // The inbound queue is empty so the app switch key we were waiting
521 // for will never arrive. Stop waiting for it.
522 resetPendingAppSwitchLocked(false);
523 isAppSwitchDue = false;
524 }
525
526 // Synthesize a key repeat if appropriate.
527 if (mKeyRepeatState.lastKeyEntry) {
528 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
529 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
530 } else {
531 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
532 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
533 }
534 }
535 }
536
537 // Nothing to do if there is no pending event.
538 if (!mPendingEvent) {
539 return;
540 }
541 } else {
542 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700543 mPendingEvent = mInboundQueue.front();
544 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 traceInboundQueueLengthLocked();
546 }
547
548 // Poke user activity for this event.
549 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700550 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 }
553
554 // Now we have an event to dispatch.
555 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700556 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700558 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700560 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700562 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 }
564
565 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700566 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 }
568
569 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700570 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700571 ConfigurationChangedEntry* typedEntry =
572 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
573 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700574 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700575 break;
576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700578 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700579 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
580 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700581 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700582 break;
583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100585 case EventEntry::Type::FOCUS: {
586 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
587 dispatchFocusLocked(currentTime, typedEntry);
588 done = true;
589 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
590 break;
591 }
592
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700593 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700594 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
595 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700596 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700597 resetPendingAppSwitchLocked(true);
598 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700599 } else if (dropReason == DropReason::NOT_DROPPED) {
600 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700601 }
602 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700603 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700604 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700605 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700606 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
607 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700608 }
609 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
610 break;
611 }
612
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700613 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700614 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700615 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
616 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700618 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700619 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700620 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700621 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
622 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700623 }
624 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
625 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 }
628
629 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700630 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700631 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 }
Michael Wright3a981722015-06-10 15:26:13 +0100633 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634
635 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700636 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637 }
638}
639
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700640/**
641 * Return true if the events preceding this incoming motion event should be dropped
642 * Return false otherwise (the default behaviour)
643 */
644bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700645 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700646 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700647
648 // Optimize case where the current application is unresponsive and the user
649 // decides to touch a window in a different application.
650 // If the application takes too long to catch up then we drop all events preceding
651 // the touch into the other window.
652 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700653 int32_t displayId = motionEntry.displayId;
654 int32_t x = static_cast<int32_t>(
655 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
656 int32_t y = static_cast<int32_t>(
657 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
658 sp<InputWindowHandle> touchedWindowHandle =
659 findTouchedWindowAtLocked(displayId, x, y, nullptr);
660 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700661 touchedWindowHandle->getApplicationToken() !=
662 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700663 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700664 ALOGI("Pruning input queue because user touched a different application while waiting "
665 "for %s",
666 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700667 return true;
668 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700669
670 // Alternatively, maybe there's a gesture monitor that could handle this event
671 std::vector<TouchedMonitor> gestureMonitors =
672 findTouchedGestureMonitorsLocked(displayId, {});
673 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
674 sp<Connection> connection =
675 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000676 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700677 // This monitor could take more input. Drop all events preceding this
678 // event, so that gesture monitor could get a chance to receive the stream
679 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
680 "responsive gesture monitor that may handle the event",
681 mAwaitedFocusedApplication->getName().c_str());
682 return true;
683 }
684 }
685 }
686
687 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
688 // yet been processed by some connections, the dispatcher will wait for these motion
689 // events to be processed before dispatching the key event. This is because these motion events
690 // may cause a new window to be launched, which the user might expect to receive focus.
691 // To prevent waiting forever for such events, just send the key to the currently focused window
692 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
693 ALOGD("Received a new pointer down event, stop waiting for events to process and "
694 "just send the pending key event to the focused window.");
695 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700696 }
697 return false;
698}
699
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700701 bool needWake = mInboundQueue.empty();
702 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 traceInboundQueueLengthLocked();
704
705 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700706 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700707 // Optimize app switch latency.
708 // If the application takes too long to catch up then we drop all events preceding
709 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700710 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700711 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700712 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700713 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700714 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700715 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700717 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700719 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700720 mAppSwitchSawKeyDown = false;
721 needWake = true;
722 }
723 }
724 }
725 break;
726 }
727
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700728 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700729 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
730 mNextUnblockedEvent = entry;
731 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700733 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100735 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700736 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
737 break;
738 }
739 case EventEntry::Type::CONFIGURATION_CHANGED:
740 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700741 // nothing to do
742 break;
743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 }
745
746 return needWake;
747}
748
749void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
750 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700751 mRecentQueue.push_back(entry);
752 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
753 mRecentQueue.front()->release();
754 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 }
756}
757
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700759 int32_t y, TouchState* touchState,
760 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700762 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
763 LOG_ALWAYS_FATAL(
764 "Must provide a valid touch state if adding portal windows or outside targets");
765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 // Traverse windows from front to back to find touched window.
Vishnu Nairad321cd2020-08-20 16:40:21 -0700767 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800768 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800769 const InputWindowInfo* windowInfo = windowHandle->getInfo();
770 if (windowInfo->displayId == displayId) {
Michael Wright44753b12020-07-08 13:48:11 +0100771 auto flags = windowInfo->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772
773 if (windowInfo->visible) {
Michael Wright44753b12020-07-08 13:48:11 +0100774 if (!flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE)) {
775 bool isTouchModal = !flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE) &&
776 !flags.test(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800777 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800778 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700779 if (portalToDisplayId != ADISPLAY_ID_NONE &&
780 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800781 if (addPortalWindows) {
782 // For the monitoring channels of the display.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700783 touchState->addPortalWindow(windowHandle);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800784 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700785 return findTouchedWindowAtLocked(portalToDisplayId, x, y, touchState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700786 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800787 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 // Found window.
789 return windowHandle;
790 }
791 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800792
Michael Wright44753b12020-07-08 13:48:11 +0100793 if (addOutsideTargets && flags.test(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH)) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700794 touchState->addOrUpdateWindow(windowHandle,
795 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
796 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800799 }
800 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700801 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802}
803
Garfield Tane84e6f92019-08-29 17:28:41 -0700804std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700805 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) const {
Michael Wright3dd60e22019-03-27 22:06:44 +0000806 std::vector<TouchedMonitor> touchedMonitors;
807
808 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
809 addGestureMonitors(monitors, touchedMonitors);
810 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
811 const InputWindowInfo* windowInfo = portalWindow->getInfo();
812 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700813 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
814 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000815 }
816 return touchedMonitors;
817}
818
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700819void InputDispatcher::dropInboundEventLocked(const EventEntry& entry, DropReason dropReason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820 const char* reason;
821 switch (dropReason) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700822 case DropReason::POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700824 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700826 reason = "inbound event was dropped because the policy consumed it";
827 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700828 case DropReason::DISABLED:
829 if (mLastDropReason != DropReason::DISABLED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700830 ALOGI("Dropped event because input dispatch is disabled.");
831 }
832 reason = "inbound event was dropped because input dispatch is disabled";
833 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700834 case DropReason::APP_SWITCH:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700835 ALOGI("Dropped event because of pending overdue app switch.");
836 reason = "inbound event was dropped because of pending overdue app switch";
837 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700838 case DropReason::BLOCKED:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700839 ALOGI("Dropped event because the current application is not responding and the user "
840 "has started interacting with a different application.");
841 reason = "inbound event was dropped because the current application is not responding "
842 "and the user has started interacting with a different application";
843 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700844 case DropReason::STALE:
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700845 ALOGI("Dropped event because it is stale.");
846 reason = "inbound event was dropped because it is stale";
847 break;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700848 case DropReason::NOT_DROPPED: {
849 LOG_ALWAYS_FATAL("Should not be dropping a NOT_DROPPED event");
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700850 return;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700851 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 }
853
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700854 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700855 case EventEntry::Type::KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
857 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700858 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700860 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700861 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
862 if (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700863 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
864 synthesizeCancelationEventsForAllConnectionsLocked(options);
865 } else {
866 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
867 synthesizeCancelationEventsForAllConnectionsLocked(options);
868 }
869 break;
870 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100871 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700872 case EventEntry::Type::CONFIGURATION_CHANGED:
873 case EventEntry::Type::DEVICE_RESET: {
874 LOG_ALWAYS_FATAL("Should not drop %s events", EventEntry::typeToString(entry.type));
875 break;
876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877 }
878}
879
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800880static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700881 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
882 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883}
884
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700885bool InputDispatcher::isAppSwitchKeyEvent(const KeyEntry& keyEntry) {
886 return !(keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry.keyCode) &&
887 (keyEntry.policyFlags & POLICY_FLAG_TRUSTED) &&
888 (keyEntry.policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889}
890
891bool InputDispatcher::isAppSwitchPendingLocked() {
892 return mAppSwitchDueTime != LONG_LONG_MAX;
893}
894
895void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
896 mAppSwitchDueTime = LONG_LONG_MAX;
897
898#if DEBUG_APP_SWITCH
899 if (handled) {
900 ALOGD("App switch has arrived.");
901 } else {
902 ALOGD("App switch was abandoned.");
903 }
904#endif
905}
906
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700908 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909}
910
911bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700912 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913 return false;
914 }
915
916 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700917 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700918 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700920 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921
922 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700923 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 return true;
925}
926
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700927void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
928 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929}
930
931void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700932 while (!mInboundQueue.empty()) {
933 EventEntry* entry = mInboundQueue.front();
934 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 releaseInboundEventLocked(entry);
936 }
937 traceInboundQueueLengthLocked();
938}
939
940void InputDispatcher::releasePendingEventLocked() {
941 if (mPendingEvent) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700943 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 }
945}
946
947void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
948 InjectionState* injectionState = entry->injectionState;
949 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
950#if DEBUG_DISPATCH_CYCLE
951 ALOGD("Injected inbound event was dropped.");
952#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800953 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 }
955 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700956 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 }
958 addRecentEventLocked(entry);
959 entry->release();
960}
961
962void InputDispatcher::resetKeyRepeatLocked() {
963 if (mKeyRepeatState.lastKeyEntry) {
964 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700965 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966 }
967}
968
Garfield Tane84e6f92019-08-29 17:28:41 -0700969KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
971
972 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700973 uint32_t policyFlags = entry->policyFlags &
974 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 if (entry->refCount == 1) {
976 entry->recycle();
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800977 entry->id = mIdGenerator.nextId();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 entry->eventTime = currentTime;
979 entry->policyFlags = policyFlags;
980 entry->repeatCount += 1;
981 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700982 KeyEntry* newEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800983 new KeyEntry(mIdGenerator.nextId(), currentTime, entry->deviceId, entry->source,
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800984 entry->displayId, policyFlags, entry->action, entry->flags,
985 entry->keyCode, entry->scanCode, entry->metaState,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700986 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987
988 mKeyRepeatState.lastKeyEntry = newEntry;
989 entry->release();
990
991 entry = newEntry;
992 }
993 entry->syntheticRepeat = true;
994
995 // Increment reference count since we keep a reference to the event in
996 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
997 entry->refCount += 1;
998
999 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
1000 return entry;
1001}
1002
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001003bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
1004 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001006 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007#endif
1008
1009 // Reset key repeating in case a keyboard device was added or removed or something.
1010 resetKeyRepeatLocked();
1011
1012 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001013 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
1014 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001016 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 return true;
1018}
1019
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001020bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001022 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001023 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024#endif
1025
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001026 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 options.deviceId = entry->deviceId;
1028 synthesizeCancelationEventsForAllConnectionsLocked(options);
1029 return true;
1030}
1031
Vishnu Nairad321cd2020-08-20 16:40:21 -07001032void InputDispatcher::enqueueFocusEventLocked(const sp<IBinder>& windowToken, bool hasFocus,
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001033 std::string_view reason) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001034 if (mPendingEvent != nullptr) {
1035 // Move the pending event to the front of the queue. This will give the chance
1036 // for the pending event to get dispatched to the newly focused window
1037 mInboundQueue.push_front(mPendingEvent);
1038 mPendingEvent = nullptr;
1039 }
1040
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001041 FocusEntry* focusEntry =
Vishnu Nairad321cd2020-08-20 16:40:21 -07001042 new FocusEntry(mIdGenerator.nextId(), now(), windowToken, hasFocus, reason);
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07001043
1044 // This event should go to the front of the queue, but behind all other focus events
1045 // Find the last focus event, and insert right after it
1046 std::deque<EventEntry*>::reverse_iterator it =
1047 std::find_if(mInboundQueue.rbegin(), mInboundQueue.rend(),
1048 [](EventEntry* event) { return event->type == EventEntry::Type::FOCUS; });
1049
1050 // Maintain the order of focus events. Insert the entry after all other focus events.
1051 mInboundQueue.insert(it.base(), focusEntry);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001052}
1053
1054void InputDispatcher::dispatchFocusLocked(nsecs_t currentTime, FocusEntry* entry) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001055 std::shared_ptr<InputChannel> channel = getInputChannelLocked(entry->connectionToken);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001056 if (channel == nullptr) {
1057 return; // Window has gone away
1058 }
1059 InputTarget target;
1060 target.inputChannel = channel;
1061 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1062 entry->dispatchInProgress = true;
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001063 std::string message = std::string("Focus ") + (entry->hasFocus ? "entering " : "leaving ") +
1064 channel->getName();
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07001065 std::string reason = std::string("reason=").append(entry->reason);
1066 android_log_event_list(LOGTAG_INPUT_FOCUS) << message << reason << LOG_ID_EVENTS;
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001067 dispatchEventLocked(currentTime, entry, {target});
1068}
1069
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001071 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001073 if (!entry->dispatchInProgress) {
1074 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
1075 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
1076 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
1077 if (mKeyRepeatState.lastKeyEntry &&
1078 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 // We have seen two identical key downs in a row which indicates that the device
1080 // driver is automatically generating key repeats itself. We take note of the
1081 // repeat here, but we disable our own next key repeat timer since it is clear that
1082 // we will not need to synthesize key repeats ourselves.
1083 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
1084 resetKeyRepeatLocked();
1085 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
1086 } else {
1087 // Not a repeat. Save key down state in case we do see a repeat later.
1088 resetKeyRepeatLocked();
1089 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
1090 }
1091 mKeyRepeatState.lastKeyEntry = entry;
1092 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001093 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 resetKeyRepeatLocked();
1095 }
1096
1097 if (entry->repeatCount == 1) {
1098 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
1099 } else {
1100 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
1101 }
1102
1103 entry->dispatchInProgress = true;
1104
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001105 logOutboundKeyDetails("dispatchKey - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 }
1107
1108 // Handle case where the policy asked us to try again later last time.
1109 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
1110 if (currentTime < entry->interceptKeyWakeupTime) {
1111 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
1112 *nextWakeupTime = entry->interceptKeyWakeupTime;
1113 }
1114 return false; // wait until next wakeup
1115 }
1116 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
1117 entry->interceptKeyWakeupTime = 0;
1118 }
1119
1120 // Give the policy a chance to intercept the key.
1121 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
1122 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001123 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -07001124 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001125 sp<IBinder> focusedWindowToken =
1126 getValueByKey(mFocusedWindowTokenByDisplay, getTargetDisplayId(*entry));
1127 if (focusedWindowToken != nullptr) {
1128 commandEntry->inputChannel = getInputChannelLocked(focusedWindowToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 }
1130 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001131 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001132 entry->refCount += 1;
1133 return false; // wait for the command to run
1134 } else {
1135 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
1136 }
1137 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001138 if (*dropReason == DropReason::NOT_DROPPED) {
1139 *dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 }
1141 }
1142
1143 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001144 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001145 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001146 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001147 : INPUT_EVENT_INJECTION_FAILED);
Garfield Tan6a5a14e2020-01-28 13:24:04 -08001148 mReporter->reportDroppedKey(entry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 return true;
1150 }
1151
1152 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001153 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001154 int32_t injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001155 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1157 return false;
1158 }
1159
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001160 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
1162 return true;
1163 }
1164
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001165 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001166 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167
1168 // Dispatch the key.
1169 dispatchEventLocked(currentTime, entry, inputTargets);
1170 return true;
1171}
1172
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001173void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01001175 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001176 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
1177 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001178 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1179 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
1180 entry.repeatCount, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181#endif
1182}
1183
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001184bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
1185 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001186 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001188 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 entry->dispatchInProgress = true;
1190
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001191 logOutboundMotionDetails("dispatchMotion - ", *entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 }
1193
1194 // Clean up if dropping the event.
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001195 if (*dropReason != DropReason::NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001196 setInjectionResult(entry,
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -07001197 *dropReason == DropReason::POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001198 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 return true;
1200 }
1201
1202 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
1203
1204 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001205 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206
1207 bool conflictingPointerActions = false;
1208 int32_t injectionResult;
1209 if (isPointerEvent) {
1210 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001211 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001212 findTouchedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001213 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001214 } else {
1215 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001216 injectionResult =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001217 findFocusedWindowTargetsLocked(currentTime, *entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 }
1219 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
1220 return false;
1221 }
1222
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08001223 setInjectionResult(entry, injectionResult);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001224 if (injectionResult == INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
1225 ALOGW("Permission denied, dropping the motion (isPointer=%s)", toString(isPointerEvent));
1226 return true;
1227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001229 CancelationOptions::Mode mode(isPointerEvent
1230 ? CancelationOptions::CANCEL_POINTER_EVENTS
1231 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
1232 CancelationOptions options(mode, "input event injection failed");
1233 synthesizeCancelationEventsForMonitorsLocked(options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 return true;
1235 }
1236
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001237 // Add monitor channels from event's or focused display.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001238 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(*entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001240 if (isPointerEvent) {
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001241 std::unordered_map<int32_t, TouchState>::iterator it =
1242 mTouchStatesByDisplay.find(entry->displayId);
1243 if (it != mTouchStatesByDisplay.end()) {
1244 const TouchState& state = it->second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001245 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001246 // The event has gone through these portal windows, so we add monitoring targets of
1247 // the corresponding displays as well.
1248 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001249 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +00001250 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001251 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001252 }
1253 }
1254 }
1255 }
1256
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 // Dispatch the motion.
1258 if (conflictingPointerActions) {
1259 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001260 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 synthesizeCancelationEventsForAllConnectionsLocked(options);
1262 }
1263 dispatchEventLocked(currentTime, entry, inputTargets);
1264 return true;
1265}
1266
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001267void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry& entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001269 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001270 ", policyFlags=0x%x, "
1271 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1272 "metaState=0x%x, buttonState=0x%x,"
1273 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001274 prefix, entry.eventTime, entry.deviceId, entry.source, entry.displayId, entry.policyFlags,
1275 entry.action, entry.actionButton, entry.flags, entry.metaState, entry.buttonState,
1276 entry.edgeFlags, entry.xPrecision, entry.yPrecision, entry.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001278 for (uint32_t i = 0; i < entry.pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001280 "x=%f, y=%f, pressure=%f, size=%f, "
1281 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1282 "orientation=%f",
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001283 i, entry.pointerProperties[i].id, entry.pointerProperties[i].toolType,
1284 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1285 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1286 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1287 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1288 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1289 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1290 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1291 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1292 entry.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 }
1294#endif
1295}
1296
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001297void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1298 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001299 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300#if DEBUG_DISPATCH_CYCLE
1301 ALOGD("dispatchEventToCurrentInputTargets");
1302#endif
1303
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00001304 updateInteractionTokensLocked(*eventEntry, inputTargets);
1305
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1307
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001308 pokeUserActivityLocked(*eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001309
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001310 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07001311 sp<Connection> connection =
1312 getConnectionLocked(inputTarget.inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001313 if (connection != nullptr) {
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08001314 prepareDispatchCycleLocked(currentTime, connection, eventEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 } else {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001316 if (DEBUG_FOCUS) {
1317 ALOGD("Dropping event delivery to target with channel '%s' because it "
1318 "is no longer registered with the input dispatcher.",
1319 inputTarget.inputChannel->getName().c_str());
1320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 }
1322 }
1323}
1324
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001325void InputDispatcher::cancelEventsForAnrLocked(const sp<Connection>& connection) {
1326 // We will not be breaking any connections here, even if the policy wants us to abort dispatch.
1327 // If the policy decides to close the app, we will get a channel removal event via
1328 // unregisterInputChannel, and will clean up the connection that way. We are already not
1329 // sending new pointers to the connection when it blocked, but focused events will continue to
1330 // pile up.
1331 ALOGW("Canceling events for %s because it is unresponsive",
1332 connection->inputChannel->getName().c_str());
1333 if (connection->status == Connection::STATUS_NORMAL) {
1334 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1335 "application not responding");
1336 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 }
1338}
1339
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001340void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001341 if (DEBUG_FOCUS) {
1342 ALOGD("Resetting ANR timeouts.");
1343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344
1345 // Reset input target wait timeout.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001346 mNoFocusedWindowTimeoutTime = std::nullopt;
Chris Yea209fde2020-07-22 13:54:51 -07001347 mAwaitedFocusedApplication.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348}
1349
Tiger Huang721e26f2018-07-24 22:26:19 +08001350/**
1351 * Get the display id that the given event should go to. If this event specifies a valid display id,
1352 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1353 * Focused display is the display that the user most recently interacted with.
1354 */
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001355int32_t InputDispatcher::getTargetDisplayId(const EventEntry& entry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001356 int32_t displayId;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001357 switch (entry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001358 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001359 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
1360 displayId = keyEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001361 break;
1362 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001363 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001364 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
1365 displayId = motionEntry.displayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001366 break;
1367 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001368 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07001369 case EventEntry::Type::CONFIGURATION_CHANGED:
1370 case EventEntry::Type::DEVICE_RESET: {
1371 ALOGE("%s events do not have a target display", EventEntry::typeToString(entry.type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001372 return ADISPLAY_ID_NONE;
1373 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001374 }
1375 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1376}
1377
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001378bool InputDispatcher::shouldWaitToSendKeyLocked(nsecs_t currentTime,
1379 const char* focusedWindowName) {
1380 if (mAnrTracker.empty()) {
1381 // already processed all events that we waited for
1382 mKeyIsWaitingForEventsTimeout = std::nullopt;
1383 return false;
1384 }
1385
1386 if (!mKeyIsWaitingForEventsTimeout.has_value()) {
1387 // Start the timer
1388 ALOGD("Waiting to send key to %s because there are unprocessed events that may cause "
1389 "focus to change",
1390 focusedWindowName);
Siarhei Vishniakou70622952020-07-30 11:17:23 -05001391 mKeyIsWaitingForEventsTimeout = currentTime +
1392 std::chrono::duration_cast<std::chrono::nanoseconds>(KEY_WAITING_FOR_EVENTS_TIMEOUT)
1393 .count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001394 return true;
1395 }
1396
1397 // We still have pending events, and already started the timer
1398 if (currentTime < *mKeyIsWaitingForEventsTimeout) {
1399 return true; // Still waiting
1400 }
1401
1402 // Waited too long, and some connection still hasn't processed all motions
1403 // Just send the key to the focused window
1404 ALOGW("Dispatching key to %s even though there are other unprocessed events",
1405 focusedWindowName);
1406 mKeyIsWaitingForEventsTimeout = std::nullopt;
1407 return false;
1408}
1409
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001411 const EventEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001412 std::vector<InputTarget>& inputTargets,
1413 nsecs_t* nextWakeupTime) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001414 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415
Tiger Huang721e26f2018-07-24 22:26:19 +08001416 int32_t displayId = getTargetDisplayId(entry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07001417 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001418 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001419 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1420
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 // If there is no currently focused window and no focused application
1422 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001423 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1424 ALOGI("Dropping %s event because there is no focused window or focused application in "
1425 "display %" PRId32 ".",
1426 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001427 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 }
1429
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001430 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1431 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1432 // start interacting with another application via touch (app switch). This code can be removed
1433 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1434 // an app is expected to have a focused window.
1435 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1436 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1437 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001438 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1439 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1440 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001441 mAwaitedFocusedApplication = focusedApplicationHandle;
1442 ALOGW("Waiting because no window has focus but %s may eventually add a "
1443 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001444 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001445 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1446 return INPUT_EVENT_INJECTION_PENDING;
1447 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1448 // Already raised ANR. Drop the event
1449 ALOGE("Dropping %s event because there is no focused window",
1450 EventEntry::typeToString(entry.type));
1451 return INPUT_EVENT_INJECTION_FAILED;
1452 } else {
1453 // Still waiting for the focused window
1454 return INPUT_EVENT_INJECTION_PENDING;
1455 }
1456 }
1457
1458 // we have a valid, non-null focused window
1459 resetNoFocusedWindowTimeoutLocked();
1460
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001462 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001463 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 }
1465
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001466 if (focusedWindowHandle->getInfo()->paused) {
1467 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1468 return INPUT_EVENT_INJECTION_PENDING;
1469 }
1470
1471 // If the event is a key event, then we must wait for all previous events to
1472 // complete before delivering it because previous events may have the
1473 // side-effect of transferring focus to a different window and we want to
1474 // ensure that the following keys are sent to the new window.
1475 //
1476 // Suppose the user touches a button in a window then immediately presses "A".
1477 // If the button causes a pop-up window to appear then we want to ensure that
1478 // the "A" key is delivered to the new pop-up window. This is because users
1479 // often anticipate pending UI changes when typing on a keyboard.
1480 // To obtain this behavior, we must serialize key events with respect to all
1481 // prior input events.
1482 if (entry.type == EventEntry::Type::KEY) {
1483 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1484 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1485 return INPUT_EVENT_INJECTION_PENDING;
1486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 }
1488
1489 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001490 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001491 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1492 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493
1494 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001495 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496}
1497
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001498/**
1499 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1500 * that are currently unresponsive.
1501 */
1502std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1503 const std::vector<TouchedMonitor>& monitors) const {
1504 std::vector<TouchedMonitor> responsiveMonitors;
1505 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1506 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1507 sp<Connection> connection = getConnectionLocked(
1508 monitor.monitor.inputChannel->getConnectionToken());
1509 if (connection == nullptr) {
1510 ALOGE("Could not find connection for monitor %s",
1511 monitor.monitor.inputChannel->getName().c_str());
1512 return false;
1513 }
1514 if (!connection->responsive) {
1515 ALOGW("Unresponsive monitor %s will not get the new gesture",
1516 connection->inputChannel->getName().c_str());
1517 return false;
1518 }
1519 return true;
1520 });
1521 return responsiveMonitors;
1522}
1523
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001525 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001526 std::vector<InputTarget>& inputTargets,
1527 nsecs_t* nextWakeupTime,
1528 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001529 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 enum InjectionPermission {
1531 INJECTION_PERMISSION_UNKNOWN,
1532 INJECTION_PERMISSION_GRANTED,
1533 INJECTION_PERMISSION_DENIED
1534 };
1535
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 // For security reasons, we defer updating the touch state until we are sure that
1537 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001538 int32_t displayId = entry.displayId;
1539 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1541
1542 // Update the touch state as needed based on the properties of the touch event.
1543 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1544 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001545 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1546 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001548 // Copy current touch state into tempTouchState.
1549 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1550 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001551 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001552 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001553 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1554 mTouchStatesByDisplay.find(displayId);
1555 if (oldStateIt != mTouchStatesByDisplay.end()) {
1556 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001557 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001558 }
1559
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001560 bool isSplit = tempTouchState.split;
1561 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1562 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1563 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001564 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1565 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1566 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1567 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1568 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001569 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 bool wrongDevice = false;
1571 if (newGesture) {
1572 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001573 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001574 ALOGI("Dropping event because a pointer for a different device is already down "
1575 "in display %" PRId32,
1576 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001577 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1579 switchedDevice = false;
1580 wrongDevice = true;
1581 goto Failed;
1582 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001583 tempTouchState.reset();
1584 tempTouchState.down = down;
1585 tempTouchState.deviceId = entry.deviceId;
1586 tempTouchState.source = entry.source;
1587 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001589 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001590 ALOGI("Dropping move event because a pointer for a different device is already active "
1591 "in display %" PRId32,
1592 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001593 // TODO: test multiple simultaneous input streams.
1594 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1595 switchedDevice = false;
1596 wrongDevice = true;
1597 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 }
1599
1600 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1601 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1602
Garfield Tan00f511d2019-06-12 16:55:40 -07001603 int32_t x;
1604 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001606 // Always dispatch mouse events to cursor position.
1607 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001608 x = int32_t(entry.xCursorPosition);
1609 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001610 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001611 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1612 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001613 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001614 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001615 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001616 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1617 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001618
1619 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001620 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001621 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001624 if (newTouchedWindowHandle != nullptr &&
1625 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001626 // New window supports splitting, but we should never split mouse events.
1627 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 } else if (isSplit) {
1629 // New window does not support splitting but we have already split events.
1630 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001631 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 }
1633
1634 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001635 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001637 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001638 }
1639
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001640 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1641 ALOGI("Not sending touch event to %s because it is paused",
1642 newTouchedWindowHandle->getName().c_str());
1643 newTouchedWindowHandle = nullptr;
1644 }
1645
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001646 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001647 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001648 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1649 if (!isResponsive) {
1650 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001651 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1652 newTouchedWindowHandle = nullptr;
1653 }
1654 }
1655
1656 // Also don't send the new touch event to unresponsive gesture monitors
1657 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1658
Michael Wright3dd60e22019-03-27 22:06:44 +00001659 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1660 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001661 "(%d, %d) in display %" PRId32 ".",
1662 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001663 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1664 goto Failed;
1665 }
1666
1667 if (newTouchedWindowHandle != nullptr) {
1668 // Set target flags.
1669 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1670 if (isSplit) {
1671 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001673 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1674 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1675 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1676 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1677 }
1678
1679 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001680 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1681 newHoverWindowHandle = nullptr;
1682 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001683 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001684 }
1685
1686 // Update the temporary touch state.
1687 BitSet32 pointerIds;
1688 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001689 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001690 pointerIds.markBit(pointerId);
1691 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001692 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 }
1694
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001695 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 } else {
1697 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1698
1699 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001700 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001701 if (DEBUG_FOCUS) {
1702 ALOGD("Dropping event because the pointer is not down or we previously "
1703 "dropped the pointer down event in display %" PRId32,
1704 displayId);
1705 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1707 goto Failed;
1708 }
1709
1710 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001711 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001712 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001713 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1714 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715
1716 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001717 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001718 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001719 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1720 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001721 if (DEBUG_FOCUS) {
1722 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1723 oldTouchedWindowHandle->getName().c_str(),
1724 newTouchedWindowHandle->getName().c_str(), displayId);
1725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001727 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1728 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1729 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730
1731 // Make a slippery entrance into the new window.
1732 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1733 isSplit = true;
1734 }
1735
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001736 int32_t targetFlags =
1737 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 if (isSplit) {
1739 targetFlags |= InputTarget::FLAG_SPLIT;
1740 }
1741 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1742 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1743 }
1744
1745 BitSet32 pointerIds;
1746 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001747 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001749 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 }
1751 }
1752 }
1753
1754 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001755 // Let the previous window know that the hover sequence is over, unless we already did it
1756 // when dispatching it as is to newTouchedWindowHandle.
1757 if (mLastHoverWindowHandle != nullptr &&
1758 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1759 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001760#if DEBUG_HOVER
1761 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001762 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001764 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1765 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766 }
1767
Garfield Tandf26e862020-07-01 20:18:19 -07001768 // Let the new window know that the hover sequence is starting, unless we already did it
1769 // when dispatching it as is to newTouchedWindowHandle.
1770 if (newHoverWindowHandle != nullptr &&
1771 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1772 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773#if DEBUG_HOVER
1774 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001775 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001777 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1778 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1779 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 }
1781 }
1782
1783 // Check permission to inject into all touched foreground windows and ensure there
1784 // is at least one touched foreground window.
1785 {
1786 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001787 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1789 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001790 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1792 injectionPermission = INJECTION_PERMISSION_DENIED;
1793 goto Failed;
1794 }
1795 }
1796 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001797 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001798 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001799 ALOGI("Dropping event because there is no touched foreground window in display "
1800 "%" PRId32 " or gesture monitor to receive it.",
1801 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001802 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1803 goto Failed;
1804 }
1805
1806 // Permission granted to injection into all touched foreground windows.
1807 injectionPermission = INJECTION_PERMISSION_GRANTED;
1808 }
1809
1810 // Check whether windows listening for outside touches are owned by the same UID. If it is
1811 // set the policy flag that we will not reveal coordinate information to this window.
1812 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1813 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001814 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001815 if (foregroundWindowHandle) {
1816 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001817 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001818 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1819 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1820 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001821 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1822 InputTarget::FLAG_ZERO_COORDS,
1823 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825 }
1826 }
1827 }
1828 }
1829
Michael Wrightd02c5b62014-02-10 15:10:22 -08001830 // If this is the first pointer going down and the touched window has a wallpaper
1831 // then also add the touched wallpaper windows so they are locked in for the duration
1832 // of the touch gesture.
1833 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1834 // engine only supports touch events. We would need to add a mechanism similar
1835 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1836 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1837 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001838 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001839 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07001840 const std::vector<sp<InputWindowHandle>>& windowHandles =
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001841 getWindowHandlesLocked(displayId);
1842 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001844 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001845 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001846 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001847 .addOrUpdateWindow(windowHandle,
1848 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1849 InputTarget::
1850 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1851 InputTarget::FLAG_DISPATCH_AS_IS,
1852 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001853 }
1854 }
1855 }
1856 }
1857
1858 // Success! Output targets.
1859 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1860
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001861 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001863 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 }
1865
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001866 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001867 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001868 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001869 }
1870
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 // Drop the outside or hover touch windows since we will not care about them
1872 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001873 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874
1875Failed:
1876 // Check injection permission once and for all.
1877 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001878 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 injectionPermission = INJECTION_PERMISSION_GRANTED;
1880 } else {
1881 injectionPermission = INJECTION_PERMISSION_DENIED;
1882 }
1883 }
1884
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001885 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1886 return injectionResult;
1887 }
1888
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001890 if (!wrongDevice) {
1891 if (switchedDevice) {
1892 if (DEBUG_FOCUS) {
1893 ALOGD("Conflicting pointer actions: Switched to a different device.");
1894 }
1895 *outConflictingPointerActions = true;
1896 }
1897
1898 if (isHoverAction) {
1899 // Started hovering, therefore no longer down.
1900 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001901 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001902 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1903 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001904 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 *outConflictingPointerActions = true;
1906 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001907 tempTouchState.reset();
1908 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1909 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1910 tempTouchState.deviceId = entry.deviceId;
1911 tempTouchState.source = entry.source;
1912 tempTouchState.displayId = displayId;
1913 }
1914 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1915 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1916 // All pointers up or canceled.
1917 tempTouchState.reset();
1918 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1919 // First pointer went down.
1920 if (oldState && oldState->down) {
1921 if (DEBUG_FOCUS) {
1922 ALOGD("Conflicting pointer actions: Down received while already down.");
1923 }
1924 *outConflictingPointerActions = true;
1925 }
1926 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1927 // One pointer went up.
1928 if (isSplit) {
1929 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1930 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001932 for (size_t i = 0; i < tempTouchState.windows.size();) {
1933 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1934 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1935 touchedWindow.pointerIds.clearBit(pointerId);
1936 if (touchedWindow.pointerIds.isEmpty()) {
1937 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1938 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001941 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001943 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001944 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001945
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001946 // Save changes unless the action was scroll in which case the temporary touch
1947 // state was only valid for this one action.
1948 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1949 if (tempTouchState.displayId >= 0) {
1950 mTouchStatesByDisplay[displayId] = tempTouchState;
1951 } else {
1952 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001954 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001956 // Update hover state.
1957 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001958 }
1959
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 return injectionResult;
1961}
1962
1963void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001964 int32_t targetFlags, BitSet32 pointerIds,
1965 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001966 std::vector<InputTarget>::iterator it =
1967 std::find_if(inputTargets.begin(), inputTargets.end(),
1968 [&windowHandle](const InputTarget& inputTarget) {
1969 return inputTarget.inputChannel->getConnectionToken() ==
1970 windowHandle->getToken();
1971 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001972
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001973 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001974
1975 if (it == inputTargets.end()) {
1976 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001977 std::shared_ptr<InputChannel> inputChannel =
1978 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001979 if (inputChannel == nullptr) {
1980 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1981 return;
1982 }
1983 inputTarget.inputChannel = inputChannel;
1984 inputTarget.flags = targetFlags;
1985 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1986 inputTargets.push_back(inputTarget);
1987 it = inputTargets.end() - 1;
1988 }
1989
1990 ALOG_ASSERT(it->flags == targetFlags);
1991 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1992
chaviw1ff3d1e2020-07-01 15:53:47 -07001993 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994}
1995
Michael Wright3dd60e22019-03-27 22:06:44 +00001996void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001997 int32_t displayId, float xOffset,
1998 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001999 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2000 mGlobalMonitorsByDisplay.find(displayId);
2001
2002 if (it != mGlobalMonitorsByDisplay.end()) {
2003 const std::vector<Monitor>& monitors = it->second;
2004 for (const Monitor& monitor : monitors) {
2005 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002006 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 }
2008}
2009
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002010void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2011 float yOffset,
2012 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002013 InputTarget target;
2014 target.inputChannel = monitor.inputChannel;
2015 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002016 ui::Transform t;
2017 t.set(xOffset, yOffset);
2018 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002019 inputTargets.push_back(target);
2020}
2021
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002023 const InjectionState* injectionState) {
2024 if (injectionState &&
2025 (windowHandle == nullptr ||
2026 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2027 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002028 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002029 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002030 "owned by uid %d",
2031 injectionState->injectorPid, injectionState->injectorUid,
2032 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 } else {
2034 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002035 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 }
2037 return false;
2038 }
2039 return true;
2040}
2041
Robert Carrc9bf1d32020-04-13 17:21:08 -07002042/**
2043 * Indicate whether one window handle should be considered as obscuring
2044 * another window handle. We only check a few preconditions. Actually
2045 * checking the bounds is left to the caller.
2046 */
2047static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2048 const sp<InputWindowHandle>& otherHandle) {
2049 // Compare by token so cloned layers aren't counted
2050 if (haveSameToken(windowHandle, otherHandle)) {
2051 return false;
2052 }
2053 auto info = windowHandle->getInfo();
2054 auto otherInfo = otherHandle->getInfo();
2055 if (!otherInfo->visible) {
2056 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002057 } else if (info->ownerPid == otherInfo->ownerPid) {
2058 // If ownerPid is the same we don't generate occlusion events as there
2059 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002060 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002061 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002062 return false;
2063 } else if (otherInfo->displayId != info->displayId) {
2064 return false;
2065 }
2066 return true;
2067}
2068
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002069bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2070 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002072 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002073 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002074 if (windowHandle == otherHandle) {
2075 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002078 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002079 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002080 return true;
2081 }
2082 }
2083 return false;
2084}
2085
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002086bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2087 int32_t displayId = windowHandle->getInfo()->displayId;
Vishnu Nairad321cd2020-08-20 16:40:21 -07002088 const std::vector<sp<InputWindowHandle>>& windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002089 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002090 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002091 if (windowHandle == otherHandle) {
2092 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002093 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002094 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002095 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002096 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002097 return true;
2098 }
2099 }
2100 return false;
2101}
2102
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002103std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002104 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002106 if (applicationHandle != nullptr) {
2107 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002108 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 } else {
2110 return applicationHandle->getName();
2111 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002112 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002113 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002115 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 }
2117}
2118
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002119void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002120 if (eventEntry.type == EventEntry::Type::FOCUS) {
2121 // Focus events are passed to apps, but do not represent user activity.
2122 return;
2123 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002124 int32_t displayId = getTargetDisplayId(eventEntry);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002125 sp<InputWindowHandle> focusedWindowHandle = getFocusedWindowHandleLocked(displayId);
Tiger Huang721e26f2018-07-24 22:26:19 +08002126 if (focusedWindowHandle != nullptr) {
2127 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002128 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002130 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131#endif
2132 return;
2133 }
2134 }
2135
2136 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002137 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002138 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002139 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2140 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002141 return;
2142 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002144 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002145 eventType = USER_ACTIVITY_EVENT_TOUCH;
2146 }
2147 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002149 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002150 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2151 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002152 return;
2153 }
2154 eventType = USER_ACTIVITY_EVENT_BUTTON;
2155 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002157 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002158 case EventEntry::Type::CONFIGURATION_CHANGED:
2159 case EventEntry::Type::DEVICE_RESET: {
2160 LOG_ALWAYS_FATAL("%s events are not user activity",
2161 EventEntry::typeToString(eventEntry.type));
2162 break;
2163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002164 }
2165
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002166 std::unique_ptr<CommandEntry> commandEntry =
2167 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002168 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002170 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171}
2172
2173void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002174 const sp<Connection>& connection,
2175 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002176 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002177 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002178 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002179 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002180 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002181 ATRACE_NAME(message.c_str());
2182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183#if DEBUG_DISPATCH_CYCLE
2184 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002185 "globalScaleFactor=%f, pointerIds=0x%x %s",
2186 connection->getInputChannelName().c_str(), inputTarget.flags,
2187 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2188 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189#endif
2190
2191 // Skip this event if the connection status is not normal.
2192 // We don't want to enqueue additional outbound events if the connection is broken.
2193 if (connection->status != Connection::STATUS_NORMAL) {
2194#if DEBUG_DISPATCH_CYCLE
2195 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002196 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197#endif
2198 return;
2199 }
2200
2201 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002202 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2203 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2204 "Entry type %s should not have FLAG_SPLIT",
2205 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002207 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002208 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002209 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002210 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 if (!splitMotionEntry) {
2212 return; // split event was dropped
2213 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002214 if (DEBUG_FOCUS) {
2215 ALOGD("channel '%s' ~ Split motion event.",
2216 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002217 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002218 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002219 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220 splitMotionEntry->release();
2221 return;
2222 }
2223 }
2224
2225 // Not splitting. Enqueue dispatch entries for the event as is.
2226 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2227}
2228
2229void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002230 const sp<Connection>& connection,
2231 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002232 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002233 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002234 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002235 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002236 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002237 ATRACE_NAME(message.c_str());
2238 }
2239
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002240 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241
2242 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002243 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002244 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002245 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002246 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002247 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002248 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002249 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002250 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002251 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002252 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002253 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255
2256 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002257 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 startDispatchCycleLocked(currentTime, connection);
2259 }
2260}
2261
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002262void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2263 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002264 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002265 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002266 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002267 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2268 connection->getInputChannelName().c_str(),
2269 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002270 ATRACE_NAME(message.c_str());
2271 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002272 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002273 if (!(inputTargetFlags & dispatchMode)) {
2274 return;
2275 }
2276 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2277
2278 // This is a new event.
2279 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002280 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002281 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002283 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2284 // different EventEntry than what was passed in.
2285 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002287 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002288 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002289 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002290 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002291 dispatchEntry->resolvedAction = keyEntry.action;
2292 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002294 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2295 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002297 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2298 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002300 return; // skip the inconsistent event
2301 }
2302 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002305 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002306 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002307 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2308 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2309 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2310 static_cast<int32_t>(IdGenerator::Source::OTHER);
2311 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002312 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2313 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2314 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2315 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2316 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2317 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2318 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2319 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2320 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2321 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2322 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002323 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002324 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002325 }
2326 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002327 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2328 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002330 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2331 "event",
2332 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002334 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2335 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002337 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002338 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2339 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2340 }
2341 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2342 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002345 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2346 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002348 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2349 "event",
2350 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002352 return; // skip the inconsistent event
2353 }
2354
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002355 dispatchEntry->resolvedEventId =
2356 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2357 ? mIdGenerator.nextId()
2358 : motionEntry.id;
2359 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2360 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2361 ") to MotionEvent(id=0x%" PRIx32 ").",
2362 motionEntry.id, dispatchEntry->resolvedEventId);
2363 ATRACE_NAME(message.c_str());
2364 }
2365
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002366 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002367 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002368
2369 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002371 case EventEntry::Type::FOCUS: {
2372 break;
2373 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002374 case EventEntry::Type::CONFIGURATION_CHANGED:
2375 case EventEntry::Type::DEVICE_RESET: {
2376 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002377 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002378 break;
2379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 }
2381
2382 // Remember that we are waiting for this dispatch to complete.
2383 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002384 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385 }
2386
2387 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002388 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002389 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002390}
2391
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002392/**
2393 * This function is purely for debugging. It helps us understand where the user interaction
2394 * was taking place. For example, if user is touching launcher, we will see a log that user
2395 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2396 * We will see both launcher and wallpaper in that list.
2397 * Once the interaction with a particular set of connections starts, no new logs will be printed
2398 * until the set of interacted connections changes.
2399 *
2400 * The following items are skipped, to reduce the logspam:
2401 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2402 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2403 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2404 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2405 * Both of those ACTION_UP events would not be logged
2406 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2407 * will not be logged. This is omitted to reduce the amount of data printed.
2408 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2409 * gesture monitor is the only connection receiving the remainder of the gesture.
2410 */
2411void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2412 const std::vector<InputTarget>& targets) {
2413 // Skip ACTION_UP events, and all events other than keys and motions
2414 if (entry.type == EventEntry::Type::KEY) {
2415 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2416 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2417 return;
2418 }
2419 } else if (entry.type == EventEntry::Type::MOTION) {
2420 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2421 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2422 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2423 return;
2424 }
2425 } else {
2426 return; // Not a key or a motion
2427 }
2428
2429 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2430 std::vector<sp<Connection>> newConnections;
2431 for (const InputTarget& target : targets) {
2432 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2433 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2434 continue; // Skip windows that receive ACTION_OUTSIDE
2435 }
2436
2437 sp<IBinder> token = target.inputChannel->getConnectionToken();
2438 sp<Connection> connection = getConnectionLocked(token);
2439 if (connection == nullptr || connection->monitor) {
2440 continue; // We only need to keep track of the non-monitor connections.
2441 }
2442 newConnectionTokens.insert(std::move(token));
2443 newConnections.emplace_back(connection);
2444 }
2445 if (newConnectionTokens == mInteractionConnectionTokens) {
2446 return; // no change
2447 }
2448 mInteractionConnectionTokens = newConnectionTokens;
2449
2450 std::string windowList;
2451 for (const sp<Connection>& connection : newConnections) {
2452 windowList += connection->getWindowName() + ", ";
2453 }
2454 std::string message = "Interaction with windows: " + windowList;
2455 if (windowList.empty()) {
2456 message += "<none>";
2457 }
2458 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2459}
2460
chaviwfd6d3512019-03-25 13:23:49 -07002461void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Vishnu Nairad321cd2020-08-20 16:40:21 -07002462 const sp<IBinder>& token) {
chaviw8c9cf542019-03-25 13:02:48 -07002463 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002464 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2465 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002466 return;
2467 }
2468
Vishnu Nairad321cd2020-08-20 16:40:21 -07002469 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
2470 if (focusedToken == token) {
2471 // ignore since token is focused
chaviw8c9cf542019-03-25 13:02:48 -07002472 return;
2473 }
2474
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002475 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2476 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
Vishnu Nairad321cd2020-08-20 16:40:21 -07002477 commandEntry->newToken = token;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002478 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479}
2480
2481void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002482 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002483 if (ATRACE_ENABLED()) {
2484 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002485 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002486 ATRACE_NAME(message.c_str());
2487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002489 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490#endif
2491
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002492 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2493 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002495 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002496 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002497 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498
2499 // Publish the event.
2500 status_t status;
2501 EventEntry* eventEntry = dispatchEntry->eventEntry;
2502 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002503 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002504 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2505 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002507 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002508 status =
2509 connection->inputPublisher
2510 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2511 keyEntry->deviceId, keyEntry->source,
2512 keyEntry->displayId, std::move(hmac),
2513 dispatchEntry->resolvedAction,
2514 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2515 keyEntry->scanCode, keyEntry->metaState,
2516 keyEntry->repeatCount, keyEntry->downTime,
2517 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002518 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519 }
2520
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002521 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002522 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002523
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002524 PointerCoords scaledCoords[MAX_POINTERS];
2525 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2526
chaviw82357092020-01-28 13:13:06 -08002527 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002528 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2529 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2530 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002531 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002532 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2533 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002534 // Don't apply window scale here since we don't want scale to affect raw
2535 // coordinates. The scale will be sent back to the client and applied
2536 // later when requesting relative coordinates.
2537 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2538 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002539 }
2540 usingCoords = scaledCoords;
2541 }
2542 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002543 // We don't want the dispatch target to know.
2544 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2545 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2546 scaledCoords[i].clear();
2547 }
2548 usingCoords = scaledCoords;
2549 }
2550 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002551
2552 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002553
2554 // Publish the motion event.
2555 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002556 .publishMotionEvent(dispatchEntry->seq,
2557 dispatchEntry->resolvedEventId,
2558 motionEntry->deviceId, motionEntry->source,
2559 motionEntry->displayId, std::move(hmac),
2560 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002561 motionEntry->actionButton,
2562 dispatchEntry->resolvedFlags,
2563 motionEntry->edgeFlags, motionEntry->metaState,
2564 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002565 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002566 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002567 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002568 motionEntry->yPrecision,
2569 motionEntry->xCursorPosition,
2570 motionEntry->yCursorPosition,
2571 motionEntry->downTime, motionEntry->eventTime,
2572 motionEntry->pointerCount,
2573 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002574 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002575 break;
2576 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002577 case EventEntry::Type::FOCUS: {
2578 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2579 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002580 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002581 focusEntry->hasFocus,
2582 mInTouchMode);
2583 break;
2584 }
2585
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002586 case EventEntry::Type::CONFIGURATION_CHANGED:
2587 case EventEntry::Type::DEVICE_RESET: {
2588 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2589 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002590 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002591 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002592 }
2593
2594 // Check the result.
2595 if (status) {
2596 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002597 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002599 "This is unexpected because the wait queue is empty, so the pipe "
2600 "should be empty and we shouldn't have any problems writing an "
2601 "event to it, status=%d",
2602 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2604 } else {
2605 // Pipe is full and we are waiting for the app to finish process some events
2606 // before sending more events to it.
2607#if DEBUG_DISPATCH_CYCLE
2608 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002609 "waiting for the application to catch up",
2610 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002611#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 }
2613 } else {
2614 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002615 "status=%d",
2616 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2618 }
2619 return;
2620 }
2621
2622 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002623 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2624 connection->outboundQueue.end(),
2625 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002626 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002627 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002628 if (connection->responsive) {
2629 mAnrTracker.insert(dispatchEntry->timeoutTime,
2630 connection->inputChannel->getConnectionToken());
2631 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002632 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002633 }
2634}
2635
chaviw09c8d2d2020-08-24 15:48:26 -07002636std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2637 size_t size;
2638 switch (event.type) {
2639 case VerifiedInputEvent::Type::KEY: {
2640 size = sizeof(VerifiedKeyEvent);
2641 break;
2642 }
2643 case VerifiedInputEvent::Type::MOTION: {
2644 size = sizeof(VerifiedMotionEvent);
2645 break;
2646 }
2647 }
2648 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2649 return mHmacKeyManager.sign(start, size);
2650}
2651
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002652const std::array<uint8_t, 32> InputDispatcher::getSignature(
2653 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2654 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2655 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2656 // Only sign events up and down events as the purely move events
2657 // are tied to their up/down counterparts so signing would be redundant.
2658 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2659 verifiedEvent.actionMasked = actionMasked;
2660 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002661 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002662 }
2663 return INVALID_HMAC;
2664}
2665
2666const std::array<uint8_t, 32> InputDispatcher::getSignature(
2667 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2668 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2669 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2670 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002671 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002672}
2673
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002675 const sp<Connection>& connection, uint32_t seq,
2676 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677#if DEBUG_DISPATCH_CYCLE
2678 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002679 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680#endif
2681
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002682 if (connection->status == Connection::STATUS_BROKEN ||
2683 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684 return;
2685 }
2686
2687 // Notify other system components and prepare to start the next dispatch cycle.
2688 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2689}
2690
2691void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002692 const sp<Connection>& connection,
2693 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694#if DEBUG_DISPATCH_CYCLE
2695 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002696 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697#endif
2698
2699 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002700 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002701 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002702 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002703 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704
2705 // The connection appears to be unrecoverably broken.
2706 // Ignore already broken or zombie connections.
2707 if (connection->status == Connection::STATUS_NORMAL) {
2708 connection->status = Connection::STATUS_BROKEN;
2709
2710 if (notify) {
2711 // Notify other system components.
2712 onDispatchCycleBrokenLocked(currentTime, connection);
2713 }
2714 }
2715}
2716
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002717void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2718 while (!queue.empty()) {
2719 DispatchEntry* dispatchEntry = queue.front();
2720 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002721 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722 }
2723}
2724
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002725void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002727 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728 }
2729 delete dispatchEntry;
2730}
2731
2732int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2733 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2734
2735 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002736 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002738 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002740 "fd=%d, events=0x%x",
2741 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 return 0; // remove the callback
2743 }
2744
2745 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002746 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2748 if (!(events & ALOOPER_EVENT_INPUT)) {
2749 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002750 "events=0x%x",
2751 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 return 1;
2753 }
2754
2755 nsecs_t currentTime = now();
2756 bool gotOne = false;
2757 status_t status;
2758 for (;;) {
2759 uint32_t seq;
2760 bool handled;
2761 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2762 if (status) {
2763 break;
2764 }
2765 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2766 gotOne = true;
2767 }
2768 if (gotOne) {
2769 d->runCommandsLockedInterruptible();
2770 if (status == WOULD_BLOCK) {
2771 return 1;
2772 }
2773 }
2774
2775 notify = status != DEAD_OBJECT || !connection->monitor;
2776 if (notify) {
2777 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002778 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002779 }
2780 } else {
2781 // Monitor channels are never explicitly unregistered.
2782 // We do it automatically when the remote endpoint is closed so don't warn
2783 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002784 const bool stillHaveWindowHandle =
2785 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2786 nullptr;
2787 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 if (notify) {
2789 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002790 "events=0x%x",
2791 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 }
2793 }
2794
2795 // Unregister the channel.
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002796 d->unregisterInputChannelLocked(*connection->inputChannel, notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002798 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002799}
2800
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002801void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002803 for (const auto& pair : mConnectionsByFd) {
2804 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 }
2806}
2807
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002809 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002810 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2811 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2812}
2813
2814void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2815 const CancelationOptions& options,
2816 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2817 for (const auto& it : monitorsByDisplay) {
2818 const std::vector<Monitor>& monitors = it.second;
2819 for (const Monitor& monitor : monitors) {
2820 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002821 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002822 }
2823}
2824
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002826 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002827 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002828 if (connection == nullptr) {
2829 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002831
2832 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833}
2834
2835void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2836 const sp<Connection>& connection, const CancelationOptions& options) {
2837 if (connection->status == Connection::STATUS_BROKEN) {
2838 return;
2839 }
2840
2841 nsecs_t currentTime = now();
2842
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002843 std::vector<EventEntry*> cancelationEvents =
2844 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002846 if (cancelationEvents.empty()) {
2847 return;
2848 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002850 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2851 "with reality: %s, mode=%d.",
2852 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2853 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002855
2856 InputTarget target;
2857 sp<InputWindowHandle> windowHandle =
2858 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2859 if (windowHandle != nullptr) {
2860 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002861 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002862 target.globalScaleFactor = windowInfo->globalScaleFactor;
2863 }
2864 target.inputChannel = connection->inputChannel;
2865 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2866
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002867 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2868 EventEntry* cancelationEventEntry = cancelationEvents[i];
2869 switch (cancelationEventEntry->type) {
2870 case EventEntry::Type::KEY: {
2871 logOutboundKeyDetails("cancel - ",
2872 static_cast<const KeyEntry&>(*cancelationEventEntry));
2873 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002875 case EventEntry::Type::MOTION: {
2876 logOutboundMotionDetails("cancel - ",
2877 static_cast<const MotionEntry&>(*cancelationEventEntry));
2878 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002879 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002880 case EventEntry::Type::FOCUS: {
2881 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2882 break;
2883 }
2884 case EventEntry::Type::CONFIGURATION_CHANGED:
2885 case EventEntry::Type::DEVICE_RESET: {
2886 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2887 EventEntry::typeToString(cancelationEventEntry->type));
2888 break;
2889 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890 }
2891
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002892 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2893 target, InputTarget::FLAG_DISPATCH_AS_IS);
2894
2895 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002896 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002897
2898 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899}
2900
Svet Ganov5d3bc372020-01-26 23:11:07 -08002901void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2902 const sp<Connection>& connection) {
2903 if (connection->status == Connection::STATUS_BROKEN) {
2904 return;
2905 }
2906
2907 nsecs_t currentTime = now();
2908
2909 std::vector<EventEntry*> downEvents =
2910 connection->inputState.synthesizePointerDownEvents(currentTime);
2911
2912 if (downEvents.empty()) {
2913 return;
2914 }
2915
2916#if DEBUG_OUTBOUND_EVENT_DETAILS
2917 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2918 connection->getInputChannelName().c_str(), downEvents.size());
2919#endif
2920
2921 InputTarget target;
2922 sp<InputWindowHandle> windowHandle =
2923 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2924 if (windowHandle != nullptr) {
2925 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002926 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002927 target.globalScaleFactor = windowInfo->globalScaleFactor;
2928 }
2929 target.inputChannel = connection->inputChannel;
2930 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2931
2932 for (EventEntry* downEventEntry : downEvents) {
2933 switch (downEventEntry->type) {
2934 case EventEntry::Type::MOTION: {
2935 logOutboundMotionDetails("down - ",
2936 static_cast<const MotionEntry&>(*downEventEntry));
2937 break;
2938 }
2939
2940 case EventEntry::Type::KEY:
2941 case EventEntry::Type::FOCUS:
2942 case EventEntry::Type::CONFIGURATION_CHANGED:
2943 case EventEntry::Type::DEVICE_RESET: {
2944 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2945 EventEntry::typeToString(downEventEntry->type));
2946 break;
2947 }
2948 }
2949
2950 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2951 target, InputTarget::FLAG_DISPATCH_AS_IS);
2952
2953 downEventEntry->release();
2954 }
2955
2956 startDispatchCycleLocked(currentTime, connection);
2957}
2958
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002959MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002960 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961 ALOG_ASSERT(pointerIds.value != 0);
2962
2963 uint32_t splitPointerIndexMap[MAX_POINTERS];
2964 PointerProperties splitPointerProperties[MAX_POINTERS];
2965 PointerCoords splitPointerCoords[MAX_POINTERS];
2966
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002967 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968 uint32_t splitPointerCount = 0;
2969
2970 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002971 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002973 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974 uint32_t pointerId = uint32_t(pointerProperties.id);
2975 if (pointerIds.hasBit(pointerId)) {
2976 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2977 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2978 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002979 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980 splitPointerCount += 1;
2981 }
2982 }
2983
2984 if (splitPointerCount != pointerIds.count()) {
2985 // This is bad. We are missing some of the pointers that we expected to deliver.
2986 // Most likely this indicates that we received an ACTION_MOVE events that has
2987 // different pointer ids than we expected based on the previous ACTION_DOWN
2988 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2989 // in this way.
2990 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002991 "we expected there to be %d pointers. This probably means we received "
2992 "a broken sequence of pointer ids from the input device.",
2993 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002994 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002995 }
2996
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002997 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002998 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002999 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3000 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3002 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003003 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003004 uint32_t pointerId = uint32_t(pointerProperties.id);
3005 if (pointerIds.hasBit(pointerId)) {
3006 if (pointerIds.count() == 1) {
3007 // The first/last pointer went down/up.
3008 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003009 ? AMOTION_EVENT_ACTION_DOWN
3010 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 } else {
3012 // A secondary pointer went down/up.
3013 uint32_t splitPointerIndex = 0;
3014 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3015 splitPointerIndex += 1;
3016 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003017 action = maskedAction |
3018 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 }
3020 } else {
3021 // An unrelated pointer changed.
3022 action = AMOTION_EVENT_ACTION_MOVE;
3023 }
3024 }
3025
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003026 int32_t newId = mIdGenerator.nextId();
3027 if (ATRACE_ENABLED()) {
3028 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3029 ") to MotionEvent(id=0x%" PRIx32 ").",
3030 originalMotionEntry.id, newId);
3031 ATRACE_NAME(message.c_str());
3032 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003033 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003034 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3035 originalMotionEntry.source, originalMotionEntry.displayId,
3036 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003037 originalMotionEntry.actionButton, originalMotionEntry.flags,
3038 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3039 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3040 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3041 originalMotionEntry.xCursorPosition,
3042 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003043 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003045 if (originalMotionEntry.injectionState) {
3046 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047 splitMotionEntry->injectionState->refCount += 1;
3048 }
3049
3050 return splitMotionEntry;
3051}
3052
3053void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3054#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003055 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056#endif
3057
3058 bool needWake;
3059 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003060 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003061
Prabir Pradhan42611e02018-11-27 14:04:02 -08003062 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003063 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064 needWake = enqueueInboundEventLocked(newEntry);
3065 } // release lock
3066
3067 if (needWake) {
3068 mLooper->wake();
3069 }
3070}
3071
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003072/**
3073 * If one of the meta shortcuts is detected, process them here:
3074 * Meta + Backspace -> generate BACK
3075 * Meta + Enter -> generate HOME
3076 * This will potentially overwrite keyCode and metaState.
3077 */
3078void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003079 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003080 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3081 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3082 if (keyCode == AKEYCODE_DEL) {
3083 newKeyCode = AKEYCODE_BACK;
3084 } else if (keyCode == AKEYCODE_ENTER) {
3085 newKeyCode = AKEYCODE_HOME;
3086 }
3087 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003088 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003089 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003090 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003091 keyCode = newKeyCode;
3092 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3093 }
3094 } else if (action == AKEY_EVENT_ACTION_UP) {
3095 // In order to maintain a consistent stream of up and down events, check to see if the key
3096 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3097 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003098 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003099 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003100 auto replacementIt = mReplacedKeys.find(replacement);
3101 if (replacementIt != mReplacedKeys.end()) {
3102 keyCode = replacementIt->second;
3103 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003104 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3105 }
3106 }
3107}
3108
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3110#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003111 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3112 "policyFlags=0x%x, action=0x%x, "
3113 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3114 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3115 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3116 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117#endif
3118 if (!validateKeyEvent(args->action)) {
3119 return;
3120 }
3121
3122 uint32_t policyFlags = args->policyFlags;
3123 int32_t flags = args->flags;
3124 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003125 // InputDispatcher tracks and generates key repeats on behalf of
3126 // whatever notifies it, so repeatCount should always be set to 0
3127 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3129 policyFlags |= POLICY_FLAG_VIRTUAL;
3130 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 if (policyFlags & POLICY_FLAG_FUNCTION) {
3133 metaState |= AMETA_FUNCTION_ON;
3134 }
3135
3136 policyFlags |= POLICY_FLAG_TRUSTED;
3137
Michael Wright78f24442014-08-06 15:55:28 -07003138 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003139 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003140
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003142 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003143 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3144 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145
Michael Wright2b3c3302018-03-02 17:19:13 +00003146 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003148 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3149 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003150 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003151 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 bool needWake;
3154 { // acquire lock
3155 mLock.lock();
3156
3157 if (shouldSendKeyToInputFilterLocked(args)) {
3158 mLock.unlock();
3159
3160 policyFlags |= POLICY_FLAG_FILTERED;
3161 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3162 return; // event was consumed by the filter
3163 }
3164
3165 mLock.lock();
3166 }
3167
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003168 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003169 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003170 args->displayId, policyFlags, args->action, flags, keyCode,
3171 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172
3173 needWake = enqueueInboundEventLocked(newEntry);
3174 mLock.unlock();
3175 } // release lock
3176
3177 if (needWake) {
3178 mLooper->wake();
3179 }
3180}
3181
3182bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3183 return mInputFilterEnabled;
3184}
3185
3186void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3187#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003188 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3189 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003190 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3191 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003192 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003193 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3194 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3195 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3196 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 for (uint32_t i = 0; i < args->pointerCount; i++) {
3198 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003199 "x=%f, y=%f, pressure=%f, size=%f, "
3200 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3201 "orientation=%f",
3202 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3203 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3204 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3205 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3206 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3207 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3208 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3209 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3210 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3211 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 }
3213#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003214 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3215 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 return;
3217 }
3218
3219 uint32_t policyFlags = args->policyFlags;
3220 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003221
3222 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003223 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003224 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3225 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003226 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228
3229 bool needWake;
3230 { // acquire lock
3231 mLock.lock();
3232
3233 if (shouldSendMotionToInputFilterLocked(args)) {
3234 mLock.unlock();
3235
3236 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003237 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003238 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3239 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003240 args->metaState, args->buttonState, args->classification, transform,
3241 args->xPrecision, args->yPrecision, args->xCursorPosition,
3242 args->yCursorPosition, args->downTime, args->eventTime,
3243 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244
3245 policyFlags |= POLICY_FLAG_FILTERED;
3246 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3247 return; // event was consumed by the filter
3248 }
3249
3250 mLock.lock();
3251 }
3252
3253 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003254 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003255 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003256 args->displayId, policyFlags, args->action, args->actionButton,
3257 args->flags, args->metaState, args->buttonState,
3258 args->classification, args->edgeFlags, args->xPrecision,
3259 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3260 args->downTime, args->pointerCount, args->pointerProperties,
3261 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262
3263 needWake = enqueueInboundEventLocked(newEntry);
3264 mLock.unlock();
3265 } // release lock
3266
3267 if (needWake) {
3268 mLooper->wake();
3269 }
3270}
3271
3272bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003273 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274}
3275
3276void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3277#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003278 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003279 "switchMask=0x%08x",
3280 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281#endif
3282
3283 uint32_t policyFlags = args->policyFlags;
3284 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003285 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286}
3287
3288void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3289#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003290 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3291 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292#endif
3293
3294 bool needWake;
3295 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003296 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297
Prabir Pradhan42611e02018-11-27 14:04:02 -08003298 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003299 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 needWake = enqueueInboundEventLocked(newEntry);
3301 } // release lock
3302
3303 if (needWake) {
3304 mLooper->wake();
3305 }
3306}
3307
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003308int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3309 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003310 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311#if DEBUG_INBOUND_EVENT_DETAILS
3312 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003313 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3314 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315#endif
3316
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003317 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318
3319 policyFlags |= POLICY_FLAG_INJECTED;
3320 if (hasInjectionPermission(injectorPid, injectorUid)) {
3321 policyFlags |= POLICY_FLAG_TRUSTED;
3322 }
3323
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003324 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003326 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003327 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3328 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 if (!validateKeyEvent(action)) {
3330 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003333 int32_t flags = incomingKey.getFlags();
3334 int32_t keyCode = incomingKey.getKeyCode();
3335 int32_t metaState = incomingKey.getMetaState();
3336 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003337 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003338 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003339 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003340 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3341 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3342 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003344 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3345 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003346 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347
3348 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3349 android::base::Timer t;
3350 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3351 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3352 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3353 std::to_string(t.duration().count()).c_str());
3354 }
3355 }
3356
3357 mLock.lock();
3358 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003359 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3360 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003361 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3362 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003363 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003364 injectedEntries.push(injectedEntry);
3365 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 }
3367
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003368 case AINPUT_EVENT_TYPE_MOTION: {
3369 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3370 int32_t action = motionEvent->getAction();
3371 size_t pointerCount = motionEvent->getPointerCount();
3372 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3373 int32_t actionButton = motionEvent->getActionButton();
3374 int32_t displayId = motionEvent->getDisplayId();
3375 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3376 return INPUT_EVENT_INJECTION_FAILED;
3377 }
3378
3379 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3380 nsecs_t eventTime = motionEvent->getEventTime();
3381 android::base::Timer t;
3382 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3383 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3384 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3385 std::to_string(t.duration().count()).c_str());
3386 }
3387 }
3388
3389 mLock.lock();
3390 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3391 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3392 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003393 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3394 motionEvent->getSource(), motionEvent->getDisplayId(),
3395 policyFlags, action, actionButton, motionEvent->getFlags(),
3396 motionEvent->getMetaState(), motionEvent->getButtonState(),
3397 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3398 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003399 motionEvent->getRawXCursorPosition(),
3400 motionEvent->getRawYCursorPosition(),
3401 motionEvent->getDownTime(), uint32_t(pointerCount),
3402 pointerProperties, samplePointerCoords,
3403 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003404 injectedEntries.push(injectedEntry);
3405 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3406 sampleEventTimes += 1;
3407 samplePointerCoords += pointerCount;
3408 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003409 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003410 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003411 motionEvent->getDisplayId(), policyFlags, action,
3412 actionButton, motionEvent->getFlags(),
3413 motionEvent->getMetaState(), motionEvent->getButtonState(),
3414 motionEvent->getClassification(),
3415 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3416 motionEvent->getYPrecision(),
3417 motionEvent->getRawXCursorPosition(),
3418 motionEvent->getRawYCursorPosition(),
3419 motionEvent->getDownTime(), uint32_t(pointerCount),
3420 pointerProperties, samplePointerCoords,
3421 motionEvent->getXOffset(), motionEvent->getYOffset());
3422 injectedEntries.push(nextInjectedEntry);
3423 }
3424 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003427 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003428 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003429 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 }
3431
3432 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3433 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3434 injectionState->injectionIsAsync = true;
3435 }
3436
3437 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003438 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439
3440 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003441 while (!injectedEntries.empty()) {
3442 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3443 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444 }
3445
3446 mLock.unlock();
3447
3448 if (needWake) {
3449 mLooper->wake();
3450 }
3451
3452 int32_t injectionResult;
3453 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003454 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455
3456 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3457 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3458 } else {
3459 for (;;) {
3460 injectionResult = injectionState->injectionResult;
3461 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3462 break;
3463 }
3464
3465 nsecs_t remainingTimeout = endTime - now();
3466 if (remainingTimeout <= 0) {
3467#if DEBUG_INJECTION
3468 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003469 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470#endif
3471 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3472 break;
3473 }
3474
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003475 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476 }
3477
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003478 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3479 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480 while (injectionState->pendingForegroundDispatches != 0) {
3481#if DEBUG_INJECTION
3482 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003483 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484#endif
3485 nsecs_t remainingTimeout = endTime - now();
3486 if (remainingTimeout <= 0) {
3487#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003488 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3489 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490#endif
3491 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3492 break;
3493 }
3494
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003495 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 }
3497 }
3498 }
3499
3500 injectionState->release();
3501 } // release lock
3502
3503#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003504 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003505 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506#endif
3507
3508 return injectionResult;
3509}
3510
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003511std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003512 std::array<uint8_t, 32> calculatedHmac;
3513 std::unique_ptr<VerifiedInputEvent> result;
3514 switch (event.getType()) {
3515 case AINPUT_EVENT_TYPE_KEY: {
3516 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3517 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3518 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003519 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003520 break;
3521 }
3522 case AINPUT_EVENT_TYPE_MOTION: {
3523 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3524 VerifiedMotionEvent verifiedMotionEvent =
3525 verifiedMotionEventFromMotionEvent(motionEvent);
3526 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003527 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003528 break;
3529 }
3530 default: {
3531 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3532 return nullptr;
3533 }
3534 }
3535 if (calculatedHmac == INVALID_HMAC) {
3536 return nullptr;
3537 }
3538 if (calculatedHmac != event.getHmac()) {
3539 return nullptr;
3540 }
3541 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003542}
3543
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003545 return injectorUid == 0 ||
3546 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003547}
3548
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003549void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550 InjectionState* injectionState = entry->injectionState;
3551 if (injectionState) {
3552#if DEBUG_INJECTION
3553 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003554 "injectorPid=%d, injectorUid=%d",
3555 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556#endif
3557
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003558 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 // Log the outcome since the injector did not wait for the injection result.
3560 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003561 case INPUT_EVENT_INJECTION_SUCCEEDED:
3562 ALOGV("Asynchronous input event injection succeeded.");
3563 break;
3564 case INPUT_EVENT_INJECTION_FAILED:
3565 ALOGW("Asynchronous input event injection failed.");
3566 break;
3567 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3568 ALOGW("Asynchronous input event injection permission denied.");
3569 break;
3570 case INPUT_EVENT_INJECTION_TIMED_OUT:
3571 ALOGW("Asynchronous input event injection timed out.");
3572 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573 }
3574 }
3575
3576 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003577 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578 }
3579}
3580
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003581void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 InjectionState* injectionState = entry->injectionState;
3583 if (injectionState) {
3584 injectionState->pendingForegroundDispatches += 1;
3585 }
3586}
3587
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003588void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 InjectionState* injectionState = entry->injectionState;
3590 if (injectionState) {
3591 injectionState->pendingForegroundDispatches -= 1;
3592
3593 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003594 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 }
3596 }
3597}
3598
Vishnu Nairad321cd2020-08-20 16:40:21 -07003599const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003600 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003601 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3602 auto it = mWindowHandlesByDisplay.find(displayId);
3603 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003604}
3605
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003607 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003608 if (windowHandleToken == nullptr) {
3609 return nullptr;
3610 }
3611
Arthur Hungb92218b2018-08-14 12:00:21 +08003612 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003613 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003614 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003615 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003616 return windowHandle;
3617 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 }
3619 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003620 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621}
3622
Vishnu Nairad321cd2020-08-20 16:40:21 -07003623sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3624 int displayId) const {
3625 if (windowHandleToken == nullptr) {
3626 return nullptr;
3627 }
3628
3629 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3630 if (windowHandle->getToken() == windowHandleToken) {
3631 return windowHandle;
3632 }
3633 }
3634 return nullptr;
3635}
3636
3637sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3638 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3639 return getWindowHandleLocked(focusedToken, displayId);
3640}
3641
Mady Mellor017bcd12020-06-23 19:12:00 +00003642bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3643 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003644 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003645 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003646 if (handle->getId() == windowHandle->getId() &&
3647 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003648 if (windowHandle->getInfo()->displayId != it.first) {
3649 ALOGE("Found window %s in display %" PRId32
3650 ", but it should belong to display %" PRId32,
3651 windowHandle->getName().c_str(), it.first,
3652 windowHandle->getInfo()->displayId);
3653 }
3654 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656 }
3657 }
3658 return false;
3659}
3660
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003661bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3662 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3663 const bool noInputChannel =
3664 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3665 if (connection != nullptr && noInputChannel) {
3666 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3667 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3668 return false;
3669 }
3670
3671 if (connection == nullptr) {
3672 if (!noInputChannel) {
3673 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3674 }
3675 return false;
3676 }
3677 if (!connection->responsive) {
3678 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3679 return false;
3680 }
3681 return true;
3682}
3683
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003684std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3685 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003686 size_t count = mInputChannelsByToken.count(token);
3687 if (count == 0) {
3688 return nullptr;
3689 }
3690 return mInputChannelsByToken.at(token);
3691}
3692
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003693void InputDispatcher::updateWindowHandlesForDisplayLocked(
3694 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3695 if (inputWindowHandles.empty()) {
3696 // Remove all handles on a display if there are no windows left.
3697 mWindowHandlesByDisplay.erase(displayId);
3698 return;
3699 }
3700
3701 // Since we compare the pointer of input window handles across window updates, we need
3702 // to make sure the handle object for the same window stays unchanged across updates.
3703 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003704 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003705 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003706 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003707 }
3708
3709 std::vector<sp<InputWindowHandle>> newHandles;
3710 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3711 if (!handle->updateInfo()) {
3712 // handle no longer valid
3713 continue;
3714 }
3715
3716 const InputWindowInfo* info = handle->getInfo();
3717 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3718 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3719 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003720 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3721 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3722 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003723 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003724 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003725 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003726 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003727 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003728 }
3729
3730 if (info->displayId != displayId) {
3731 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3732 handle->getName().c_str(), displayId, info->displayId);
3733 continue;
3734 }
3735
Robert Carredd13602020-04-13 17:24:34 -07003736 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3737 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003738 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003739 oldHandle->updateFrom(handle);
3740 newHandles.push_back(oldHandle);
3741 } else {
3742 newHandles.push_back(handle);
3743 }
3744 }
3745
3746 // Insert or replace
3747 mWindowHandlesByDisplay[displayId] = newHandles;
3748}
3749
Arthur Hung72d8dc32020-03-28 00:48:39 +00003750void InputDispatcher::setInputWindows(
3751 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3752 { // acquire lock
3753 std::scoped_lock _l(mLock);
3754 for (auto const& i : handlesPerDisplay) {
3755 setInputWindowsLocked(i.second, i.first);
3756 }
3757 }
3758 // Wake up poll loop since it may need to make new input dispatching choices.
3759 mLooper->wake();
3760}
3761
Arthur Hungb92218b2018-08-14 12:00:21 +08003762/**
3763 * Called from InputManagerService, update window handle list by displayId that can receive input.
3764 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3765 * If set an empty list, remove all handles from the specific display.
3766 * For focused handle, check if need to change and send a cancel event to previous one.
3767 * For removed handle, check if need to send a cancel event if already in touch.
3768 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003769void InputDispatcher::setInputWindowsLocked(
3770 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003771 if (DEBUG_FOCUS) {
3772 std::string windowList;
3773 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3774 windowList += iwh->getName() + " ";
3775 }
3776 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3777 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003779 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3780 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3781 const bool noInputWindow =
3782 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3783 if (noInputWindow && window->getToken() != nullptr) {
3784 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3785 window->getName().c_str());
3786 window->releaseChannel();
3787 }
3788 }
3789
Arthur Hung72d8dc32020-03-28 00:48:39 +00003790 // Copy old handles for release if they are no longer present.
3791 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003792
Arthur Hung72d8dc32020-03-28 00:48:39 +00003793 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003794
Vishnu Nairad321cd2020-08-20 16:40:21 -07003795 sp<IBinder> newFocusedToken = nullptr;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003796 bool foundHoveredWindow = false;
3797 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003798 // Set newFocusedToken to the top most focused window instead of the last one
3799 if (!newFocusedToken && windowHandle->getInfo()->focusable &&
Arthur Hung72d8dc32020-03-28 00:48:39 +00003800 windowHandle->getInfo()->visible) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003801 newFocusedToken = windowHandle->getToken();
Arthur Hung72d8dc32020-03-28 00:48:39 +00003802 }
3803 if (windowHandle == mLastHoverWindowHandle) {
3804 foundHoveredWindow = true;
3805 }
3806 }
3807
3808 if (!foundHoveredWindow) {
3809 mLastHoverWindowHandle = nullptr;
3810 }
3811
Vishnu Nairad321cd2020-08-20 16:40:21 -07003812 sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3813 if (oldFocusedToken != newFocusedToken) {
3814 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, "setInputWindowsLocked");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003817 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3818 mTouchStatesByDisplay.find(displayId);
3819 if (stateIt != mTouchStatesByDisplay.end()) {
3820 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003821 for (size_t i = 0; i < state.windows.size();) {
3822 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003823 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003824 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003825 ALOGD("Touched window was removed: %s in display %" PRId32,
3826 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003827 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003828 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003829 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3830 if (touchedInputChannel != nullptr) {
3831 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3832 "touched window was removed");
3833 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003835 state.windows.erase(state.windows.begin() + i);
3836 } else {
3837 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
3839 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003840 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003841
Arthur Hung72d8dc32020-03-28 00:48:39 +00003842 // Release information for windows that are no longer present.
3843 // This ensures that unused input channels are released promptly.
3844 // Otherwise, they might stick around until the window handle is destroyed
3845 // which might not happen until the next GC.
3846 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003847 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003848 if (DEBUG_FOCUS) {
3849 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003850 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003851 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003852 }
chaviw291d88a2019-02-14 10:33:58 -08003853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854}
3855
3856void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003857 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003858 if (DEBUG_FOCUS) {
3859 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3860 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3861 }
Chris Yea209fde2020-07-22 13:54:51 -07003862 if (inputApplicationHandle != nullptr &&
3863 inputApplicationHandle->getApplicationToken() != nullptr) {
3864 // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003865 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866
Chris Yea209fde2020-07-22 13:54:51 -07003867 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003868 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003869
Chris Yea209fde2020-07-22 13:54:51 -07003870 // If oldFocusedApplicationHandle already exists
3871 if (oldFocusedApplicationHandle != nullptr) {
3872 // If a new focused application handle is different from the old one and
3873 // old focus application info is awaited focused application info.
3874 if (*oldFocusedApplicationHandle != *inputApplicationHandle &&
3875 mAwaitedFocusedApplication != nullptr &&
3876 *oldFocusedApplicationHandle == *mAwaitedFocusedApplication) {
3877 resetNoFocusedWindowTimeoutLocked();
3878 }
3879 // Erase the old application from container first
3880 mFocusedApplicationHandlesByDisplay.erase(displayId);
3881 // Should already get freed after removed from container but just double check.
3882 oldFocusedApplicationHandle.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003883 }
3884
Chris Yea209fde2020-07-22 13:54:51 -07003885 // Set the new application handle.
3886 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 } // release lock
3888
3889 // Wake up poll loop since it may need to make new input dispatching choices.
3890 mLooper->wake();
3891}
3892
Tiger Huang721e26f2018-07-24 22:26:19 +08003893/**
3894 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3895 * the display not specified.
3896 *
3897 * We track any unreleased events for each window. If a window loses the ability to receive the
3898 * released event, we will send a cancel event to it. So when the focused display is changed, we
3899 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3900 * display. The display-specified events won't be affected.
3901 */
3902void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003903 if (DEBUG_FOCUS) {
3904 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3905 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003906 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003907 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003908
3909 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003910 sp<IBinder> oldFocusedWindowToken =
3911 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
3912 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003913 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07003914 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08003915 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003916 CancelationOptions
3917 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3918 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003919 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003920 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3921 }
3922 }
3923 mFocusedDisplayId = displayId;
3924
Chris Ye3c2d6f52020-08-09 10:39:48 -07003925 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07003926 sp<IBinder> newFocusedWindowToken =
3927 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3928 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08003929
Vishnu Nairad321cd2020-08-20 16:40:21 -07003930 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003931 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003932 if (!mFocusedWindowTokenByDisplay.empty()) {
3933 ALOGE("But another display has a focused window\n%s",
3934 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003935 }
3936 }
3937 }
3938
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003939 if (DEBUG_FOCUS) {
3940 logDispatchStateLocked();
3941 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003942 } // release lock
3943
3944 // Wake up poll loop since it may need to make new input dispatching choices.
3945 mLooper->wake();
3946}
3947
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003949 if (DEBUG_FOCUS) {
3950 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952
3953 bool changed;
3954 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003955 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956
3957 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3958 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003959 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 }
3961
3962 if (mDispatchEnabled && !enabled) {
3963 resetAndDropEverythingLocked("dispatcher is being disabled");
3964 }
3965
3966 mDispatchEnabled = enabled;
3967 mDispatchFrozen = frozen;
3968 changed = true;
3969 } else {
3970 changed = false;
3971 }
3972
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003973 if (DEBUG_FOCUS) {
3974 logDispatchStateLocked();
3975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 } // release lock
3977
3978 if (changed) {
3979 // Wake up poll loop since it may need to make new input dispatching choices.
3980 mLooper->wake();
3981 }
3982}
3983
3984void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003985 if (DEBUG_FOCUS) {
3986 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988
3989 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003990 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003991
3992 if (mInputFilterEnabled == enabled) {
3993 return;
3994 }
3995
3996 mInputFilterEnabled = enabled;
3997 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3998 } // release lock
3999
4000 // Wake up poll loop since there might be work to do to drop everything.
4001 mLooper->wake();
4002}
4003
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004004void InputDispatcher::setInTouchMode(bool inTouchMode) {
4005 std::scoped_lock lock(mLock);
4006 mInTouchMode = inTouchMode;
4007}
4008
chaviwfbe5d9c2018-12-26 12:23:37 -08004009bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4010 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004011 if (DEBUG_FOCUS) {
4012 ALOGD("Trivial transfer to same window.");
4013 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004014 return true;
4015 }
4016
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004018 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019
chaviwfbe5d9c2018-12-26 12:23:37 -08004020 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4021 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004022 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004023 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024 return false;
4025 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004026 if (DEBUG_FOCUS) {
4027 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4028 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004031 if (DEBUG_FOCUS) {
4032 ALOGD("Cannot transfer focus because windows are on different displays.");
4033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034 return false;
4035 }
4036
4037 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004038 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4039 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004040 for (size_t i = 0; i < state.windows.size(); i++) {
4041 const TouchedWindow& touchedWindow = state.windows[i];
4042 if (touchedWindow.windowHandle == fromWindowHandle) {
4043 int32_t oldTargetFlags = touchedWindow.targetFlags;
4044 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004046 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004048 int32_t newTargetFlags = oldTargetFlags &
4049 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4050 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004051 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052
Jeff Brownf086ddb2014-02-11 14:28:48 -08004053 found = true;
4054 goto Found;
4055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 }
4057 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004058 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004060 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004061 if (DEBUG_FOCUS) {
4062 ALOGD("Focus transfer failed because from window did not have focus.");
4063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064 return false;
4065 }
4066
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004067 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4068 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004069 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004070 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004071 CancelationOptions
4072 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4073 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004075 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 }
4077
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004078 if (DEBUG_FOCUS) {
4079 logDispatchStateLocked();
4080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 } // release lock
4082
4083 // Wake up poll loop since it may need to make new input dispatching choices.
4084 mLooper->wake();
4085 return true;
4086}
4087
4088void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004089 if (DEBUG_FOCUS) {
4090 ALOGD("Resetting and dropping all events (%s).", reason);
4091 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092
4093 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4094 synthesizeCancelationEventsForAllConnectionsLocked(options);
4095
4096 resetKeyRepeatLocked();
4097 releasePendingEventLocked();
4098 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004099 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004100
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004101 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004102 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004104 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105}
4106
4107void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004108 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 dumpDispatchStateLocked(dump);
4110
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004111 std::istringstream stream(dump);
4112 std::string line;
4113
4114 while (std::getline(stream, line, '\n')) {
4115 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 }
4117}
4118
Vishnu Nairad321cd2020-08-20 16:40:21 -07004119std::string InputDispatcher::dumpFocusedWindowsLocked() {
4120 if (mFocusedWindowTokenByDisplay.empty()) {
4121 return INDENT "FocusedWindows: <none>\n";
4122 }
4123
4124 std::string dump;
4125 dump += INDENT "FocusedWindows:\n";
4126 for (auto& it : mFocusedWindowTokenByDisplay) {
4127 const int32_t displayId = it.first;
4128 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4129 if (windowHandle) {
4130 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4131 windowHandle->getName().c_str());
4132 } else {
4133 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4134 " has focused token without a window'\n",
4135 displayId);
4136 }
4137 }
4138 return dump;
4139}
4140
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004141void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004142 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4143 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4144 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004145 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146
Tiger Huang721e26f2018-07-24 22:26:19 +08004147 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4148 dump += StringPrintf(INDENT "FocusedApplications:\n");
4149 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4150 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004151 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004152 const std::chrono::duration timeout =
4153 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004154 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004155 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004156 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004159 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004161
Vishnu Nairad321cd2020-08-20 16:40:21 -07004162 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004164 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004165 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004166 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4167 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004168 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004169 state.displayId, toString(state.down), toString(state.split),
4170 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004171 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004172 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004173 for (size_t i = 0; i < state.windows.size(); i++) {
4174 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004175 dump += StringPrintf(INDENT4
4176 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4177 i, touchedWindow.windowHandle->getName().c_str(),
4178 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004179 }
4180 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004181 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004182 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004183 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004184 dump += INDENT3 "Portal windows:\n";
4185 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004186 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004187 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4188 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004189 }
4190 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 }
4192 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004193 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 }
4195
Arthur Hungb92218b2018-08-14 12:00:21 +08004196 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004197 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004198 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004199 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004200 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004201 dump += INDENT2 "Windows:\n";
4202 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004203 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004204 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205
Arthur Hungb92218b2018-08-14 12:00:21 +08004206 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004207 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4208 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004209 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004210 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004211 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004212 i, windowInfo->name.c_str(), windowInfo->displayId,
4213 windowInfo->portalToDisplayId,
4214 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004215 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004216 toString(windowInfo->hasWallpaper),
4217 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004218 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004219 static_cast<int32_t>(windowInfo->type),
4220 windowInfo->frameLeft, windowInfo->frameTop,
4221 windowInfo->frameRight, windowInfo->frameBottom,
chaviw1ff3d1e2020-07-01 15:53:47 -07004222 windowInfo->globalScaleFactor);
Arthur Hungb92218b2018-08-14 12:00:21 +08004223 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004224 dump += StringPrintf(", inputFeatures=%s",
4225 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004226 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4227 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004228 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004229 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004230 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004231 }
4232 } else {
4233 dump += INDENT2 "Windows: <none>\n";
4234 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 }
4236 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004237 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 }
4239
Michael Wright3dd60e22019-03-27 22:06:44 +00004240 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004241 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004242 const std::vector<Monitor>& monitors = it.second;
4243 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4244 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004245 }
4246 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004247 const std::vector<Monitor>& monitors = it.second;
4248 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4249 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004250 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004252 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 }
4254
4255 nsecs_t currentTime = now();
4256
4257 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004258 if (!mRecentQueue.empty()) {
4259 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4260 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004261 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004263 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 }
4265 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004266 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 }
4268
4269 // Dump event currently being dispatched.
4270 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004271 dump += INDENT "PendingEvent:\n";
4272 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004274 dump += StringPrintf(", age=%" PRId64 "ms\n",
4275 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004277 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 }
4279
4280 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004281 if (!mInboundQueue.empty()) {
4282 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4283 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004284 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004286 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 }
4288 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004289 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 }
4291
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004292 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004293 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004294 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4295 const KeyReplacement& replacement = pair.first;
4296 int32_t newKeyCode = pair.second;
4297 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004298 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004299 }
4300 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004301 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004302 }
4303
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004304 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004305 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004306 for (const auto& pair : mConnectionsByFd) {
4307 const sp<Connection>& connection = pair.second;
4308 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004309 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004310 pair.first, connection->getInputChannelName().c_str(),
4311 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004312 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004314 if (!connection->outboundQueue.empty()) {
4315 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4316 connection->outboundQueue.size());
4317 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 dump.append(INDENT4);
4319 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004320 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4321 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004322 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004323 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 }
4325 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004326 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
4328
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004329 if (!connection->waitQueue.empty()) {
4330 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4331 connection->waitQueue.size());
4332 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004333 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004335 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004336 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004337 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004338 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004339 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 }
4341 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004342 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 }
4344 }
4345 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004346 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 }
4348
4349 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004350 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4351 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004353 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354 }
4355
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004356 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004357 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4358 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4359 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360}
4361
Michael Wright3dd60e22019-03-27 22:06:44 +00004362void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4363 const size_t numMonitors = monitors.size();
4364 for (size_t i = 0; i < numMonitors; i++) {
4365 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004366 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004367 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4368 dump += "\n";
4369 }
4370}
4371
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004372status_t InputDispatcher::registerInputChannel(const std::shared_ptr<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004374 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375#endif
4376
4377 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004378 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004379 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004380 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004382 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 return BAD_VALUE;
4384 }
4385
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004386 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387
4388 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004389 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004390 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4393 } // release lock
4394
4395 // Wake the looper because some connections have changed.
4396 mLooper->wake();
4397 return OK;
4398}
4399
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004400status_t InputDispatcher::registerInputMonitor(const std::shared_ptr<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004401 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004402 { // acquire lock
4403 std::scoped_lock _l(mLock);
4404
4405 if (displayId < 0) {
4406 ALOGW("Attempted to register input monitor without a specified display.");
4407 return BAD_VALUE;
4408 }
4409
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004410 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004411 ALOGW("Attempted to register input monitor without an identifying token.");
4412 return BAD_VALUE;
4413 }
4414
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004415 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004416
4417 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004418 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004419 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004420
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004421 auto& monitorsByDisplay =
4422 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004423 monitorsByDisplay[displayId].emplace_back(inputChannel);
4424
4425 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004426 }
4427 // Wake the looper because some connections have changed.
4428 mLooper->wake();
4429 return OK;
4430}
4431
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004432status_t InputDispatcher::unregisterInputChannel(const InputChannel& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433#if DEBUG_REGISTRATION
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004434 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435#endif
4436
4437 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004438 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439
4440 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4441 if (status) {
4442 return status;
4443 }
4444 } // release lock
4445
4446 // Wake the poll loop because removing the connection may have changed the current
4447 // synchronization state.
4448 mLooper->wake();
4449 return OK;
4450}
4451
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004452status_t InputDispatcher::unregisterInputChannelLocked(const InputChannel& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004453 bool notify) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004454 sp<Connection> connection = getConnectionLocked(inputChannel.getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004455 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004457 inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458 return BAD_VALUE;
4459 }
4460
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004461 removeConnectionLocked(connection);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004462 mInputChannelsByToken.erase(inputChannel.getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004463
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464 if (connection->monitor) {
4465 removeMonitorChannelLocked(inputChannel);
4466 }
4467
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004468 mLooper->removeFd(inputChannel.getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469
4470 nsecs_t currentTime = now();
4471 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4472
4473 connection->status = Connection::STATUS_ZOMBIE;
4474 return OK;
4475}
4476
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004477void InputDispatcher::removeMonitorChannelLocked(const InputChannel& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004478 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4479 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4480}
4481
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004482void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004483 const InputChannel& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004484 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004485 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004486 std::vector<Monitor>& monitors = it->second;
4487 const size_t numMonitors = monitors.size();
4488 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004489 if (*monitors[i].inputChannel == inputChannel) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004490 monitors.erase(monitors.begin() + i);
4491 break;
4492 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004493 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004494 if (monitors.empty()) {
4495 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004496 } else {
4497 ++it;
4498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 }
4500}
4501
Michael Wright3dd60e22019-03-27 22:06:44 +00004502status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4503 { // acquire lock
4504 std::scoped_lock _l(mLock);
4505 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4506
4507 if (!foundDisplayId) {
4508 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4509 return BAD_VALUE;
4510 }
4511 int32_t displayId = foundDisplayId.value();
4512
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004513 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4514 mTouchStatesByDisplay.find(displayId);
4515 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004516 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4517 return BAD_VALUE;
4518 }
4519
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004520 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004521 std::optional<int32_t> foundDeviceId;
4522 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004523 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004524 foundDeviceId = state.deviceId;
4525 }
4526 }
4527 if (!foundDeviceId || !state.down) {
4528 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004529 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004530 return BAD_VALUE;
4531 }
4532 int32_t deviceId = foundDeviceId.value();
4533
4534 // Send cancel events to all the input channels we're stealing from.
4535 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004536 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004537 options.deviceId = deviceId;
4538 options.displayId = displayId;
4539 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004540 std::shared_ptr<InputChannel> channel =
4541 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004542 if (channel != nullptr) {
4543 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4544 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004545 }
4546 // Then clear the current touch state so we stop dispatching to them as well.
4547 state.filterNonMonitors();
4548 }
4549 return OK;
4550}
4551
Michael Wright3dd60e22019-03-27 22:06:44 +00004552std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4553 const sp<IBinder>& token) {
4554 for (const auto& it : mGestureMonitorsByDisplay) {
4555 const std::vector<Monitor>& monitors = it.second;
4556 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004557 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004558 return it.first;
4559 }
4560 }
4561 }
4562 return std::nullopt;
4563}
4564
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004565sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004566 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004567 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004568 }
4569
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004570 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004571 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004572 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004573 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574 }
4575 }
Robert Carr4e670e52018-08-15 13:26:12 -07004576
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004577 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578}
4579
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004580void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004581 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004582 removeByValue(mConnectionsByFd, connection);
4583}
4584
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004585void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4586 const sp<Connection>& connection, uint32_t seq,
4587 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004588 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4589 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004590 commandEntry->connection = connection;
4591 commandEntry->eventTime = currentTime;
4592 commandEntry->seq = seq;
4593 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004594 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595}
4596
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004597void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4598 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004600 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004602 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4603 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004605 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606}
4607
Vishnu Nairad321cd2020-08-20 16:40:21 -07004608void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4609 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004610 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4611 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004612 commandEntry->oldToken = oldToken;
4613 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004614 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004615}
4616
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004617void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4618 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4619 // is already healthy again. Don't raise ANR in this situation
4620 if (connection->waitQueue.empty()) {
4621 ALOGI("Not raising ANR because the connection %s has recovered",
4622 connection->inputChannel->getName().c_str());
4623 return;
4624 }
4625 /**
4626 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4627 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4628 * has changed. This could cause newer entries to time out before the already dispatched
4629 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4630 * processes the events linearly. So providing information about the oldest entry seems to be
4631 * most useful.
4632 */
4633 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4634 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4635 std::string reason =
4636 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4637 connection->inputChannel->getName().c_str(),
4638 ns2ms(currentWait),
4639 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004641 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4642 reason);
4643
4644 std::unique_ptr<CommandEntry> commandEntry =
4645 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4646 commandEntry->inputApplicationHandle = nullptr;
4647 commandEntry->inputChannel = connection->inputChannel;
4648 commandEntry->reason = std::move(reason);
4649 postCommandLocked(std::move(commandEntry));
4650}
4651
Chris Yea209fde2020-07-22 13:54:51 -07004652void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004653 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4654 application->getName().c_str());
4655
4656 updateLastAnrStateLocked(application, reason);
4657
4658 std::unique_ptr<CommandEntry> commandEntry =
4659 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4660 commandEntry->inputApplicationHandle = application;
4661 commandEntry->inputChannel = nullptr;
4662 commandEntry->reason = std::move(reason);
4663 postCommandLocked(std::move(commandEntry));
4664}
4665
4666void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4667 const std::string& reason) {
4668 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4669 updateLastAnrStateLocked(windowLabel, reason);
4670}
4671
Chris Yea209fde2020-07-22 13:54:51 -07004672void InputDispatcher::updateLastAnrStateLocked(
4673 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004674 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4675 updateLastAnrStateLocked(windowLabel, reason);
4676}
4677
4678void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4679 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004681 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682 struct tm tm;
4683 localtime_r(&t, &tm);
4684 char timestr[64];
4685 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004686 mLastAnrState.clear();
4687 mLastAnrState += INDENT "ANR:\n";
4688 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004689 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4690 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004691 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692}
4693
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004694void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695 mLock.unlock();
4696
4697 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4698
4699 mLock.lock();
4700}
4701
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004702void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 sp<Connection> connection = commandEntry->connection;
4704
4705 if (connection->status != Connection::STATUS_ZOMBIE) {
4706 mLock.unlock();
4707
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004708 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709
4710 mLock.lock();
4711 }
4712}
4713
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004714void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004715 sp<IBinder> oldToken = commandEntry->oldToken;
4716 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004717 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004718 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004719 mLock.lock();
4720}
4721
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004722void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004723 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004724 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725 mLock.unlock();
4726
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004727 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004728 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729
4730 mLock.lock();
4731
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004732 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004733 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4734 } else {
4735 // stop waking up for events in this connection, it is already not responding
4736 sp<Connection> connection = getConnectionLocked(token);
4737 if (connection == nullptr) {
4738 return;
4739 }
4740 cancelEventsForAnrLocked(connection);
4741 }
4742}
4743
Chris Yea209fde2020-07-22 13:54:51 -07004744void InputDispatcher::extendAnrTimeoutsLocked(
4745 const std::shared_ptr<InputApplicationHandle>& application,
4746 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004747 sp<Connection> connection = getConnectionLocked(connectionToken);
4748 if (connection == nullptr) {
4749 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4750 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004751 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004752 mAwaitedFocusedApplication = application;
4753 } else {
4754 // It's also possible that the connection already disappeared. No action necessary.
4755 }
4756 return;
4757 }
4758
4759 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004760 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004761
4762 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004763 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004764 for (DispatchEntry* entry : connection->waitQueue) {
4765 if (newTimeout >= entry->timeoutTime) {
4766 // Already removed old entries when connection was marked unresponsive
4767 entry->timeoutTime = newTimeout;
4768 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4769 }
4770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771}
4772
4773void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4774 CommandEntry* commandEntry) {
4775 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004776 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777
4778 mLock.unlock();
4779
Michael Wright2b3c3302018-03-02 17:19:13 +00004780 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004781 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004782 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004783 : nullptr;
4784 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004785 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4786 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004787 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004788 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789
4790 mLock.lock();
4791
4792 if (delay < 0) {
4793 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4794 } else if (!delay) {
4795 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4796 } else {
4797 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4798 entry->interceptKeyWakeupTime = now() + delay;
4799 }
4800 entry->release();
4801}
4802
chaviwfd6d3512019-03-25 13:23:49 -07004803void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4804 mLock.unlock();
4805 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4806 mLock.lock();
4807}
4808
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004809/**
4810 * Connection is responsive if it has no events in the waitQueue that are older than the
4811 * current time.
4812 */
4813static bool isConnectionResponsive(const Connection& connection) {
4814 const nsecs_t currentTime = now();
4815 for (const DispatchEntry* entry : connection.waitQueue) {
4816 if (entry->timeoutTime < currentTime) {
4817 return false;
4818 }
4819 }
4820 return true;
4821}
4822
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004823void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004825 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004827 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828
4829 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004830 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004831 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004832 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004834 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004835 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004836 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004837 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4838 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004839 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004840 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004841
4842 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004843 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004844 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4845 restartEvent =
4846 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004847 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004848 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4849 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4850 handled);
4851 } else {
4852 restartEvent = false;
4853 }
4854
4855 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004856 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004857 // contents of the wait queue to have been drained, so we need to double-check
4858 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004859 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4860 if (dispatchEntryIt != connection->waitQueue.end()) {
4861 dispatchEntry = *dispatchEntryIt;
4862 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863 mAnrTracker.erase(dispatchEntry->timeoutTime,
4864 connection->inputChannel->getConnectionToken());
4865 if (!connection->responsive) {
4866 connection->responsive = isConnectionResponsive(*connection);
4867 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004868 traceWaitQueueLength(connection);
4869 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004870 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004871 traceOutboundQueueLength(connection);
4872 } else {
4873 releaseDispatchEntry(dispatchEntry);
4874 }
4875 }
4876
4877 // Start the next dispatch cycle for this connection.
4878 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879}
4880
4881bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004882 DispatchEntry* dispatchEntry,
4883 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004884 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004885 if (!handled) {
4886 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004887 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004888 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004889 return false;
4890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004892 // Get the fallback key state.
4893 // Clear it out after dispatching the UP.
4894 int32_t originalKeyCode = keyEntry->keyCode;
4895 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4896 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4897 connection->inputState.removeFallbackKey(originalKeyCode);
4898 }
4899
4900 if (handled || !dispatchEntry->hasForegroundTarget()) {
4901 // If the application handles the original key for which we previously
4902 // generated a fallback or if the window is not a foreground window,
4903 // then cancel the associated fallback key, if any.
4904 if (fallbackKeyCode != -1) {
4905 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004907 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004908 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4909 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4910 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004912 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004913 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914
4915 mLock.unlock();
4916
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004917 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004918 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919
4920 mLock.lock();
4921
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004922 // Cancel the fallback key.
4923 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004925 "application handled the original non-fallback key "
4926 "or is no longer a foreground target, "
4927 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 options.keyCode = fallbackKeyCode;
4929 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004931 connection->inputState.removeFallbackKey(originalKeyCode);
4932 }
4933 } else {
4934 // If the application did not handle a non-fallback key, first check
4935 // that we are in a good state to perform unhandled key event processing
4936 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004937 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004938 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004940 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004941 "since this is not an initial down. "
4942 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4943 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004945 return false;
4946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004947
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004948 // Dispatch the unhandled key to the policy.
4949#if DEBUG_OUTBOUND_EVENT_DETAILS
4950 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004951 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4952 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004953#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004954 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004955
4956 mLock.unlock();
4957
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004958 bool fallback =
4959 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4960 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004961
4962 mLock.lock();
4963
4964 if (connection->status != Connection::STATUS_NORMAL) {
4965 connection->inputState.removeFallbackKey(originalKeyCode);
4966 return false;
4967 }
4968
4969 // Latch the fallback keycode for this key on an initial down.
4970 // The fallback keycode cannot change at any other point in the lifecycle.
4971 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004973 fallbackKeyCode = event.getKeyCode();
4974 } else {
4975 fallbackKeyCode = AKEYCODE_UNKNOWN;
4976 }
4977 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4978 }
4979
4980 ALOG_ASSERT(fallbackKeyCode != -1);
4981
4982 // Cancel the fallback key if the policy decides not to send it anymore.
4983 // We will continue to dispatch the key to the policy but we will no
4984 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004985 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4986 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004987#if DEBUG_OUTBOUND_EVENT_DETAILS
4988 if (fallback) {
4989 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004990 "as a fallback for %d, but on the DOWN it had requested "
4991 "to send %d instead. Fallback canceled.",
4992 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004993 } else {
4994 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004995 "but on the DOWN it had requested to send %d. "
4996 "Fallback canceled.",
4997 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004998 }
4999#endif
5000
5001 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
5002 "canceling fallback, policy no longer desires it");
5003 options.keyCode = fallbackKeyCode;
5004 synthesizeCancelationEventsForConnectionLocked(connection, options);
5005
5006 fallback = false;
5007 fallbackKeyCode = AKEYCODE_UNKNOWN;
5008 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005009 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005010 }
5011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005012
5013#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005014 {
5015 std::string msg;
5016 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5017 connection->inputState.getFallbackKeys();
5018 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005019 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005020 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005021 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005022 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005023 }
5024#endif
5025
5026 if (fallback) {
5027 // Restart the dispatch cycle using the fallback key.
5028 keyEntry->eventTime = event.getEventTime();
5029 keyEntry->deviceId = event.getDeviceId();
5030 keyEntry->source = event.getSource();
5031 keyEntry->displayId = event.getDisplayId();
5032 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5033 keyEntry->keyCode = fallbackKeyCode;
5034 keyEntry->scanCode = event.getScanCode();
5035 keyEntry->metaState = event.getMetaState();
5036 keyEntry->repeatCount = event.getRepeatCount();
5037 keyEntry->downTime = event.getDownTime();
5038 keyEntry->syntheticRepeat = false;
5039
5040#if DEBUG_OUTBOUND_EVENT_DETAILS
5041 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005042 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5043 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005044#endif
5045 return true; // restart the event
5046 } else {
5047#if DEBUG_OUTBOUND_EVENT_DETAILS
5048 ALOGD("Unhandled key event: No fallback key.");
5049#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005050
5051 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005052 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053 }
5054 }
5055 return false;
5056}
5057
5058bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005059 DispatchEntry* dispatchEntry,
5060 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061 return false;
5062}
5063
5064void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5065 mLock.unlock();
5066
5067 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5068
5069 mLock.lock();
5070}
5071
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005072KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5073 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005074 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005075 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5076 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005077 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005078}
5079
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005080void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5081 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005082 // TODO Write some statistics about how long we spend waiting.
5083}
5084
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005085/**
5086 * Report the touch event latency to the statsd server.
5087 * Input events are reported for statistics if:
5088 * - This is a touchscreen event
5089 * - InputFilter is not enabled
5090 * - Event is not injected or synthesized
5091 *
5092 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5093 * from getting aggregated with the "old" data.
5094 */
5095void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5096 REQUIRES(mLock) {
5097 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5098 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5099 if (!reportForStatistics) {
5100 return;
5101 }
5102
5103 if (mTouchStatistics.shouldReport()) {
5104 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5105 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5106 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5107 mTouchStatistics.reset();
5108 }
5109 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5110 mTouchStatistics.addValue(latencyMicros);
5111}
5112
Michael Wrightd02c5b62014-02-10 15:10:22 -08005113void InputDispatcher::traceInboundQueueLengthLocked() {
5114 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005115 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116 }
5117}
5118
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005119void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120 if (ATRACE_ENABLED()) {
5121 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005122 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005123 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124 }
5125}
5126
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005127void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128 if (ATRACE_ENABLED()) {
5129 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005130 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005131 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 }
5133}
5134
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005135void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005136 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005138 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139 dumpDispatchStateLocked(dump);
5140
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005141 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005142 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005143 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144 }
5145}
5146
5147void InputDispatcher::monitor() {
5148 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005149 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005151 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152}
5153
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005154/**
5155 * Wake up the dispatcher and wait until it processes all events and commands.
5156 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5157 * this method can be safely called from any thread, as long as you've ensured that
5158 * the work you are interested in completing has already been queued.
5159 */
5160bool InputDispatcher::waitForIdle() {
5161 /**
5162 * Timeout should represent the longest possible time that a device might spend processing
5163 * events and commands.
5164 */
5165 constexpr std::chrono::duration TIMEOUT = 100ms;
5166 std::unique_lock lock(mLock);
5167 mLooper->wake();
5168 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5169 return result == std::cv_status::no_timeout;
5170}
5171
Vishnu Naire798b472020-07-23 13:52:21 -07005172/**
5173 * Sets focus to the window identified by the token. This must be called
5174 * after updating any input window handles.
5175 *
5176 * Params:
5177 * request.token - input channel token used to identify the window that should gain focus.
5178 * request.focusedToken - the token that the caller expects currently to be focused. If the
5179 * specified token does not match the currently focused window, this request will be dropped.
5180 * If the specified focused token matches the currently focused window, the call will succeed.
5181 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5182 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5183 * when requesting the focus change. This determines which request gets
5184 * precedence if there is a focus change request from another source such as pointer down.
5185 */
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005186void InputDispatcher::setFocusedWindow(const FocusRequest& request) {}
5187
Vishnu Nairad321cd2020-08-20 16:40:21 -07005188void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5189 const sp<IBinder>& newFocusedToken, int32_t displayId,
5190 std::string_view reason) {
5191 if (oldFocusedToken) {
5192 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005193 if (focusedInputChannel) {
5194 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5195 "focus left window");
5196 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005197 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005198 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005199 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005200 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005201 if (newFocusedToken) {
5202 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5203 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005204 }
5205
5206 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005207 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005208 }
5209}
Garfield Tane84e6f92019-08-29 17:28:41 -07005210} // namespace android::inputdispatcher