blob: 4a1a74eeaf741c860f5c33b9b0efd9e26da2c28c [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 Vishniakouadefc3e2020-09-02 22:28:29 -0500382 unregisterInputChannel(connection->inputChannel->getConnectionToken());
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 Vishniakouadefc3e2020-09-02 22:28:29 -05002796 d->unregisterInputChannelLocked(connection->inputChannel->getConnectionToken(), 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
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003316 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317
3318 policyFlags |= POLICY_FLAG_INJECTED;
3319 if (hasInjectionPermission(injectorPid, injectorUid)) {
3320 policyFlags |= POLICY_FLAG_TRUSTED;
3321 }
3322
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003323 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003325 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003326 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3327 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003328 if (!validateKeyEvent(action)) {
3329 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003332 int32_t flags = incomingKey.getFlags();
3333 int32_t keyCode = incomingKey.getKeyCode();
3334 int32_t metaState = incomingKey.getMetaState();
3335 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003336 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003337 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003338 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003339 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3340 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3341 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003343 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3344 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003345 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003346
3347 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3348 android::base::Timer t;
3349 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3350 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3351 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3352 std::to_string(t.duration().count()).c_str());
3353 }
3354 }
3355
3356 mLock.lock();
3357 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003358 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3359 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003360 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3361 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003362 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003363 injectedEntries.push(injectedEntry);
3364 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365 }
3366
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003367 case AINPUT_EVENT_TYPE_MOTION: {
3368 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3369 int32_t action = motionEvent->getAction();
3370 size_t pointerCount = motionEvent->getPointerCount();
3371 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3372 int32_t actionButton = motionEvent->getActionButton();
3373 int32_t displayId = motionEvent->getDisplayId();
3374 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3375 return INPUT_EVENT_INJECTION_FAILED;
3376 }
3377
3378 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3379 nsecs_t eventTime = motionEvent->getEventTime();
3380 android::base::Timer t;
3381 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3382 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3383 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3384 std::to_string(t.duration().count()).c_str());
3385 }
3386 }
3387
3388 mLock.lock();
3389 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3390 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3391 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003392 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3393 motionEvent->getSource(), motionEvent->getDisplayId(),
3394 policyFlags, action, actionButton, motionEvent->getFlags(),
3395 motionEvent->getMetaState(), motionEvent->getButtonState(),
3396 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3397 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003398 motionEvent->getRawXCursorPosition(),
3399 motionEvent->getRawYCursorPosition(),
3400 motionEvent->getDownTime(), uint32_t(pointerCount),
3401 pointerProperties, samplePointerCoords,
3402 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003403 injectedEntries.push(injectedEntry);
3404 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3405 sampleEventTimes += 1;
3406 samplePointerCoords += pointerCount;
3407 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003408 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003409 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003410 motionEvent->getDisplayId(), policyFlags, action,
3411 actionButton, motionEvent->getFlags(),
3412 motionEvent->getMetaState(), motionEvent->getButtonState(),
3413 motionEvent->getClassification(),
3414 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3415 motionEvent->getYPrecision(),
3416 motionEvent->getRawXCursorPosition(),
3417 motionEvent->getRawYCursorPosition(),
3418 motionEvent->getDownTime(), uint32_t(pointerCount),
3419 pointerProperties, samplePointerCoords,
3420 motionEvent->getXOffset(), motionEvent->getYOffset());
3421 injectedEntries.push(nextInjectedEntry);
3422 }
3423 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003426 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003427 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003428 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 }
3430
3431 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3432 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3433 injectionState->injectionIsAsync = true;
3434 }
3435
3436 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003437 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438
3439 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003440 while (!injectedEntries.empty()) {
3441 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3442 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 }
3444
3445 mLock.unlock();
3446
3447 if (needWake) {
3448 mLooper->wake();
3449 }
3450
3451 int32_t injectionResult;
3452 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003453 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454
3455 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3456 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3457 } else {
3458 for (;;) {
3459 injectionResult = injectionState->injectionResult;
3460 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3461 break;
3462 }
3463
3464 nsecs_t remainingTimeout = endTime - now();
3465 if (remainingTimeout <= 0) {
3466#if DEBUG_INJECTION
3467 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003468 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469#endif
3470 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3471 break;
3472 }
3473
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003474 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 }
3476
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003477 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3478 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 while (injectionState->pendingForegroundDispatches != 0) {
3480#if DEBUG_INJECTION
3481 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003482 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483#endif
3484 nsecs_t remainingTimeout = endTime - now();
3485 if (remainingTimeout <= 0) {
3486#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003487 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3488 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489#endif
3490 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3491 break;
3492 }
3493
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003494 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495 }
3496 }
3497 }
3498
3499 injectionState->release();
3500 } // release lock
3501
3502#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003503 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003504 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505#endif
3506
3507 return injectionResult;
3508}
3509
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003510std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003511 std::array<uint8_t, 32> calculatedHmac;
3512 std::unique_ptr<VerifiedInputEvent> result;
3513 switch (event.getType()) {
3514 case AINPUT_EVENT_TYPE_KEY: {
3515 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3516 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3517 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003518 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003519 break;
3520 }
3521 case AINPUT_EVENT_TYPE_MOTION: {
3522 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3523 VerifiedMotionEvent verifiedMotionEvent =
3524 verifiedMotionEventFromMotionEvent(motionEvent);
3525 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003526 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003527 break;
3528 }
3529 default: {
3530 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3531 return nullptr;
3532 }
3533 }
3534 if (calculatedHmac == INVALID_HMAC) {
3535 return nullptr;
3536 }
3537 if (calculatedHmac != event.getHmac()) {
3538 return nullptr;
3539 }
3540 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003541}
3542
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003544 return injectorUid == 0 ||
3545 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546}
3547
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003548void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549 InjectionState* injectionState = entry->injectionState;
3550 if (injectionState) {
3551#if DEBUG_INJECTION
3552 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003553 "injectorPid=%d, injectorUid=%d",
3554 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555#endif
3556
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003557 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 // Log the outcome since the injector did not wait for the injection result.
3559 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003560 case INPUT_EVENT_INJECTION_SUCCEEDED:
3561 ALOGV("Asynchronous input event injection succeeded.");
3562 break;
3563 case INPUT_EVENT_INJECTION_FAILED:
3564 ALOGW("Asynchronous input event injection failed.");
3565 break;
3566 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3567 ALOGW("Asynchronous input event injection permission denied.");
3568 break;
3569 case INPUT_EVENT_INJECTION_TIMED_OUT:
3570 ALOGW("Asynchronous input event injection timed out.");
3571 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 }
3573 }
3574
3575 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003576 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577 }
3578}
3579
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003580void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581 InjectionState* injectionState = entry->injectionState;
3582 if (injectionState) {
3583 injectionState->pendingForegroundDispatches += 1;
3584 }
3585}
3586
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003587void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 InjectionState* injectionState = entry->injectionState;
3589 if (injectionState) {
3590 injectionState->pendingForegroundDispatches -= 1;
3591
3592 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003593 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 }
3595 }
3596}
3597
Vishnu Nairad321cd2020-08-20 16:40:21 -07003598const std::vector<sp<InputWindowHandle>>& InputDispatcher::getWindowHandlesLocked(
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003599 int32_t displayId) const {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003600 static const std::vector<sp<InputWindowHandle>> EMPTY_WINDOW_HANDLES;
3601 auto it = mWindowHandlesByDisplay.find(displayId);
3602 return it != mWindowHandlesByDisplay.end() ? it->second : EMPTY_WINDOW_HANDLES;
Arthur Hungb92218b2018-08-14 12:00:21 +08003603}
3604
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003606 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003607 if (windowHandleToken == nullptr) {
3608 return nullptr;
3609 }
3610
Arthur Hungb92218b2018-08-14 12:00:21 +08003611 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003612 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003613 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003614 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003615 return windowHandle;
3616 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
3618 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003619 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620}
3621
Vishnu Nairad321cd2020-08-20 16:40:21 -07003622sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(const sp<IBinder>& windowHandleToken,
3623 int displayId) const {
3624 if (windowHandleToken == nullptr) {
3625 return nullptr;
3626 }
3627
3628 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3629 if (windowHandle->getToken() == windowHandleToken) {
3630 return windowHandle;
3631 }
3632 }
3633 return nullptr;
3634}
3635
3636sp<InputWindowHandle> InputDispatcher::getFocusedWindowHandleLocked(int displayId) const {
3637 sp<IBinder> focusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3638 return getWindowHandleLocked(focusedToken, displayId);
3639}
3640
Mady Mellor017bcd12020-06-23 19:12:00 +00003641bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3642 for (auto& it : mWindowHandlesByDisplay) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003643 const std::vector<sp<InputWindowHandle>>& windowHandles = it.second;
Mady Mellor017bcd12020-06-23 19:12:00 +00003644 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003645 if (handle->getId() == windowHandle->getId() &&
3646 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003647 if (windowHandle->getInfo()->displayId != it.first) {
3648 ALOGE("Found window %s in display %" PRId32
3649 ", but it should belong to display %" PRId32,
3650 windowHandle->getName().c_str(), it.first,
3651 windowHandle->getInfo()->displayId);
3652 }
3653 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655 }
3656 }
3657 return false;
3658}
3659
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003660bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3661 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3662 const bool noInputChannel =
3663 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3664 if (connection != nullptr && noInputChannel) {
3665 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3666 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3667 return false;
3668 }
3669
3670 if (connection == nullptr) {
3671 if (!noInputChannel) {
3672 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3673 }
3674 return false;
3675 }
3676 if (!connection->responsive) {
3677 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3678 return false;
3679 }
3680 return true;
3681}
3682
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003683std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3684 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003685 size_t count = mInputChannelsByToken.count(token);
3686 if (count == 0) {
3687 return nullptr;
3688 }
3689 return mInputChannelsByToken.at(token);
3690}
3691
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003692void InputDispatcher::updateWindowHandlesForDisplayLocked(
3693 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3694 if (inputWindowHandles.empty()) {
3695 // Remove all handles on a display if there are no windows left.
3696 mWindowHandlesByDisplay.erase(displayId);
3697 return;
3698 }
3699
3700 // Since we compare the pointer of input window handles across window updates, we need
3701 // to make sure the handle object for the same window stays unchanged across updates.
3702 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003703 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003704 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003705 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003706 }
3707
3708 std::vector<sp<InputWindowHandle>> newHandles;
3709 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3710 if (!handle->updateInfo()) {
3711 // handle no longer valid
3712 continue;
3713 }
3714
3715 const InputWindowInfo* info = handle->getInfo();
3716 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3717 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3718 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003719 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3720 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3721 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003722 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003723 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003724 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003725 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003726 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003727 }
3728
3729 if (info->displayId != displayId) {
3730 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3731 handle->getName().c_str(), displayId, info->displayId);
3732 continue;
3733 }
3734
Robert Carredd13602020-04-13 17:24:34 -07003735 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3736 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003737 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003738 oldHandle->updateFrom(handle);
3739 newHandles.push_back(oldHandle);
3740 } else {
3741 newHandles.push_back(handle);
3742 }
3743 }
3744
3745 // Insert or replace
3746 mWindowHandlesByDisplay[displayId] = newHandles;
3747}
3748
Arthur Hung72d8dc32020-03-28 00:48:39 +00003749void InputDispatcher::setInputWindows(
3750 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3751 { // acquire lock
3752 std::scoped_lock _l(mLock);
3753 for (auto const& i : handlesPerDisplay) {
3754 setInputWindowsLocked(i.second, i.first);
3755 }
3756 }
3757 // Wake up poll loop since it may need to make new input dispatching choices.
3758 mLooper->wake();
3759}
3760
Arthur Hungb92218b2018-08-14 12:00:21 +08003761/**
3762 * Called from InputManagerService, update window handle list by displayId that can receive input.
3763 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3764 * If set an empty list, remove all handles from the specific display.
3765 * For focused handle, check if need to change and send a cancel event to previous one.
3766 * For removed handle, check if need to send a cancel event if already in touch.
3767 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003768void InputDispatcher::setInputWindowsLocked(
3769 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003770 if (DEBUG_FOCUS) {
3771 std::string windowList;
3772 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3773 windowList += iwh->getName() + " ";
3774 }
3775 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3776 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003778 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3779 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3780 const bool noInputWindow =
3781 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3782 if (noInputWindow && window->getToken() != nullptr) {
3783 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3784 window->getName().c_str());
3785 window->releaseChannel();
3786 }
3787 }
3788
Arthur Hung72d8dc32020-03-28 00:48:39 +00003789 // Copy old handles for release if they are no longer present.
3790 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791
Arthur Hung72d8dc32020-03-28 00:48:39 +00003792 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003793
Vishnu Nairad321cd2020-08-20 16:40:21 -07003794 sp<IBinder> newFocusedToken = nullptr;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003795 bool foundHoveredWindow = false;
3796 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003797 // Set newFocusedToken to the top most focused window instead of the last one
3798 if (!newFocusedToken && windowHandle->getInfo()->focusable &&
Arthur Hung72d8dc32020-03-28 00:48:39 +00003799 windowHandle->getInfo()->visible) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003800 newFocusedToken = windowHandle->getToken();
Arthur Hung72d8dc32020-03-28 00:48:39 +00003801 }
3802 if (windowHandle == mLastHoverWindowHandle) {
3803 foundHoveredWindow = true;
3804 }
3805 }
3806
3807 if (!foundHoveredWindow) {
3808 mLastHoverWindowHandle = nullptr;
3809 }
3810
Vishnu Nairad321cd2020-08-20 16:40:21 -07003811 sp<IBinder> oldFocusedToken = getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3812 if (oldFocusedToken != newFocusedToken) {
3813 onFocusChangedLocked(oldFocusedToken, newFocusedToken, displayId, "setInputWindowsLocked");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003814 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003816 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3817 mTouchStatesByDisplay.find(displayId);
3818 if (stateIt != mTouchStatesByDisplay.end()) {
3819 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003820 for (size_t i = 0; i < state.windows.size();) {
3821 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003822 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003823 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003824 ALOGD("Touched window was removed: %s in display %" PRId32,
3825 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003826 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003827 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003828 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3829 if (touchedInputChannel != nullptr) {
3830 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3831 "touched window was removed");
3832 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003834 state.windows.erase(state.windows.begin() + i);
3835 } else {
3836 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837 }
3838 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003839 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003840
Arthur Hung72d8dc32020-03-28 00:48:39 +00003841 // Release information for windows that are no longer present.
3842 // This ensures that unused input channels are released promptly.
3843 // Otherwise, they might stick around until the window handle is destroyed
3844 // which might not happen until the next GC.
3845 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003846 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003847 if (DEBUG_FOCUS) {
3848 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003849 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003850 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003851 }
chaviw291d88a2019-02-14 10:33:58 -08003852 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853}
3854
3855void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003856 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003857 if (DEBUG_FOCUS) {
3858 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3859 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3860 }
Chris Yea209fde2020-07-22 13:54:51 -07003861 if (inputApplicationHandle != nullptr &&
3862 inputApplicationHandle->getApplicationToken() != nullptr) {
3863 // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003864 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865
Chris Yea209fde2020-07-22 13:54:51 -07003866 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003867 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003868
Chris Yea209fde2020-07-22 13:54:51 -07003869 // If oldFocusedApplicationHandle already exists
3870 if (oldFocusedApplicationHandle != nullptr) {
3871 // If a new focused application handle is different from the old one and
3872 // old focus application info is awaited focused application info.
3873 if (*oldFocusedApplicationHandle != *inputApplicationHandle &&
3874 mAwaitedFocusedApplication != nullptr &&
3875 *oldFocusedApplicationHandle == *mAwaitedFocusedApplication) {
3876 resetNoFocusedWindowTimeoutLocked();
3877 }
3878 // Erase the old application from container first
3879 mFocusedApplicationHandlesByDisplay.erase(displayId);
3880 // Should already get freed after removed from container but just double check.
3881 oldFocusedApplicationHandle.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003882 }
3883
Chris Yea209fde2020-07-22 13:54:51 -07003884 // Set the new application handle.
3885 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886 } // release lock
3887
3888 // Wake up poll loop since it may need to make new input dispatching choices.
3889 mLooper->wake();
3890}
3891
Tiger Huang721e26f2018-07-24 22:26:19 +08003892/**
3893 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3894 * the display not specified.
3895 *
3896 * We track any unreleased events for each window. If a window loses the ability to receive the
3897 * released event, we will send a cancel event to it. So when the focused display is changed, we
3898 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3899 * display. The display-specified events won't be affected.
3900 */
3901void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003902 if (DEBUG_FOCUS) {
3903 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3904 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003905 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003906 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003907
3908 if (mFocusedDisplayId != displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07003909 sp<IBinder> oldFocusedWindowToken =
3910 getValueByKey(mFocusedWindowTokenByDisplay, mFocusedDisplayId);
3911 if (oldFocusedWindowToken != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003912 std::shared_ptr<InputChannel> inputChannel =
Vishnu Nairad321cd2020-08-20 16:40:21 -07003913 getInputChannelLocked(oldFocusedWindowToken);
Tiger Huang721e26f2018-07-24 22:26:19 +08003914 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003915 CancelationOptions
3916 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3917 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003918 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003919 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3920 }
3921 }
3922 mFocusedDisplayId = displayId;
3923
Chris Ye3c2d6f52020-08-09 10:39:48 -07003924 // Find new focused window and validate
Vishnu Nairad321cd2020-08-20 16:40:21 -07003925 sp<IBinder> newFocusedWindowToken =
3926 getValueByKey(mFocusedWindowTokenByDisplay, displayId);
3927 notifyFocusChangedLocked(oldFocusedWindowToken, newFocusedWindowToken);
Robert Carrf759f162018-11-13 12:57:11 -08003928
Vishnu Nairad321cd2020-08-20 16:40:21 -07003929 if (newFocusedWindowToken == nullptr) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003930 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
Vishnu Nairad321cd2020-08-20 16:40:21 -07003931 if (!mFocusedWindowTokenByDisplay.empty()) {
3932 ALOGE("But another display has a focused window\n%s",
3933 dumpFocusedWindowsLocked().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003934 }
3935 }
3936 }
3937
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003938 if (DEBUG_FOCUS) {
3939 logDispatchStateLocked();
3940 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003941 } // release lock
3942
3943 // Wake up poll loop since it may need to make new input dispatching choices.
3944 mLooper->wake();
3945}
3946
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003948 if (DEBUG_FOCUS) {
3949 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951
3952 bool changed;
3953 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003954 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955
3956 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3957 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003958 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959 }
3960
3961 if (mDispatchEnabled && !enabled) {
3962 resetAndDropEverythingLocked("dispatcher is being disabled");
3963 }
3964
3965 mDispatchEnabled = enabled;
3966 mDispatchFrozen = frozen;
3967 changed = true;
3968 } else {
3969 changed = false;
3970 }
3971
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003972 if (DEBUG_FOCUS) {
3973 logDispatchStateLocked();
3974 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 } // release lock
3976
3977 if (changed) {
3978 // Wake up poll loop since it may need to make new input dispatching choices.
3979 mLooper->wake();
3980 }
3981}
3982
3983void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003984 if (DEBUG_FOCUS) {
3985 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3986 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987
3988 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003989 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990
3991 if (mInputFilterEnabled == enabled) {
3992 return;
3993 }
3994
3995 mInputFilterEnabled = enabled;
3996 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3997 } // release lock
3998
3999 // Wake up poll loop since there might be work to do to drop everything.
4000 mLooper->wake();
4001}
4002
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004003void InputDispatcher::setInTouchMode(bool inTouchMode) {
4004 std::scoped_lock lock(mLock);
4005 mInTouchMode = inTouchMode;
4006}
4007
chaviwfbe5d9c2018-12-26 12:23:37 -08004008bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4009 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004010 if (DEBUG_FOCUS) {
4011 ALOGD("Trivial transfer to same window.");
4012 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004013 return true;
4014 }
4015
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004017 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018
chaviwfbe5d9c2018-12-26 12:23:37 -08004019 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4020 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004021 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004022 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023 return false;
4024 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004025 if (DEBUG_FOCUS) {
4026 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4027 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004030 if (DEBUG_FOCUS) {
4031 ALOGD("Cannot transfer focus because windows are on different displays.");
4032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033 return false;
4034 }
4035
4036 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004037 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4038 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004039 for (size_t i = 0; i < state.windows.size(); i++) {
4040 const TouchedWindow& touchedWindow = state.windows[i];
4041 if (touchedWindow.windowHandle == fromWindowHandle) {
4042 int32_t oldTargetFlags = touchedWindow.targetFlags;
4043 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004045 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004047 int32_t newTargetFlags = oldTargetFlags &
4048 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4049 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004050 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051
Jeff Brownf086ddb2014-02-11 14:28:48 -08004052 found = true;
4053 goto Found;
4054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 }
4056 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004057 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004058
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004059 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004060 if (DEBUG_FOCUS) {
4061 ALOGD("Focus transfer failed because from window did not have focus.");
4062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063 return false;
4064 }
4065
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004066 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4067 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004068 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004069 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004070 CancelationOptions
4071 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4072 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004074 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 }
4076
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004077 if (DEBUG_FOCUS) {
4078 logDispatchStateLocked();
4079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080 } // release lock
4081
4082 // Wake up poll loop since it may need to make new input dispatching choices.
4083 mLooper->wake();
4084 return true;
4085}
4086
4087void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004088 if (DEBUG_FOCUS) {
4089 ALOGD("Resetting and dropping all events (%s).", reason);
4090 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091
4092 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4093 synthesizeCancelationEventsForAllConnectionsLocked(options);
4094
4095 resetKeyRepeatLocked();
4096 releasePendingEventLocked();
4097 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004098 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004100 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004101 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004103 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104}
4105
4106void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004107 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 dumpDispatchStateLocked(dump);
4109
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004110 std::istringstream stream(dump);
4111 std::string line;
4112
4113 while (std::getline(stream, line, '\n')) {
4114 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115 }
4116}
4117
Vishnu Nairad321cd2020-08-20 16:40:21 -07004118std::string InputDispatcher::dumpFocusedWindowsLocked() {
4119 if (mFocusedWindowTokenByDisplay.empty()) {
4120 return INDENT "FocusedWindows: <none>\n";
4121 }
4122
4123 std::string dump;
4124 dump += INDENT "FocusedWindows:\n";
4125 for (auto& it : mFocusedWindowTokenByDisplay) {
4126 const int32_t displayId = it.first;
4127 const sp<InputWindowHandle> windowHandle = getFocusedWindowHandleLocked(displayId);
4128 if (windowHandle) {
4129 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4130 windowHandle->getName().c_str());
4131 } else {
4132 dump += StringPrintf(INDENT2 "displayId=%" PRId32
4133 " has focused token without a window'\n",
4134 displayId);
4135 }
4136 }
4137 return dump;
4138}
4139
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004140void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004141 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4142 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4143 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004144 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145
Tiger Huang721e26f2018-07-24 22:26:19 +08004146 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4147 dump += StringPrintf(INDENT "FocusedApplications:\n");
4148 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4149 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004150 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004151 const std::chrono::duration timeout =
4152 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004153 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004154 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004155 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004158 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004160
Vishnu Nairad321cd2020-08-20 16:40:21 -07004161 dump += dumpFocusedWindowsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004163 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004164 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004165 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4166 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004167 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004168 state.displayId, toString(state.down), toString(state.split),
4169 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004170 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004171 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004172 for (size_t i = 0; i < state.windows.size(); i++) {
4173 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004174 dump += StringPrintf(INDENT4
4175 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4176 i, touchedWindow.windowHandle->getName().c_str(),
4177 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004178 }
4179 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004180 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004181 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004182 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004183 dump += INDENT3 "Portal windows:\n";
4184 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004185 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004186 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4187 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004188 }
4189 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 }
4191 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 }
4194
Arthur Hungb92218b2018-08-14 12:00:21 +08004195 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004197 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004198 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004199 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004200 dump += INDENT2 "Windows:\n";
4201 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004202 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004203 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204
Arthur Hungb92218b2018-08-14 12:00:21 +08004205 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004206 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4207 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004208 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004209 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004210 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004211 i, windowInfo->name.c_str(), windowInfo->displayId,
4212 windowInfo->portalToDisplayId,
4213 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004214 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004215 toString(windowInfo->hasWallpaper),
4216 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004217 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004218 static_cast<int32_t>(windowInfo->type),
4219 windowInfo->frameLeft, windowInfo->frameTop,
4220 windowInfo->frameRight, windowInfo->frameBottom,
chaviw1ff3d1e2020-07-01 15:53:47 -07004221 windowInfo->globalScaleFactor);
Arthur Hungb92218b2018-08-14 12:00:21 +08004222 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004223 dump += StringPrintf(", inputFeatures=%s",
4224 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004225 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4226 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004227 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004228 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004229 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004230 }
4231 } else {
4232 dump += INDENT2 "Windows: <none>\n";
4233 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 }
4235 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004236 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 }
4238
Michael Wright3dd60e22019-03-27 22:06:44 +00004239 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004240 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004241 const std::vector<Monitor>& monitors = it.second;
4242 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4243 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004244 }
4245 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004246 const std::vector<Monitor>& monitors = it.second;
4247 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4248 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004251 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 }
4253
4254 nsecs_t currentTime = now();
4255
4256 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004257 if (!mRecentQueue.empty()) {
4258 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4259 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004260 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004262 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 }
4264 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004265 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 }
4267
4268 // Dump event currently being dispatched.
4269 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004270 dump += INDENT "PendingEvent:\n";
4271 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004273 dump += StringPrintf(", age=%" PRId64 "ms\n",
4274 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004276 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 }
4278
4279 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004280 if (!mInboundQueue.empty()) {
4281 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4282 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004283 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004285 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 }
4287 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004288 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 }
4290
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004291 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004292 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004293 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4294 const KeyReplacement& replacement = pair.first;
4295 int32_t newKeyCode = pair.second;
4296 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004297 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004298 }
4299 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004300 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004301 }
4302
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004303 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004304 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004305 for (const auto& pair : mConnectionsByFd) {
4306 const sp<Connection>& connection = pair.second;
4307 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004308 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004309 pair.first, connection->getInputChannelName().c_str(),
4310 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004311 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004313 if (!connection->outboundQueue.empty()) {
4314 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4315 connection->outboundQueue.size());
4316 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 dump.append(INDENT4);
4318 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004319 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4320 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004321 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004322 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 }
4324 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004325 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 }
4327
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004328 if (!connection->waitQueue.empty()) {
4329 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4330 connection->waitQueue.size());
4331 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004332 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004334 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004335 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004336 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004337 ns2ms(currentTime - entry->eventEntry->eventTime),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004338 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 }
4340 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004341 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342 }
4343 }
4344 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004345 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346 }
4347
4348 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004349 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4350 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004352 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353 }
4354
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004355 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004356 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4357 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4358 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359}
4360
Michael Wright3dd60e22019-03-27 22:06:44 +00004361void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4362 const size_t numMonitors = monitors.size();
4363 for (size_t i = 0; i < numMonitors; i++) {
4364 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004365 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004366 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4367 dump += "\n";
4368 }
4369}
4370
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004371status_t InputDispatcher::registerInputChannel(const std::shared_ptr<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004373 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374#endif
4375
4376 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004377 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004378 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004379 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004381 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 return BAD_VALUE;
4383 }
4384
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004385 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386
4387 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004388 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004389 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4392 } // release lock
4393
4394 // Wake the looper because some connections have changed.
4395 mLooper->wake();
4396 return OK;
4397}
4398
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004399status_t InputDispatcher::registerInputMonitor(const std::shared_ptr<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004400 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004401 { // acquire lock
4402 std::scoped_lock _l(mLock);
4403
4404 if (displayId < 0) {
4405 ALOGW("Attempted to register input monitor without a specified display.");
4406 return BAD_VALUE;
4407 }
4408
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004409 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004410 ALOGW("Attempted to register input monitor without an identifying token.");
4411 return BAD_VALUE;
4412 }
4413
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004414 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004415
4416 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004417 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004418 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004419
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004420 auto& monitorsByDisplay =
4421 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004422 monitorsByDisplay[displayId].emplace_back(inputChannel);
4423
4424 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004425 }
4426 // Wake the looper because some connections have changed.
4427 mLooper->wake();
4428 return OK;
4429}
4430
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004431status_t InputDispatcher::unregisterInputChannel(const sp<IBinder>& connectionToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004433 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004435 status_t status = unregisterInputChannelLocked(connectionToken, false /*notify*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 if (status) {
4437 return status;
4438 }
4439 } // release lock
4440
4441 // Wake the poll loop because removing the connection may have changed the current
4442 // synchronization state.
4443 mLooper->wake();
4444 return OK;
4445}
4446
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004447status_t InputDispatcher::unregisterInputChannelLocked(const sp<IBinder>& connectionToken,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004448 bool notify) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004449 sp<Connection> connection = getConnectionLocked(connectionToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004450 if (connection == nullptr) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004451 ALOGW("Attempted to unregister already unregistered input channel");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 return BAD_VALUE;
4453 }
4454
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004455 removeConnectionLocked(connection);
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004456 mInputChannelsByToken.erase(connectionToken);
Robert Carr5c8a0262018-10-03 16:30:44 -07004457
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458 if (connection->monitor) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004459 removeMonitorChannelLocked(connectionToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460 }
4461
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004462 mLooper->removeFd(connection->inputChannel->getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463
4464 nsecs_t currentTime = now();
4465 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4466
4467 connection->status = Connection::STATUS_ZOMBIE;
4468 return OK;
4469}
4470
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004471void InputDispatcher::removeMonitorChannelLocked(const sp<IBinder>& connectionToken) {
4472 removeMonitorChannelLocked(connectionToken, mGlobalMonitorsByDisplay);
4473 removeMonitorChannelLocked(connectionToken, mGestureMonitorsByDisplay);
Michael Wright3dd60e22019-03-27 22:06:44 +00004474}
4475
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004476void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004477 const sp<IBinder>& connectionToken,
Michael Wright3dd60e22019-03-27 22:06:44 +00004478 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004479 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004480 std::vector<Monitor>& monitors = it->second;
4481 const size_t numMonitors = monitors.size();
4482 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouadefc3e2020-09-02 22:28:29 -05004483 if (monitors[i].inputChannel->getConnectionToken() == connectionToken) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004484 monitors.erase(monitors.begin() + i);
4485 break;
4486 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004487 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004488 if (monitors.empty()) {
4489 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004490 } else {
4491 ++it;
4492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004493 }
4494}
4495
Michael Wright3dd60e22019-03-27 22:06:44 +00004496status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4497 { // acquire lock
4498 std::scoped_lock _l(mLock);
4499 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4500
4501 if (!foundDisplayId) {
4502 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4503 return BAD_VALUE;
4504 }
4505 int32_t displayId = foundDisplayId.value();
4506
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004507 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4508 mTouchStatesByDisplay.find(displayId);
4509 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004510 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4511 return BAD_VALUE;
4512 }
4513
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004514 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004515 std::optional<int32_t> foundDeviceId;
4516 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004517 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004518 foundDeviceId = state.deviceId;
4519 }
4520 }
4521 if (!foundDeviceId || !state.down) {
4522 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004523 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004524 return BAD_VALUE;
4525 }
4526 int32_t deviceId = foundDeviceId.value();
4527
4528 // Send cancel events to all the input channels we're stealing from.
4529 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004530 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004531 options.deviceId = deviceId;
4532 options.displayId = displayId;
4533 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004534 std::shared_ptr<InputChannel> channel =
4535 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004536 if (channel != nullptr) {
4537 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4538 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004539 }
4540 // Then clear the current touch state so we stop dispatching to them as well.
4541 state.filterNonMonitors();
4542 }
4543 return OK;
4544}
4545
Michael Wright3dd60e22019-03-27 22:06:44 +00004546std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4547 const sp<IBinder>& token) {
4548 for (const auto& it : mGestureMonitorsByDisplay) {
4549 const std::vector<Monitor>& monitors = it.second;
4550 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004551 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004552 return it.first;
4553 }
4554 }
4555 }
4556 return std::nullopt;
4557}
4558
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004559sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004560 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004561 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004562 }
4563
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004564 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004565 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004566 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004567 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004568 }
4569 }
Robert Carr4e670e52018-08-15 13:26:12 -07004570
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004571 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572}
4573
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004574void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004575 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004576 removeByValue(mConnectionsByFd, connection);
4577}
4578
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004579void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4580 const sp<Connection>& connection, uint32_t seq,
4581 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004582 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4583 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584 commandEntry->connection = connection;
4585 commandEntry->eventTime = currentTime;
4586 commandEntry->seq = seq;
4587 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004588 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589}
4590
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004591void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4592 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004594 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004596 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4597 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004599 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600}
4601
Vishnu Nairad321cd2020-08-20 16:40:21 -07004602void InputDispatcher::notifyFocusChangedLocked(const sp<IBinder>& oldToken,
4603 const sp<IBinder>& newToken) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004604 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4605 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004606 commandEntry->oldToken = oldToken;
4607 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004608 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004609}
4610
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004611void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4612 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4613 // is already healthy again. Don't raise ANR in this situation
4614 if (connection->waitQueue.empty()) {
4615 ALOGI("Not raising ANR because the connection %s has recovered",
4616 connection->inputChannel->getName().c_str());
4617 return;
4618 }
4619 /**
4620 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4621 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4622 * has changed. This could cause newer entries to time out before the already dispatched
4623 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4624 * processes the events linearly. So providing information about the oldest entry seems to be
4625 * most useful.
4626 */
4627 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4628 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4629 std::string reason =
4630 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4631 connection->inputChannel->getName().c_str(),
4632 ns2ms(currentWait),
4633 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004635 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4636 reason);
4637
4638 std::unique_ptr<CommandEntry> commandEntry =
4639 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4640 commandEntry->inputApplicationHandle = nullptr;
4641 commandEntry->inputChannel = connection->inputChannel;
4642 commandEntry->reason = std::move(reason);
4643 postCommandLocked(std::move(commandEntry));
4644}
4645
Chris Yea209fde2020-07-22 13:54:51 -07004646void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004647 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4648 application->getName().c_str());
4649
4650 updateLastAnrStateLocked(application, reason);
4651
4652 std::unique_ptr<CommandEntry> commandEntry =
4653 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4654 commandEntry->inputApplicationHandle = application;
4655 commandEntry->inputChannel = nullptr;
4656 commandEntry->reason = std::move(reason);
4657 postCommandLocked(std::move(commandEntry));
4658}
4659
4660void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4661 const std::string& reason) {
4662 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4663 updateLastAnrStateLocked(windowLabel, reason);
4664}
4665
Chris Yea209fde2020-07-22 13:54:51 -07004666void InputDispatcher::updateLastAnrStateLocked(
4667 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004668 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4669 updateLastAnrStateLocked(windowLabel, reason);
4670}
4671
4672void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4673 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004675 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676 struct tm tm;
4677 localtime_r(&t, &tm);
4678 char timestr[64];
4679 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004680 mLastAnrState.clear();
4681 mLastAnrState += INDENT "ANR:\n";
4682 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004683 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4684 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004685 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686}
4687
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004688void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 mLock.unlock();
4690
4691 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4692
4693 mLock.lock();
4694}
4695
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004696void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697 sp<Connection> connection = commandEntry->connection;
4698
4699 if (connection->status != Connection::STATUS_ZOMBIE) {
4700 mLock.unlock();
4701
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004702 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703
4704 mLock.lock();
4705 }
4706}
4707
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004708void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004709 sp<IBinder> oldToken = commandEntry->oldToken;
4710 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004711 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004712 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004713 mLock.lock();
4714}
4715
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004716void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004717 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004718 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 mLock.unlock();
4720
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004721 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004722 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723
4724 mLock.lock();
4725
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004726 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004727 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4728 } else {
4729 // stop waking up for events in this connection, it is already not responding
4730 sp<Connection> connection = getConnectionLocked(token);
4731 if (connection == nullptr) {
4732 return;
4733 }
4734 cancelEventsForAnrLocked(connection);
4735 }
4736}
4737
Chris Yea209fde2020-07-22 13:54:51 -07004738void InputDispatcher::extendAnrTimeoutsLocked(
4739 const std::shared_ptr<InputApplicationHandle>& application,
4740 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004741 sp<Connection> connection = getConnectionLocked(connectionToken);
4742 if (connection == nullptr) {
4743 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4744 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004745 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004746 mAwaitedFocusedApplication = application;
4747 } else {
4748 // It's also possible that the connection already disappeared. No action necessary.
4749 }
4750 return;
4751 }
4752
4753 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004754 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004755
4756 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004757 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004758 for (DispatchEntry* entry : connection->waitQueue) {
4759 if (newTimeout >= entry->timeoutTime) {
4760 // Already removed old entries when connection was marked unresponsive
4761 entry->timeoutTime = newTimeout;
4762 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4763 }
4764 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765}
4766
4767void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4768 CommandEntry* commandEntry) {
4769 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004770 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771
4772 mLock.unlock();
4773
Michael Wright2b3c3302018-03-02 17:19:13 +00004774 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004775 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004776 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004777 : nullptr;
4778 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004779 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4780 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004781 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783
4784 mLock.lock();
4785
4786 if (delay < 0) {
4787 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4788 } else if (!delay) {
4789 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4790 } else {
4791 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4792 entry->interceptKeyWakeupTime = now() + delay;
4793 }
4794 entry->release();
4795}
4796
chaviwfd6d3512019-03-25 13:23:49 -07004797void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4798 mLock.unlock();
4799 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4800 mLock.lock();
4801}
4802
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004803/**
4804 * Connection is responsive if it has no events in the waitQueue that are older than the
4805 * current time.
4806 */
4807static bool isConnectionResponsive(const Connection& connection) {
4808 const nsecs_t currentTime = now();
4809 for (const DispatchEntry* entry : connection.waitQueue) {
4810 if (entry->timeoutTime < currentTime) {
4811 return false;
4812 }
4813 }
4814 return true;
4815}
4816
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004817void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004819 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004821 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822
4823 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004824 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004825 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004826 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004828 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004829 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004830 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004831 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4832 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004833 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004834 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004835
4836 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004837 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004838 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4839 restartEvent =
4840 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004841 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004842 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4843 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4844 handled);
4845 } else {
4846 restartEvent = false;
4847 }
4848
4849 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004850 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004851 // contents of the wait queue to have been drained, so we need to double-check
4852 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004853 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4854 if (dispatchEntryIt != connection->waitQueue.end()) {
4855 dispatchEntry = *dispatchEntryIt;
4856 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004857 mAnrTracker.erase(dispatchEntry->timeoutTime,
4858 connection->inputChannel->getConnectionToken());
4859 if (!connection->responsive) {
4860 connection->responsive = isConnectionResponsive(*connection);
4861 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004862 traceWaitQueueLength(connection);
4863 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004864 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004865 traceOutboundQueueLength(connection);
4866 } else {
4867 releaseDispatchEntry(dispatchEntry);
4868 }
4869 }
4870
4871 // Start the next dispatch cycle for this connection.
4872 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873}
4874
4875bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004876 DispatchEntry* dispatchEntry,
4877 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004878 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004879 if (!handled) {
4880 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004881 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004882 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004883 return false;
4884 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004886 // Get the fallback key state.
4887 // Clear it out after dispatching the UP.
4888 int32_t originalKeyCode = keyEntry->keyCode;
4889 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4890 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4891 connection->inputState.removeFallbackKey(originalKeyCode);
4892 }
4893
4894 if (handled || !dispatchEntry->hasForegroundTarget()) {
4895 // If the application handles the original key for which we previously
4896 // generated a fallback or if the window is not a foreground window,
4897 // then cancel the associated fallback key, if any.
4898 if (fallbackKeyCode != -1) {
4899 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004901 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004902 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4903 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4904 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004906 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004907 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908
4909 mLock.unlock();
4910
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004911 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004912 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913
4914 mLock.lock();
4915
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004916 // Cancel the fallback key.
4917 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004919 "application handled the original non-fallback key "
4920 "or is no longer a foreground target, "
4921 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 options.keyCode = fallbackKeyCode;
4923 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004925 connection->inputState.removeFallbackKey(originalKeyCode);
4926 }
4927 } else {
4928 // If the application did not handle a non-fallback key, first check
4929 // that we are in a good state to perform unhandled key event processing
4930 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004931 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004932 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004934 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004935 "since this is not an initial down. "
4936 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4937 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004939 return false;
4940 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004942 // Dispatch the unhandled key to the policy.
4943#if DEBUG_OUTBOUND_EVENT_DETAILS
4944 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004945 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4946 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004947#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004948 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004949
4950 mLock.unlock();
4951
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004952 bool fallback =
4953 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4954 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004955
4956 mLock.lock();
4957
4958 if (connection->status != Connection::STATUS_NORMAL) {
4959 connection->inputState.removeFallbackKey(originalKeyCode);
4960 return false;
4961 }
4962
4963 // Latch the fallback keycode for this key on an initial down.
4964 // The fallback keycode cannot change at any other point in the lifecycle.
4965 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004966 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004967 fallbackKeyCode = event.getKeyCode();
4968 } else {
4969 fallbackKeyCode = AKEYCODE_UNKNOWN;
4970 }
4971 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4972 }
4973
4974 ALOG_ASSERT(fallbackKeyCode != -1);
4975
4976 // Cancel the fallback key if the policy decides not to send it anymore.
4977 // We will continue to dispatch the key to the policy but we will no
4978 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004979 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4980 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004981#if DEBUG_OUTBOUND_EVENT_DETAILS
4982 if (fallback) {
4983 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004984 "as a fallback for %d, but on the DOWN it had requested "
4985 "to send %d instead. Fallback canceled.",
4986 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004987 } else {
4988 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004989 "but on the DOWN it had requested to send %d. "
4990 "Fallback canceled.",
4991 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004992 }
4993#endif
4994
4995 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4996 "canceling fallback, policy no longer desires it");
4997 options.keyCode = fallbackKeyCode;
4998 synthesizeCancelationEventsForConnectionLocked(connection, options);
4999
5000 fallback = false;
5001 fallbackKeyCode = AKEYCODE_UNKNOWN;
5002 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005003 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005004 }
5005 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006
5007#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005008 {
5009 std::string msg;
5010 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5011 connection->inputState.getFallbackKeys();
5012 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005013 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005015 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005016 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005017 }
5018#endif
5019
5020 if (fallback) {
5021 // Restart the dispatch cycle using the fallback key.
5022 keyEntry->eventTime = event.getEventTime();
5023 keyEntry->deviceId = event.getDeviceId();
5024 keyEntry->source = event.getSource();
5025 keyEntry->displayId = event.getDisplayId();
5026 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5027 keyEntry->keyCode = fallbackKeyCode;
5028 keyEntry->scanCode = event.getScanCode();
5029 keyEntry->metaState = event.getMetaState();
5030 keyEntry->repeatCount = event.getRepeatCount();
5031 keyEntry->downTime = event.getDownTime();
5032 keyEntry->syntheticRepeat = false;
5033
5034#if DEBUG_OUTBOUND_EVENT_DETAILS
5035 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005036 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5037 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005038#endif
5039 return true; // restart the event
5040 } else {
5041#if DEBUG_OUTBOUND_EVENT_DETAILS
5042 ALOGD("Unhandled key event: No fallback key.");
5043#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005044
5045 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005046 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 }
5048 }
5049 return false;
5050}
5051
5052bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005053 DispatchEntry* dispatchEntry,
5054 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 return false;
5056}
5057
5058void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5059 mLock.unlock();
5060
5061 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5062
5063 mLock.lock();
5064}
5065
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005066KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5067 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005068 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005069 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5070 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005071 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005072}
5073
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005074void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5075 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005076 // TODO Write some statistics about how long we spend waiting.
5077}
5078
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005079/**
5080 * Report the touch event latency to the statsd server.
5081 * Input events are reported for statistics if:
5082 * - This is a touchscreen event
5083 * - InputFilter is not enabled
5084 * - Event is not injected or synthesized
5085 *
5086 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5087 * from getting aggregated with the "old" data.
5088 */
5089void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5090 REQUIRES(mLock) {
5091 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5092 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5093 if (!reportForStatistics) {
5094 return;
5095 }
5096
5097 if (mTouchStatistics.shouldReport()) {
5098 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5099 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5100 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5101 mTouchStatistics.reset();
5102 }
5103 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5104 mTouchStatistics.addValue(latencyMicros);
5105}
5106
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107void InputDispatcher::traceInboundQueueLengthLocked() {
5108 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005109 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 }
5111}
5112
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005113void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005114 if (ATRACE_ENABLED()) {
5115 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005116 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005117 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118 }
5119}
5120
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005121void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122 if (ATRACE_ENABLED()) {
5123 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005124 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005125 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126 }
5127}
5128
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005129void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005130 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005131
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005132 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005133 dumpDispatchStateLocked(dump);
5134
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005135 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005136 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005137 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138 }
5139}
5140
5141void InputDispatcher::monitor() {
5142 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005143 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005145 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146}
5147
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005148/**
5149 * Wake up the dispatcher and wait until it processes all events and commands.
5150 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5151 * this method can be safely called from any thread, as long as you've ensured that
5152 * the work you are interested in completing has already been queued.
5153 */
5154bool InputDispatcher::waitForIdle() {
5155 /**
5156 * Timeout should represent the longest possible time that a device might spend processing
5157 * events and commands.
5158 */
5159 constexpr std::chrono::duration TIMEOUT = 100ms;
5160 std::unique_lock lock(mLock);
5161 mLooper->wake();
5162 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5163 return result == std::cv_status::no_timeout;
5164}
5165
Vishnu Naire798b472020-07-23 13:52:21 -07005166/**
5167 * Sets focus to the window identified by the token. This must be called
5168 * after updating any input window handles.
5169 *
5170 * Params:
5171 * request.token - input channel token used to identify the window that should gain focus.
5172 * request.focusedToken - the token that the caller expects currently to be focused. If the
5173 * specified token does not match the currently focused window, this request will be dropped.
5174 * If the specified focused token matches the currently focused window, the call will succeed.
5175 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5176 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5177 * when requesting the focus change. This determines which request gets
5178 * precedence if there is a focus change request from another source such as pointer down.
5179 */
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005180void InputDispatcher::setFocusedWindow(const FocusRequest& request) {}
5181
Vishnu Nairad321cd2020-08-20 16:40:21 -07005182void InputDispatcher::onFocusChangedLocked(const sp<IBinder>& oldFocusedToken,
5183 const sp<IBinder>& newFocusedToken, int32_t displayId,
5184 std::string_view reason) {
5185 if (oldFocusedToken) {
5186 std::shared_ptr<InputChannel> focusedInputChannel = getInputChannelLocked(oldFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005187 if (focusedInputChannel) {
5188 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5189 "focus left window");
5190 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Vishnu Nairad321cd2020-08-20 16:40:21 -07005191 enqueueFocusEventLocked(oldFocusedToken, false /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005192 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005193 mFocusedWindowTokenByDisplay.erase(displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005194 }
Vishnu Nairad321cd2020-08-20 16:40:21 -07005195 if (newFocusedToken) {
5196 mFocusedWindowTokenByDisplay[displayId] = newFocusedToken;
5197 enqueueFocusEventLocked(newFocusedToken, true /*hasFocus*/, reason);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005198 }
5199
5200 if (mFocusedDisplayId == displayId) {
Vishnu Nairad321cd2020-08-20 16:40:21 -07005201 notifyFocusChangedLocked(oldFocusedToken, newFocusedToken);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005202 }
5203}
Garfield Tane84e6f92019-08-29 17:28:41 -07005204} // namespace android::inputdispatcher