blob: 0980107b4291904ff10843bd420d0b9b6caf2bd6 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
John Recke0710582019-09-26 13:46:12 -070020#define LOG_NDEBUG 1
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
Siarhei Vishniakou86587282019-09-09 18:20:15 +010038static constexpr bool DEBUG_FOCUS = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -080039
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wright2b3c3302018-03-02 17:19:13 +000048#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080049#include <android-base/stringprintf.h>
Siarhei Vishniakou70622952020-07-30 11:17:23 -050050#include <android/os/IInputConstants.h>
Robert Carr4e670e52018-08-15 13:26:12 -070051#include <binder/Binder.h>
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -080052#include <input/InputDevice.h>
Michael Wright44753b12020-07-08 13:48:11 +010053#include <input/InputWindow.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070054#include <log/log.h>
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +000055#include <log/log_event_list.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070056#include <powermanager/PowerManager.h>
Michael Wright44753b12020-07-08 13:48:11 +010057#include <statslog.h>
58#include <unistd.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070059#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
Michael Wright44753b12020-07-08 13:48:11 +010061#include <cerrno>
62#include <cinttypes>
63#include <climits>
64#include <cstddef>
65#include <ctime>
66#include <queue>
67#include <sstream>
68
69#include "Connection.h"
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071#define INDENT " "
72#define INDENT2 " "
73#define INDENT3 " "
74#define INDENT4 " "
75
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080076using android::base::StringPrintf;
77
Garfield Tane84e6f92019-08-29 17:28:41 -070078namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Default input dispatching timeout if there is no focused application or paused window
81// from which to determine an appropriate dispatching timeout.
Siarhei Vishniakou70622952020-07-30 11:17:23 -050082constexpr std::chrono::duration DEFAULT_INPUT_DISPATCHING_TIMEOUT =
83 std::chrono::milliseconds(android::os::IInputConstants::DEFAULT_DISPATCHING_TIMEOUT_MILLIS);
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow for all pending events to be processed when an app switch
86// key is on the way. This is used to preempt input dispatch and drop input events
87// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Amount of time to allow for an event to be dispatched (measured since its eventTime)
91// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Michael Wrightd02c5b62014-02-10 15:10:22 -080094// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000095constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
96
97// Log a warning when an interception call takes longer than this to process.
98constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700100// Additional key latency in case a connection is still processing some motion events.
101// This will help with the case when a user touched a button that opens a new window,
102// and gives us the chance to dispatch the key to this new window.
103constexpr std::chrono::nanoseconds KEY_WAITING_FOR_EVENTS_TIMEOUT = 500ms;
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000106constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
107
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +0000108// Event log tags. See EventLogTags.logtags for reference
109constexpr int LOGTAG_INPUT_INTERACTION = 62000;
110constexpr int LOGTAG_INPUT_FOCUS = 62001;
111
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112static inline nsecs_t now() {
113 return systemTime(SYSTEM_TIME_MONOTONIC);
114}
115
116static inline const char* toString(bool value) {
117 return value ? "true" : "false";
118}
119
120static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700121 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
122 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123}
124
125static bool isValidKeyAction(int32_t action) {
126 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700127 case AKEY_EVENT_ACTION_DOWN:
128 case AKEY_EVENT_ACTION_UP:
129 return true;
130 default:
131 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 }
133}
134
135static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700136 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137 ALOGE("Key event has invalid action code 0x%x", action);
138 return false;
139 }
140 return true;
141}
142
Michael Wright7b159c92015-05-14 14:48:03 +0100143static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700145 case AMOTION_EVENT_ACTION_DOWN:
146 case AMOTION_EVENT_ACTION_UP:
147 case AMOTION_EVENT_ACTION_CANCEL:
148 case AMOTION_EVENT_ACTION_MOVE:
149 case AMOTION_EVENT_ACTION_OUTSIDE:
150 case AMOTION_EVENT_ACTION_HOVER_ENTER:
151 case AMOTION_EVENT_ACTION_HOVER_MOVE:
152 case AMOTION_EVENT_ACTION_HOVER_EXIT:
153 case AMOTION_EVENT_ACTION_SCROLL:
154 return true;
155 case AMOTION_EVENT_ACTION_POINTER_DOWN:
156 case AMOTION_EVENT_ACTION_POINTER_UP: {
157 int32_t index = getMotionEventActionPointerIndex(action);
158 return index >= 0 && index < pointerCount;
159 }
160 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
161 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
162 return actionButton != 0;
163 default:
164 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800165 }
166}
167
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500168static int64_t millis(std::chrono::nanoseconds t) {
169 return std::chrono::duration_cast<std::chrono::milliseconds>(t).count();
170}
171
Michael Wright7b159c92015-05-14 14:48:03 +0100172static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700173 const PointerProperties* pointerProperties) {
174 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 ALOGE("Motion event has invalid action code 0x%x", action);
176 return false;
177 }
178 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000179 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700180 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 return false;
182 }
183 BitSet32 pointerIdBits;
184 for (size_t i = 0; i < pointerCount; i++) {
185 int32_t id = pointerProperties[i].id;
186 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700187 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
188 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 return false;
190 }
191 if (pointerIdBits.hasBit(id)) {
192 ALOGE("Motion event has duplicate pointer id %d", id);
193 return false;
194 }
195 pointerIdBits.markBit(id);
196 }
197 return true;
198}
199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800200static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800202 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 return;
204 }
205
206 bool first = true;
207 Region::const_iterator cur = region.begin();
208 Region::const_iterator const tail = region.end();
209 while (cur != tail) {
210 if (first) {
211 first = false;
212 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800213 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800215 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 cur++;
217 }
218}
219
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700220/**
221 * Find the entry in std::unordered_map by key, and return it.
222 * If the entry is not found, return a default constructed entry.
223 *
224 * Useful when the entries are vectors, since an empty vector will be returned
225 * if the entry is not found.
226 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
227 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700228template <typename K, typename V>
229static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700230 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700231 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800232}
233
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700234/**
235 * Find the entry in std::unordered_map by value, and remove it.
236 * If more than one entry has the same value, then all matching
237 * key-value pairs will be removed.
238 *
239 * Return true if at least one value has been removed.
240 */
241template <typename K, typename V>
242static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
243 bool removed = false;
244 for (auto it = map.begin(); it != map.end();) {
245 if (it->second == value) {
246 it = map.erase(it);
247 removed = true;
248 } else {
249 it++;
250 }
251 }
252 return removed;
253}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254
chaviwaf87b3e2019-10-01 16:59:28 -0700255static bool haveSameToken(const sp<InputWindowHandle>& first, const sp<InputWindowHandle>& second) {
256 if (first == second) {
257 return true;
258 }
259
260 if (first == nullptr || second == nullptr) {
261 return false;
262 }
263
264 return first->getToken() == second->getToken();
265}
266
Siarhei Vishniakouadfd4fa2019-12-20 11:02:58 -0800267static bool isStaleEvent(nsecs_t currentTime, const EventEntry& entry) {
268 return currentTime - entry.eventTime >= STALE_EVENT_TIMEOUT;
269}
270
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000271static std::unique_ptr<DispatchEntry> createDispatchEntry(const InputTarget& inputTarget,
272 EventEntry* eventEntry,
273 int32_t inputTargetFlags) {
chaviw1ff3d1e2020-07-01 15:53:47 -0700274 if (inputTarget.useDefaultPointerTransform()) {
275 const ui::Transform& transform = inputTarget.getDefaultPointerTransform();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000276 return std::make_unique<DispatchEntry>(eventEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700277 inputTargetFlags, transform,
278 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000279 }
280
281 ALOG_ASSERT(eventEntry->type == EventEntry::Type::MOTION);
282 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*eventEntry);
283
284 PointerCoords pointerCoords[motionEntry.pointerCount];
285
286 // Use the first pointer information to normalize all other pointers. This could be any pointer
287 // as long as all other pointers are normalized to the same value and the final DispatchEntry
chaviw1ff3d1e2020-07-01 15:53:47 -0700288 // uses the transform for the normalized pointer.
289 const ui::Transform& firstPointerTransform =
290 inputTarget.pointerTransforms[inputTarget.pointerIds.firstMarkedBit()];
291 ui::Transform inverseFirstTransform = firstPointerTransform.inverse();
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000292
293 // Iterate through all pointers in the event to normalize against the first.
294 for (uint32_t pointerIndex = 0; pointerIndex < motionEntry.pointerCount; pointerIndex++) {
295 const PointerProperties& pointerProperties = motionEntry.pointerProperties[pointerIndex];
296 uint32_t pointerId = uint32_t(pointerProperties.id);
chaviw1ff3d1e2020-07-01 15:53:47 -0700297 const ui::Transform& currTransform = inputTarget.pointerTransforms[pointerId];
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000298
299 pointerCoords[pointerIndex].copyFrom(motionEntry.pointerCoords[pointerIndex]);
chaviw1ff3d1e2020-07-01 15:53:47 -0700300 // First, apply the current pointer's transform to update the coordinates into
301 // window space.
302 pointerCoords[pointerIndex].transform(currTransform);
303 // Next, apply the inverse transform of the normalized coordinates so the
304 // current coordinates are transformed into the normalized coordinate space.
305 pointerCoords[pointerIndex].transform(inverseFirstTransform);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000306 }
307
308 MotionEntry* combinedMotionEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -0800309 new MotionEntry(motionEntry.id, motionEntry.eventTime, motionEntry.deviceId,
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000310 motionEntry.source, motionEntry.displayId, motionEntry.policyFlags,
311 motionEntry.action, motionEntry.actionButton, motionEntry.flags,
312 motionEntry.metaState, motionEntry.buttonState,
313 motionEntry.classification, motionEntry.edgeFlags,
314 motionEntry.xPrecision, motionEntry.yPrecision,
315 motionEntry.xCursorPosition, motionEntry.yCursorPosition,
316 motionEntry.downTime, motionEntry.pointerCount,
317 motionEntry.pointerProperties, pointerCoords, 0 /* xOffset */,
318 0 /* yOffset */);
319
320 if (motionEntry.injectionState) {
321 combinedMotionEntry->injectionState = motionEntry.injectionState;
322 combinedMotionEntry->injectionState->refCount += 1;
323 }
324
325 std::unique_ptr<DispatchEntry> dispatchEntry =
326 std::make_unique<DispatchEntry>(combinedMotionEntry, // increments ref
chaviw1ff3d1e2020-07-01 15:53:47 -0700327 inputTargetFlags, firstPointerTransform,
328 inputTarget.globalScaleFactor);
Chavi Weingarten65f98b82020-01-16 18:56:50 +0000329 combinedMotionEntry->release();
330 return dispatchEntry;
331}
332
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -0700333static void addGestureMonitors(const std::vector<Monitor>& monitors,
334 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset = 0,
335 float yOffset = 0) {
336 if (monitors.empty()) {
337 return;
338 }
339 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
340 for (const Monitor& monitor : monitors) {
341 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
342 }
343}
344
Michael Wrightd02c5b62014-02-10 15:10:22 -0800345// --- InputDispatcher ---
346
Garfield Tan00f511d2019-06-12 16:55:40 -0700347InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
348 : mPolicy(policy),
349 mPendingEvent(nullptr),
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700350 mLastDropReason(DropReason::NOT_DROPPED),
Garfield Tanff1f1bb2020-01-28 13:24:04 -0800351 mIdGenerator(IdGenerator::Source::INPUT_DISPATCHER),
Garfield Tan00f511d2019-06-12 16:55:40 -0700352 mAppSwitchSawKeyDown(false),
353 mAppSwitchDueTime(LONG_LONG_MAX),
354 mNextUnblockedEvent(nullptr),
355 mDispatchEnabled(false),
356 mDispatchFrozen(false),
357 mInputFilterEnabled(false),
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -0800358 // mInTouchMode will be initialized by the WindowManager to the default device config.
359 // To avoid leaking stack in case that call never comes, and for tests,
360 // initialize it here anyways.
361 mInTouchMode(true),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700362 mFocusedDisplayId(ADISPLAY_ID_DEFAULT) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800363 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800364 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800365
Yi Kong9b14ac62018-07-17 13:48:38 -0700366 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800367
368 policy->getDispatcherConfiguration(&mConfig);
369}
370
371InputDispatcher::~InputDispatcher() {
372 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800373 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800374
375 resetKeyRepeatLocked();
376 releasePendingEventLocked();
377 drainInboundQueueLocked();
378 }
379
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700380 while (!mConnectionsByFd.empty()) {
381 sp<Connection> connection = mConnectionsByFd.begin()->second;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500382 unregisterInputChannel(*connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800383 }
384}
385
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700386status_t InputDispatcher::start() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700387 if (mThread) {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700388 return ALREADY_EXISTS;
389 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700390 mThread = std::make_unique<InputThread>(
391 "InputDispatcher", [this]() { dispatchOnce(); }, [this]() { mLooper->wake(); });
392 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700393}
394
395status_t InputDispatcher::stop() {
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700396 if (mThread && mThread->isCallingThread()) {
397 ALOGE("InputDispatcher cannot be stopped from its own thread!");
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700398 return INVALID_OPERATION;
399 }
Prabir Pradhan5a57cff2019-10-31 18:40:33 -0700400 mThread.reset();
401 return OK;
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700402}
403
Michael Wrightd02c5b62014-02-10 15:10:22 -0800404void InputDispatcher::dispatchOnce() {
405 nsecs_t nextWakeupTime = LONG_LONG_MAX;
406 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800407 std::scoped_lock _l(mLock);
408 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409
410 // Run a dispatch loop if there are no pending commands.
411 // The dispatch loop might enqueue commands to run afterwards.
412 if (!haveCommandsLocked()) {
413 dispatchOnceInnerLocked(&nextWakeupTime);
414 }
415
416 // Run all pending commands if there are any.
417 // If any commands were run then force the next poll to wake up immediately.
418 if (runCommandsLockedInterruptible()) {
419 nextWakeupTime = LONG_LONG_MIN;
420 }
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800421
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700422 // If we are still waiting for ack on some events,
423 // we might have to wake up earlier to check if an app is anr'ing.
424 const nsecs_t nextAnrCheck = processAnrsLocked();
425 nextWakeupTime = std::min(nextWakeupTime, nextAnrCheck);
426
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800427 // We are about to enter an infinitely long sleep, because we have no commands or
428 // pending or queued events
429 if (nextWakeupTime == LONG_LONG_MAX) {
430 mDispatcherEnteredIdle.notify_all();
431 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800432 } // release lock
433
434 // Wait for callback or timeout or wake. (make sure we round up, not down)
435 nsecs_t currentTime = now();
436 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
437 mLooper->pollOnce(timeoutMillis);
438}
439
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700440/**
441 * Check if any of the connections' wait queues have events that are too old.
442 * If we waited for events to be ack'ed for more than the window timeout, raise an ANR.
443 * Return the time at which we should wake up next.
444 */
445nsecs_t InputDispatcher::processAnrsLocked() {
446 const nsecs_t currentTime = now();
447 nsecs_t nextAnrCheck = LONG_LONG_MAX;
448 // Check if we are waiting for a focused window to appear. Raise ANR if waited too long
449 if (mNoFocusedWindowTimeoutTime.has_value() && mAwaitedFocusedApplication != nullptr) {
450 if (currentTime >= *mNoFocusedWindowTimeoutTime) {
451 onAnrLocked(mAwaitedFocusedApplication);
Chris Yea209fde2020-07-22 13:54:51 -0700452 mAwaitedFocusedApplication.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700453 return LONG_LONG_MIN;
454 } else {
455 // Keep waiting
456 const nsecs_t millisRemaining = ns2ms(*mNoFocusedWindowTimeoutTime - currentTime);
457 ALOGW("Still no focused window. Will drop the event in %" PRId64 "ms", millisRemaining);
458 nextAnrCheck = *mNoFocusedWindowTimeoutTime;
459 }
460 }
461
462 // Check if any connection ANRs are due
463 nextAnrCheck = std::min(nextAnrCheck, mAnrTracker.firstTimeout());
464 if (currentTime < nextAnrCheck) { // most likely scenario
465 return nextAnrCheck; // everything is normal. Let's check again at nextAnrCheck
466 }
467
468 // If we reached here, we have an unresponsive connection.
469 sp<Connection> connection = getConnectionLocked(mAnrTracker.firstToken());
470 if (connection == nullptr) {
471 ALOGE("Could not find connection for entry %" PRId64, mAnrTracker.firstTimeout());
472 return nextAnrCheck;
473 }
474 connection->responsive = false;
475 // Stop waking up for this unresponsive connection
476 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
477 onAnrLocked(connection);
478 return LONG_LONG_MIN;
479}
480
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500481std::chrono::nanoseconds InputDispatcher::getDispatchingTimeoutLocked(const sp<IBinder>& token) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700482 sp<InputWindowHandle> window = getWindowHandleLocked(token);
483 if (window != nullptr) {
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500484 return window->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700485 }
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500486 return DEFAULT_INPUT_DISPATCHING_TIMEOUT;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700487}
488
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
490 nsecs_t currentTime = now();
491
Jeff Browndc5992e2014-04-11 01:27:26 -0700492 // Reset the key repeat timer whenever normal dispatch is suspended while the
493 // device is in a non-interactive state. This is to ensure that we abort a key
494 // repeat if the device is just coming out of sleep.
495 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496 resetKeyRepeatLocked();
497 }
498
499 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
500 if (mDispatchFrozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +0100501 if (DEBUG_FOCUS) {
502 ALOGD("Dispatch frozen. Waiting some more.");
503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800504 return;
505 }
506
507 // Optimize latency of app switches.
508 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
509 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
510 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
511 if (mAppSwitchDueTime < *nextWakeupTime) {
512 *nextWakeupTime = mAppSwitchDueTime;
513 }
514
515 // Ready to start a new event.
516 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700517 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700518 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519 if (isAppSwitchDue) {
520 // The inbound queue is empty so the app switch key we were waiting
521 // for will never arrive. Stop waiting for it.
522 resetPendingAppSwitchLocked(false);
523 isAppSwitchDue = false;
524 }
525
526 // Synthesize a key repeat if appropriate.
527 if (mKeyRepeatState.lastKeyEntry) {
528 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
529 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
530 } else {
531 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
532 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
533 }
534 }
535 }
536
537 // Nothing to do if there is no pending event.
538 if (!mPendingEvent) {
539 return;
540 }
541 } else {
542 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700543 mPendingEvent = mInboundQueue.front();
544 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 traceInboundQueueLengthLocked();
546 }
547
548 // Poke user activity for this event.
549 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700550 pokeUserActivityLocked(*mPendingEvent);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 }
553
554 // Now we have an event to dispatch.
555 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700556 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557 bool done = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700558 DropReason dropReason = DropReason::NOT_DROPPED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700560 dropReason = DropReason::POLICY;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561 } else if (!mDispatchEnabled) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700562 dropReason = DropReason::DISABLED;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 }
564
565 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700566 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 }
568
569 switch (mPendingEvent->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700570 case EventEntry::Type::CONFIGURATION_CHANGED: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700571 ConfigurationChangedEntry* typedEntry =
572 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
573 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700574 dropReason = DropReason::NOT_DROPPED; // configuration changes are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700575 break;
576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700578 case EventEntry::Type::DEVICE_RESET: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700579 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
580 done = dispatchDeviceResetLocked(currentTime, typedEntry);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700581 dropReason = DropReason::NOT_DROPPED; // device resets are never dropped
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700582 break;
583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100585 case EventEntry::Type::FOCUS: {
586 FocusEntry* typedEntry = static_cast<FocusEntry*>(mPendingEvent);
587 dispatchFocusLocked(currentTime, typedEntry);
588 done = true;
589 dropReason = DropReason::NOT_DROPPED; // focus events are never dropped
590 break;
591 }
592
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700593 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700594 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
595 if (isAppSwitchDue) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700596 if (isAppSwitchKeyEvent(*typedEntry)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700597 resetPendingAppSwitchLocked(true);
598 isAppSwitchDue = false;
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700599 } else if (dropReason == DropReason::NOT_DROPPED) {
600 dropReason = DropReason::APP_SWITCH;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700601 }
602 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700603 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700604 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700605 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700606 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
607 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700608 }
609 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
610 break;
611 }
612
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700613 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700614 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700615 if (dropReason == DropReason::NOT_DROPPED && isAppSwitchDue) {
616 dropReason = DropReason::APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 }
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700618 if (dropReason == DropReason::NOT_DROPPED && isStaleEvent(currentTime, *typedEntry)) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700619 dropReason = DropReason::STALE;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700620 }
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700621 if (dropReason == DropReason::NOT_DROPPED && mNextUnblockedEvent) {
622 dropReason = DropReason::BLOCKED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700623 }
624 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
625 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 }
628
629 if (done) {
Siarhei Vishniakou0fb1a0e2019-10-22 11:23:36 -0700630 if (dropReason != DropReason::NOT_DROPPED) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700631 dropInboundEventLocked(*mPendingEvent, dropReason);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 }
Michael Wright3a981722015-06-10 15:26:13 +0100633 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634
635 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700636 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637 }
638}
639
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700640/**
641 * Return true if the events preceding this incoming motion event should be dropped
642 * Return false otherwise (the default behaviour)
643 */
644bool InputDispatcher::shouldPruneInboundQueueLocked(const MotionEntry& motionEntry) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700645 const bool isPointerDownEvent = motionEntry.action == AMOTION_EVENT_ACTION_DOWN &&
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700646 (motionEntry.source & AINPUT_SOURCE_CLASS_POINTER);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700647
648 // Optimize case where the current application is unresponsive and the user
649 // decides to touch a window in a different application.
650 // If the application takes too long to catch up then we drop all events preceding
651 // the touch into the other window.
652 if (isPointerDownEvent && mAwaitedFocusedApplication != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700653 int32_t displayId = motionEntry.displayId;
654 int32_t x = static_cast<int32_t>(
655 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
656 int32_t y = static_cast<int32_t>(
657 motionEntry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
658 sp<InputWindowHandle> touchedWindowHandle =
659 findTouchedWindowAtLocked(displayId, x, y, nullptr);
660 if (touchedWindowHandle != nullptr &&
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700661 touchedWindowHandle->getApplicationToken() !=
662 mAwaitedFocusedApplication->getApplicationToken()) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700663 // User touched a different application than the one we are waiting on.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700664 ALOGI("Pruning input queue because user touched a different application while waiting "
665 "for %s",
666 mAwaitedFocusedApplication->getName().c_str());
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700667 return true;
668 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700669
670 // Alternatively, maybe there's a gesture monitor that could handle this event
671 std::vector<TouchedMonitor> gestureMonitors =
672 findTouchedGestureMonitorsLocked(displayId, {});
673 for (TouchedMonitor& gestureMonitor : gestureMonitors) {
674 sp<Connection> connection =
675 getConnectionLocked(gestureMonitor.monitor.inputChannel->getConnectionToken());
Siarhei Vishniakou34ed4d42020-06-18 00:43:02 +0000676 if (connection != nullptr && connection->responsive) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700677 // This monitor could take more input. Drop all events preceding this
678 // event, so that gesture monitor could get a chance to receive the stream
679 ALOGW("Pruning the input queue because %s is unresponsive, but we have a "
680 "responsive gesture monitor that may handle the event",
681 mAwaitedFocusedApplication->getName().c_str());
682 return true;
683 }
684 }
685 }
686
687 // Prevent getting stuck: if we have a pending key event, and some motion events that have not
688 // yet been processed by some connections, the dispatcher will wait for these motion
689 // events to be processed before dispatching the key event. This is because these motion events
690 // may cause a new window to be launched, which the user might expect to receive focus.
691 // To prevent waiting forever for such events, just send the key to the currently focused window
692 if (isPointerDownEvent && mKeyIsWaitingForEventsTimeout) {
693 ALOGD("Received a new pointer down event, stop waiting for events to process and "
694 "just send the pending key event to the focused window.");
695 mKeyIsWaitingForEventsTimeout = now();
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700696 }
697 return false;
698}
699
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700701 bool needWake = mInboundQueue.empty();
702 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 traceInboundQueueLengthLocked();
704
705 switch (entry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700706 case EventEntry::Type::KEY: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700707 // Optimize app switch latency.
708 // If the application takes too long to catch up then we drop all events preceding
709 // the app switch key.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700710 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*entry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700711 if (isAppSwitchKeyEvent(keyEntry)) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700712 if (keyEntry.action == AKEY_EVENT_ACTION_DOWN) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700713 mAppSwitchSawKeyDown = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700714 } else if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700715 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700717 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718#endif
Siarhei Vishniakoud2770042019-10-29 11:08:14 -0700719 mAppSwitchDueTime = keyEntry.eventTime + APP_SWITCH_TIMEOUT;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700720 mAppSwitchSawKeyDown = false;
721 needWake = true;
722 }
723 }
724 }
725 break;
726 }
727
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700728 case EventEntry::Type::MOTION: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700729 if (shouldPruneInboundQueueLocked(static_cast<MotionEntry&>(*entry))) {
730 mNextUnblockedEvent = entry;
731 needWake = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700733 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100735 case EventEntry::Type::FOCUS: {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -0700736 LOG_ALWAYS_FATAL("Focus events should be inserted using enqueueFocusEventLocked");
737 break;
738 }
739 case EventEntry::Type::CONFIGURATION_CHANGED:
740 case EventEntry::Type::DEVICE_RESET: {
Siarhei Vishniakou49483272019-10-22 13:13:47 -0700741 // nothing to do
742 break;
743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744 }
745
746 return needWake;
747}
748
749void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
750 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700751 mRecentQueue.push_back(entry);
752 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
753 mRecentQueue.front()->release();
754 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 }
756}
757
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700758sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700759 int32_t y, TouchState* touchState,
760 bool addOutsideTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700761 bool addPortalWindows) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -0700762 if ((addPortalWindows || addOutsideTargets) && touchState == nullptr) {
763 LOG_ALWAYS_FATAL(
764 "Must provide a valid touch state if adding portal windows or outside targets");
765 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800767 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
768 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 Nair7d3d00d2020-08-03 11:20:42 -07001032void InputDispatcher::enqueueFocusEventLocked(const InputWindowHandle& window, bool hasFocus,
1033 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 Nair7d3d00d2020-08-03 11:20:42 -07001042 new FocusEntry(mIdGenerator.nextId(), now(), window.getToken(), 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);
Tiger Huang721e26f2018-07-24 22:26:19 +08001125 sp<InputWindowHandle> focusedWindowHandle =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001126 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(*entry));
Tiger Huang721e26f2018-07-24 22:26:19 +08001127 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001128 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
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);
1417 sp<InputWindowHandle> focusedWindowHandle =
1418 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Chris Yea209fde2020-07-22 13:54:51 -07001419 std::shared_ptr<InputApplicationHandle> focusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08001420 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1421
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 // If there is no currently focused window and no focused application
1423 // then drop the event.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001424 if (focusedWindowHandle == nullptr && focusedApplicationHandle == nullptr) {
1425 ALOGI("Dropping %s event because there is no focused window or focused application in "
1426 "display %" PRId32 ".",
1427 EventEntry::typeToString(entry.type), displayId);
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001428 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429 }
1430
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001431 // Compatibility behavior: raise ANR if there is a focused application, but no focused window.
1432 // Only start counting when we have a focused event to dispatch. The ANR is canceled if we
1433 // start interacting with another application via touch (app switch). This code can be removed
1434 // if the "no focused window ANR" is moved to the policy. Input doesn't know whether
1435 // an app is expected to have a focused window.
1436 if (focusedWindowHandle == nullptr && focusedApplicationHandle != nullptr) {
1437 if (!mNoFocusedWindowTimeoutTime.has_value()) {
1438 // We just discovered that there's no focused window. Start the ANR timer
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001439 std::chrono::nanoseconds timeout = focusedApplicationHandle->getDispatchingTimeout(
1440 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1441 mNoFocusedWindowTimeoutTime = currentTime + timeout.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001442 mAwaitedFocusedApplication = focusedApplicationHandle;
1443 ALOGW("Waiting because no window has focus but %s may eventually add a "
1444 "window when it finishes starting up. Will wait for %" PRId64 "ms",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001445 mAwaitedFocusedApplication->getName().c_str(), millis(timeout));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001446 *nextWakeupTime = *mNoFocusedWindowTimeoutTime;
1447 return INPUT_EVENT_INJECTION_PENDING;
1448 } else if (currentTime > *mNoFocusedWindowTimeoutTime) {
1449 // Already raised ANR. Drop the event
1450 ALOGE("Dropping %s event because there is no focused window",
1451 EventEntry::typeToString(entry.type));
1452 return INPUT_EVENT_INJECTION_FAILED;
1453 } else {
1454 // Still waiting for the focused window
1455 return INPUT_EVENT_INJECTION_PENDING;
1456 }
1457 }
1458
1459 // we have a valid, non-null focused window
1460 resetNoFocusedWindowTimeoutLocked();
1461
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 // Check permissions.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001463 if (!checkInjectionPermission(focusedWindowHandle, entry.injectionState)) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001464 return INPUT_EVENT_INJECTION_PERMISSION_DENIED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001465 }
1466
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001467 if (focusedWindowHandle->getInfo()->paused) {
1468 ALOGI("Waiting because %s is paused", focusedWindowHandle->getName().c_str());
1469 return INPUT_EVENT_INJECTION_PENDING;
1470 }
1471
1472 // If the event is a key event, then we must wait for all previous events to
1473 // complete before delivering it because previous events may have the
1474 // side-effect of transferring focus to a different window and we want to
1475 // ensure that the following keys are sent to the new window.
1476 //
1477 // Suppose the user touches a button in a window then immediately presses "A".
1478 // If the button causes a pop-up window to appear then we want to ensure that
1479 // the "A" key is delivered to the new pop-up window. This is because users
1480 // often anticipate pending UI changes when typing on a keyboard.
1481 // To obtain this behavior, we must serialize key events with respect to all
1482 // prior input events.
1483 if (entry.type == EventEntry::Type::KEY) {
1484 if (shouldWaitToSendKeyLocked(currentTime, focusedWindowHandle->getName().c_str())) {
1485 *nextWakeupTime = *mKeyIsWaitingForEventsTimeout;
1486 return INPUT_EVENT_INJECTION_PENDING;
1487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 }
1489
1490 // Success! Output targets.
Tiger Huang721e26f2018-07-24 22:26:19 +08001491 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001492 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1493 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494
1495 // Done.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001496 return INPUT_EVENT_INJECTION_SUCCEEDED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497}
1498
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001499/**
1500 * Given a list of monitors, remove the ones we cannot find a connection for, and the ones
1501 * that are currently unresponsive.
1502 */
1503std::vector<TouchedMonitor> InputDispatcher::selectResponsiveMonitorsLocked(
1504 const std::vector<TouchedMonitor>& monitors) const {
1505 std::vector<TouchedMonitor> responsiveMonitors;
1506 std::copy_if(monitors.begin(), monitors.end(), std::back_inserter(responsiveMonitors),
1507 [this](const TouchedMonitor& monitor) REQUIRES(mLock) {
1508 sp<Connection> connection = getConnectionLocked(
1509 monitor.monitor.inputChannel->getConnectionToken());
1510 if (connection == nullptr) {
1511 ALOGE("Could not find connection for monitor %s",
1512 monitor.monitor.inputChannel->getName().c_str());
1513 return false;
1514 }
1515 if (!connection->responsive) {
1516 ALOGW("Unresponsive monitor %s will not get the new gesture",
1517 connection->inputChannel->getName().c_str());
1518 return false;
1519 }
1520 return true;
1521 });
1522 return responsiveMonitors;
1523}
1524
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001526 const MotionEntry& entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001527 std::vector<InputTarget>& inputTargets,
1528 nsecs_t* nextWakeupTime,
1529 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001530 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 enum InjectionPermission {
1532 INJECTION_PERMISSION_UNKNOWN,
1533 INJECTION_PERMISSION_GRANTED,
1534 INJECTION_PERMISSION_DENIED
1535 };
1536
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 // For security reasons, we defer updating the touch state until we are sure that
1538 // event injection will be allowed.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001539 int32_t displayId = entry.displayId;
1540 int32_t action = entry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1542
1543 // Update the touch state as needed based on the properties of the touch event.
1544 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1545 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001546 sp<InputWindowHandle> newHoverWindowHandle(mLastHoverWindowHandle);
1547 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001549 // Copy current touch state into tempTouchState.
1550 // This state will be used to update mTouchStatesByDisplay at the end of this function.
1551 // If no state for the specified display exists, then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001552 const TouchState* oldState = nullptr;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001553 TouchState tempTouchState;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07001554 std::unordered_map<int32_t, TouchState>::iterator oldStateIt =
1555 mTouchStatesByDisplay.find(displayId);
1556 if (oldStateIt != mTouchStatesByDisplay.end()) {
1557 oldState = &(oldStateIt->second);
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001558 tempTouchState.copyFrom(*oldState);
Jeff Brownf086ddb2014-02-11 14:28:48 -08001559 }
1560
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001561 bool isSplit = tempTouchState.split;
1562 bool switchedDevice = tempTouchState.deviceId >= 0 && tempTouchState.displayId >= 0 &&
1563 (tempTouchState.deviceId != entry.deviceId || tempTouchState.source != entry.source ||
1564 tempTouchState.displayId != displayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001565 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1566 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1567 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1568 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1569 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001570 const bool isFromMouse = entry.source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 bool wrongDevice = false;
1572 if (newGesture) {
1573 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001574 if (switchedDevice && tempTouchState.down && !down && !isHoverAction) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001575 ALOGI("Dropping event because a pointer for a different device is already down "
1576 "in display %" PRId32,
1577 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001578 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1580 switchedDevice = false;
1581 wrongDevice = true;
1582 goto Failed;
1583 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001584 tempTouchState.reset();
1585 tempTouchState.down = down;
1586 tempTouchState.deviceId = entry.deviceId;
1587 tempTouchState.source = entry.source;
1588 tempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001590 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001591 ALOGI("Dropping move event because a pointer for a different device is already active "
1592 "in display %" PRId32,
1593 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001594 // TODO: test multiple simultaneous input streams.
1595 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1596 switchedDevice = false;
1597 wrongDevice = true;
1598 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 }
1600
1601 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1602 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1603
Garfield Tan00f511d2019-06-12 16:55:40 -07001604 int32_t x;
1605 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001607 // Always dispatch mouse events to cursor position.
1608 if (isFromMouse) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001609 x = int32_t(entry.xCursorPosition);
1610 y = int32_t(entry.yCursorPosition);
Garfield Tan00f511d2019-06-12 16:55:40 -07001611 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001612 x = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1613 y = int32_t(entry.pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
Garfield Tan00f511d2019-06-12 16:55:40 -07001614 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001615 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tandf26e862020-07-01 20:18:19 -07001616 newTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001617 findTouchedWindowAtLocked(displayId, x, y, &tempTouchState,
1618 isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001619
1620 std::vector<TouchedMonitor> newGestureMonitors = isDown
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001621 ? findTouchedGestureMonitorsLocked(displayId, tempTouchState.portalWindows)
Michael Wright3dd60e22019-03-27 22:06:44 +00001622 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623
Michael Wrightd02c5b62014-02-10 15:10:22 -08001624 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001625 if (newTouchedWindowHandle != nullptr &&
1626 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001627 // New window supports splitting, but we should never split mouse events.
1628 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629 } else if (isSplit) {
1630 // New window does not support splitting but we have already split events.
1631 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001632 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633 }
1634
1635 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001636 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 // Try to assign the pointer to the first foreground window we find, if there is one.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001638 newTouchedWindowHandle = tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001639 }
1640
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001641 if (newTouchedWindowHandle != nullptr && newTouchedWindowHandle->getInfo()->paused) {
1642 ALOGI("Not sending touch event to %s because it is paused",
1643 newTouchedWindowHandle->getName().c_str());
1644 newTouchedWindowHandle = nullptr;
1645 }
1646
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001647 // Ensure the window has a connection and the connection is responsive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001648 if (newTouchedWindowHandle != nullptr) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001649 const bool isResponsive = hasResponsiveConnectionLocked(*newTouchedWindowHandle);
1650 if (!isResponsive) {
1651 ALOGW("%s will not receive the new gesture at %" PRIu64,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001652 newTouchedWindowHandle->getName().c_str(), entry.eventTime);
1653 newTouchedWindowHandle = nullptr;
1654 }
1655 }
1656
1657 // Also don't send the new touch event to unresponsive gesture monitors
1658 newGestureMonitors = selectResponsiveMonitorsLocked(newGestureMonitors);
1659
Michael Wright3dd60e22019-03-27 22:06:44 +00001660 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1661 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001662 "(%d, %d) in display %" PRId32 ".",
1663 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001664 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1665 goto Failed;
1666 }
1667
1668 if (newTouchedWindowHandle != nullptr) {
1669 // Set target flags.
1670 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1671 if (isSplit) {
1672 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001674 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1675 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1676 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1677 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1678 }
1679
1680 // Update hover state.
Garfield Tandf26e862020-07-01 20:18:19 -07001681 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT) {
1682 newHoverWindowHandle = nullptr;
1683 } else if (isHoverAction) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001684 newHoverWindowHandle = newTouchedWindowHandle;
Michael Wright3dd60e22019-03-27 22:06:44 +00001685 }
1686
1687 // Update the temporary touch state.
1688 BitSet32 pointerIds;
1689 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001690 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wright3dd60e22019-03-27 22:06:44 +00001691 pointerIds.markBit(pointerId);
1692 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001693 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001694 }
1695
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001696 tempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 } else {
1698 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1699
1700 // If the pointer is not currently down, then ignore the event.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001701 if (!tempTouchState.down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001702 if (DEBUG_FOCUS) {
1703 ALOGD("Dropping event because the pointer is not down or we previously "
1704 "dropped the pointer down event in display %" PRId32,
1705 displayId);
1706 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1708 goto Failed;
1709 }
1710
1711 // Check whether touches should slip outside of the current foreground window.
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001712 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry.pointerCount == 1 &&
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001713 tempTouchState.isSlippery()) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001714 int32_t x = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1715 int32_t y = int32_t(entry.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716
1717 sp<InputWindowHandle> oldTouchedWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001718 tempTouchState.getFirstForegroundWindowHandle();
Garfield Tandf26e862020-07-01 20:18:19 -07001719 newTouchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y, &tempTouchState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001720 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1721 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001722 if (DEBUG_FOCUS) {
1723 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
1724 oldTouchedWindowHandle->getName().c_str(),
1725 newTouchedWindowHandle->getName().c_str(), displayId);
1726 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 // Make a slippery exit from the old window.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001728 tempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1729 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1730 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731
1732 // Make a slippery entrance into the new window.
1733 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1734 isSplit = true;
1735 }
1736
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001737 int32_t targetFlags =
1738 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 if (isSplit) {
1740 targetFlags |= InputTarget::FLAG_SPLIT;
1741 }
1742 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1743 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1744 }
1745
1746 BitSet32 pointerIds;
1747 if (isSplit) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001748 pointerIds.markBit(entry.pointerProperties[0].id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001750 tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 }
1752 }
1753 }
1754
1755 if (newHoverWindowHandle != mLastHoverWindowHandle) {
Garfield Tandf26e862020-07-01 20:18:19 -07001756 // Let the previous window know that the hover sequence is over, unless we already did it
1757 // when dispatching it as is to newTouchedWindowHandle.
1758 if (mLastHoverWindowHandle != nullptr &&
1759 (maskedAction != AMOTION_EVENT_ACTION_HOVER_EXIT ||
1760 mLastHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761#if DEBUG_HOVER
1762 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001763 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001765 tempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1766 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 }
1768
Garfield Tandf26e862020-07-01 20:18:19 -07001769 // Let the new window know that the hover sequence is starting, unless we already did it
1770 // when dispatching it as is to newTouchedWindowHandle.
1771 if (newHoverWindowHandle != nullptr &&
1772 (maskedAction != AMOTION_EVENT_ACTION_HOVER_ENTER ||
1773 newHoverWindowHandle != newTouchedWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774#if DEBUG_HOVER
1775 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001776 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777#endif
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001778 tempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1779 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1780 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001781 }
1782 }
1783
1784 // Check permission to inject into all touched foreground windows and ensure there
1785 // is at least one touched foreground window.
1786 {
1787 bool haveForegroundWindow = false;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001788 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1790 haveForegroundWindow = true;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001791 if (!checkInjectionPermission(touchedWindow.windowHandle, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001792 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1793 injectionPermission = INJECTION_PERMISSION_DENIED;
1794 goto Failed;
1795 }
1796 }
1797 }
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001798 bool hasGestureMonitor = !tempTouchState.gestureMonitors.empty();
Michael Wright3dd60e22019-03-27 22:06:44 +00001799 if (!haveForegroundWindow && !hasGestureMonitor) {
Siarhei Vishniakouf0007dd2020-04-13 11:40:37 -07001800 ALOGI("Dropping event because there is no touched foreground window in display "
1801 "%" PRId32 " or gesture monitor to receive it.",
1802 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001803 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1804 goto Failed;
1805 }
1806
1807 // Permission granted to injection into all touched foreground windows.
1808 injectionPermission = INJECTION_PERMISSION_GRANTED;
1809 }
1810
1811 // Check whether windows listening for outside touches are owned by the same UID. If it is
1812 // set the policy flag that we will not reveal coordinate information to this window.
1813 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1814 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001815 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001816 if (foregroundWindowHandle) {
1817 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001818 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001819 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1820 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1821 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001822 tempTouchState.addOrUpdateWindow(inputWindowHandle,
1823 InputTarget::FLAG_ZERO_COORDS,
1824 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001825 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
1827 }
1828 }
1829 }
1830
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 // If this is the first pointer going down and the touched window has a wallpaper
1832 // then also add the touched wallpaper windows so they are locked in for the duration
1833 // of the touch gesture.
1834 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1835 // engine only supports touch events. We would need to add a mechanism similar
1836 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1837 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1838 sp<InputWindowHandle> foregroundWindowHandle =
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001839 tempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001840 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001841 const std::vector<sp<InputWindowHandle>> windowHandles =
1842 getWindowHandlesLocked(displayId);
1843 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001845 if (info->displayId == displayId &&
Michael Wright44753b12020-07-08 13:48:11 +01001846 windowHandle->getInfo()->type == InputWindowInfo::Type::WALLPAPER) {
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001847 tempTouchState
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001848 .addOrUpdateWindow(windowHandle,
1849 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1850 InputTarget::
1851 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1852 InputTarget::FLAG_DISPATCH_AS_IS,
1853 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 }
1855 }
1856 }
1857 }
1858
1859 // Success! Output targets.
1860 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1861
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001862 for (const TouchedWindow& touchedWindow : tempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001864 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 }
1866
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001867 for (const TouchedMonitor& touchedMonitor : tempTouchState.gestureMonitors) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001868 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001869 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001870 }
1871
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872 // Drop the outside or hover touch windows since we will not care about them
1873 // in the next iteration.
Siarhei Vishniakou33eceeb2020-03-24 19:50:03 -07001874 tempTouchState.filterNonAsIsTouchWindows();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875
1876Failed:
1877 // Check injection permission once and for all.
1878 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07001879 if (checkInjectionPermission(nullptr, entry.injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001880 injectionPermission = INJECTION_PERMISSION_GRANTED;
1881 } else {
1882 injectionPermission = INJECTION_PERMISSION_DENIED;
1883 }
1884 }
1885
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001886 if (injectionPermission != INJECTION_PERMISSION_GRANTED) {
1887 return injectionResult;
1888 }
1889
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890 // Update final pieces of touch state if the injector had permission.
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001891 if (!wrongDevice) {
1892 if (switchedDevice) {
1893 if (DEBUG_FOCUS) {
1894 ALOGD("Conflicting pointer actions: Switched to a different device.");
1895 }
1896 *outConflictingPointerActions = true;
1897 }
1898
1899 if (isHoverAction) {
1900 // Started hovering, therefore no longer down.
1901 if (oldState && oldState->down) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001902 if (DEBUG_FOCUS) {
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001903 ALOGD("Conflicting pointer actions: Hover received while pointer was "
1904 "down.");
Siarhei Vishniakou86587282019-09-09 18:20:15 +01001905 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 *outConflictingPointerActions = true;
1907 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001908 tempTouchState.reset();
1909 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1910 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1911 tempTouchState.deviceId = entry.deviceId;
1912 tempTouchState.source = entry.source;
1913 tempTouchState.displayId = displayId;
1914 }
1915 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1916 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1917 // All pointers up or canceled.
1918 tempTouchState.reset();
1919 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1920 // First pointer went down.
1921 if (oldState && oldState->down) {
1922 if (DEBUG_FOCUS) {
1923 ALOGD("Conflicting pointer actions: Down received while already down.");
1924 }
1925 *outConflictingPointerActions = true;
1926 }
1927 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1928 // One pointer went up.
1929 if (isSplit) {
1930 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1931 uint32_t pointerId = entry.pointerProperties[pointerIndex].id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001933 for (size_t i = 0; i < tempTouchState.windows.size();) {
1934 TouchedWindow& touchedWindow = tempTouchState.windows[i];
1935 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1936 touchedWindow.pointerIds.clearBit(pointerId);
1937 if (touchedWindow.pointerIds.isEmpty()) {
1938 tempTouchState.windows.erase(tempTouchState.windows.begin() + i);
1939 continue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001942 i += 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001944 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001945 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001946
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001947 // Save changes unless the action was scroll in which case the temporary touch
1948 // state was only valid for this one action.
1949 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1950 if (tempTouchState.displayId >= 0) {
1951 mTouchStatesByDisplay[displayId] = tempTouchState;
1952 } else {
1953 mTouchStatesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07001957 // Update hover state.
1958 mLastHoverWindowHandle = newHoverWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 }
1960
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 return injectionResult;
1962}
1963
1964void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001965 int32_t targetFlags, BitSet32 pointerIds,
1966 std::vector<InputTarget>& inputTargets) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001967 std::vector<InputTarget>::iterator it =
1968 std::find_if(inputTargets.begin(), inputTargets.end(),
1969 [&windowHandle](const InputTarget& inputTarget) {
1970 return inputTarget.inputChannel->getConnectionToken() ==
1971 windowHandle->getToken();
1972 });
Chavi Weingarten97b8eec2020-01-09 18:09:08 +00001973
Chavi Weingarten114b77f2020-01-15 22:35:10 +00001974 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001975
1976 if (it == inputTargets.end()) {
1977 InputTarget inputTarget;
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05001978 std::shared_ptr<InputChannel> inputChannel =
1979 getInputChannelLocked(windowHandle->getToken());
Chavi Weingarten65f98b82020-01-16 18:56:50 +00001980 if (inputChannel == nullptr) {
1981 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1982 return;
1983 }
1984 inputTarget.inputChannel = inputChannel;
1985 inputTarget.flags = targetFlags;
1986 inputTarget.globalScaleFactor = windowInfo->globalScaleFactor;
1987 inputTargets.push_back(inputTarget);
1988 it = inputTargets.end() - 1;
1989 }
1990
1991 ALOG_ASSERT(it->flags == targetFlags);
1992 ALOG_ASSERT(it->globalScaleFactor == windowInfo->globalScaleFactor);
1993
chaviw1ff3d1e2020-07-01 15:53:47 -07001994 it->addPointers(pointerIds, windowInfo->transform);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995}
1996
Michael Wright3dd60e22019-03-27 22:06:44 +00001997void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001998 int32_t displayId, float xOffset,
1999 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002000 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
2001 mGlobalMonitorsByDisplay.find(displayId);
2002
2003 if (it != mGlobalMonitorsByDisplay.end()) {
2004 const std::vector<Monitor>& monitors = it->second;
2005 for (const Monitor& monitor : monitors) {
2006 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002007 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 }
2009}
2010
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002011void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
2012 float yOffset,
2013 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002014 InputTarget target;
2015 target.inputChannel = monitor.inputChannel;
2016 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
chaviw1ff3d1e2020-07-01 15:53:47 -07002017 ui::Transform t;
2018 t.set(xOffset, yOffset);
2019 target.setDefaultPointerTransform(t);
Michael Wright3dd60e22019-03-27 22:06:44 +00002020 inputTargets.push_back(target);
2021}
2022
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002024 const InjectionState* injectionState) {
2025 if (injectionState &&
2026 (windowHandle == nullptr ||
2027 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
2028 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002029 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002031 "owned by uid %d",
2032 injectionState->injectorPid, injectionState->injectorUid,
2033 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 } else {
2035 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002036 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 }
2038 return false;
2039 }
2040 return true;
2041}
2042
Robert Carrc9bf1d32020-04-13 17:21:08 -07002043/**
2044 * Indicate whether one window handle should be considered as obscuring
2045 * another window handle. We only check a few preconditions. Actually
2046 * checking the bounds is left to the caller.
2047 */
2048static bool canBeObscuredBy(const sp<InputWindowHandle>& windowHandle,
2049 const sp<InputWindowHandle>& otherHandle) {
2050 // Compare by token so cloned layers aren't counted
2051 if (haveSameToken(windowHandle, otherHandle)) {
2052 return false;
2053 }
2054 auto info = windowHandle->getInfo();
2055 auto otherInfo = otherHandle->getInfo();
2056 if (!otherInfo->visible) {
2057 return false;
Robert Carr98c34a82020-06-09 15:36:34 -07002058 } else if (info->ownerPid == otherInfo->ownerPid) {
2059 // If ownerPid is the same we don't generate occlusion events as there
2060 // is no in-process security boundary.
Robert Carrc9bf1d32020-04-13 17:21:08 -07002061 return false;
Chris Yefcdff3e2020-05-10 15:16:04 -07002062 } else if (otherInfo->trustedOverlay) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002063 return false;
2064 } else if (otherInfo->displayId != info->displayId) {
2065 return false;
2066 }
2067 return true;
2068}
2069
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002070bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
2071 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002073 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2074 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002075 if (windowHandle == otherHandle) {
2076 break; // All future windows are below us. Exit early.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002079 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002080 otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081 return true;
2082 }
2083 }
2084 return false;
2085}
2086
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002087bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
2088 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002089 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002090 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002091 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Robert Carrc9bf1d32020-04-13 17:21:08 -07002092 if (windowHandle == otherHandle) {
2093 break; // All future windows are below us. Exit early.
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002094 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002095 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Robert Carrc9bf1d32020-04-13 17:21:08 -07002096 if (canBeObscuredBy(windowHandle, otherHandle) &&
minchelif28cc4e2020-03-19 11:18:11 +08002097 otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002098 return true;
2099 }
2100 }
2101 return false;
2102}
2103
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002104std::string InputDispatcher::getApplicationWindowLabel(
Chris Yea209fde2020-07-22 13:54:51 -07002105 const std::shared_ptr<InputApplicationHandle>& applicationHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002107 if (applicationHandle != nullptr) {
2108 if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002109 return applicationHandle->getName() + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 } else {
2111 return applicationHandle->getName();
2112 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002113 } else if (windowHandle != nullptr) {
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07002114 return windowHandle->getInfo()->applicationInfo.name + " - " + windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002116 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 }
2118}
2119
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002120void InputDispatcher::pokeUserActivityLocked(const EventEntry& eventEntry) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002121 if (eventEntry.type == EventEntry::Type::FOCUS) {
2122 // Focus events are passed to apps, but do not represent user activity.
2123 return;
2124 }
Tiger Huang721e26f2018-07-24 22:26:19 +08002125 int32_t displayId = getTargetDisplayId(eventEntry);
2126 sp<InputWindowHandle> focusedWindowHandle =
2127 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2128 if (focusedWindowHandle != nullptr) {
2129 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wright44753b12020-07-08 13:48:11 +01002130 if (info->inputFeatures.test(InputWindowInfo::Feature::DISABLE_USER_ACTIVITY)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002131#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002132 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133#endif
2134 return;
2135 }
2136 }
2137
2138 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002139 switch (eventEntry.type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002140 case EventEntry::Type::MOTION: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002141 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(eventEntry);
2142 if (motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002143 return;
2144 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002146 if (MotionEvent::isTouchEvent(motionEntry.source, motionEntry.action)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002147 eventType = USER_ACTIVITY_EVENT_TOUCH;
2148 }
2149 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002151 case EventEntry::Type::KEY: {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002152 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(eventEntry);
2153 if (keyEntry.flags & AKEY_EVENT_FLAG_CANCELED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002154 return;
2155 }
2156 eventType = USER_ACTIVITY_EVENT_BUTTON;
2157 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002159 case EventEntry::Type::FOCUS:
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002160 case EventEntry::Type::CONFIGURATION_CHANGED:
2161 case EventEntry::Type::DEVICE_RESET: {
2162 LOG_ALWAYS_FATAL("%s events are not user activity",
2163 EventEntry::typeToString(eventEntry.type));
2164 break;
2165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166 }
2167
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002168 std::unique_ptr<CommandEntry> commandEntry =
2169 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002170 commandEntry->eventTime = eventEntry.eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002172 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173}
2174
2175void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002176 const sp<Connection>& connection,
2177 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002178 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002179 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002180 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002181 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002182 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002183 ATRACE_NAME(message.c_str());
2184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185#if DEBUG_DISPATCH_CYCLE
2186 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002187 "globalScaleFactor=%f, pointerIds=0x%x %s",
2188 connection->getInputChannelName().c_str(), inputTarget.flags,
2189 inputTarget.globalScaleFactor, inputTarget.pointerIds.value,
2190 inputTarget.getPointerInfoString().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191#endif
2192
2193 // Skip this event if the connection status is not normal.
2194 // We don't want to enqueue additional outbound events if the connection is broken.
2195 if (connection->status != Connection::STATUS_NORMAL) {
2196#if DEBUG_DISPATCH_CYCLE
2197 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002198 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199#endif
2200 return;
2201 }
2202
2203 // Split a motion event if needed.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002204 if (inputTarget.flags & InputTarget::FLAG_SPLIT) {
2205 LOG_ALWAYS_FATAL_IF(eventEntry->type != EventEntry::Type::MOTION,
2206 "Entry type %s should not have FLAG_SPLIT",
2207 EventEntry::typeToString(eventEntry->type));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002208
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002209 const MotionEntry& originalMotionEntry = static_cast<const MotionEntry&>(*eventEntry);
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002210 if (inputTarget.pointerIds.count() != originalMotionEntry.pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002211 MotionEntry* splitMotionEntry =
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002212 splitMotionEvent(originalMotionEntry, inputTarget.pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213 if (!splitMotionEntry) {
2214 return; // split event was dropped
2215 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002216 if (DEBUG_FOCUS) {
2217 ALOGD("channel '%s' ~ Split motion event.",
2218 connection->getInputChannelName().c_str());
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002219 logOutboundMotionDetails(" ", *splitMotionEntry);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01002220 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002221 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 splitMotionEntry->release();
2223 return;
2224 }
2225 }
2226
2227 // Not splitting. Enqueue dispatch entries for the event as is.
2228 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2229}
2230
2231void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002232 const sp<Connection>& connection,
2233 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002234 const InputTarget& inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002235 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002236 std::string message =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002237 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, id=0x%" PRIx32 ")",
Garfield Tan6a5a14e2020-01-28 13:24:04 -08002238 connection->getInputChannelName().c_str(), eventEntry->id);
Michael Wright3dd60e22019-03-27 22:06:44 +00002239 ATRACE_NAME(message.c_str());
2240 }
2241
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002242 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243
2244 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002245 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002246 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002247 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002248 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002249 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002250 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002251 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002252 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002253 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002254 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002255 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002256 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257
2258 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002259 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260 startDispatchCycleLocked(currentTime, connection);
2261 }
2262}
2263
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002264void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2265 EventEntry* eventEntry,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002266 const InputTarget& inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002267 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002268 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002269 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2270 connection->getInputChannelName().c_str(),
2271 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002272 ATRACE_NAME(message.c_str());
2273 }
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002274 int32_t inputTargetFlags = inputTarget.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 if (!(inputTargetFlags & dispatchMode)) {
2276 return;
2277 }
2278 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2279
2280 // This is a new event.
2281 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002282 std::unique_ptr<DispatchEntry> dispatchEntry =
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002283 createDispatchEntry(inputTarget, eventEntry, inputTargetFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002285 // Use the eventEntry from dispatchEntry since the entry may have changed and can now be a
2286 // different EventEntry than what was passed in.
2287 EventEntry* newEntry = dispatchEntry->eventEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 // Apply target flags and update the connection's input state.
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002289 switch (newEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002290 case EventEntry::Type::KEY: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002291 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002292 dispatchEntry->resolvedEventId = keyEntry.id;
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002293 dispatchEntry->resolvedAction = keyEntry.action;
2294 dispatchEntry->resolvedFlags = keyEntry.flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002296 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2297 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002299 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2300 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002302 return; // skip the inconsistent event
2303 }
2304 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002307 case EventEntry::Type::MOTION: {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002308 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(*newEntry);
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002309 // Assign a default value to dispatchEntry that will never be generated by InputReader,
2310 // and assign a InputDispatcher value if it doesn't change in the if-else chain below.
2311 constexpr int32_t DEFAULT_RESOLVED_EVENT_ID =
2312 static_cast<int32_t>(IdGenerator::Source::OTHER);
2313 dispatchEntry->resolvedEventId = DEFAULT_RESOLVED_EVENT_ID;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002314 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2315 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2316 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2317 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2318 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2319 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2320 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2321 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2322 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2323 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2324 } else {
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002325 dispatchEntry->resolvedAction = motionEntry.action;
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002326 dispatchEntry->resolvedEventId = motionEntry.id;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002327 }
2328 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002329 !connection->inputState.isHovering(motionEntry.deviceId, motionEntry.source,
2330 motionEntry.displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002332 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2333 "event",
2334 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002336 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002338
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002339 dispatchEntry->resolvedFlags = motionEntry.flags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002340 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2341 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2342 }
2343 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2344 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002347 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2348 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002350 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2351 "event",
2352 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002354 return; // skip the inconsistent event
2355 }
2356
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002357 dispatchEntry->resolvedEventId =
2358 dispatchEntry->resolvedEventId == DEFAULT_RESOLVED_EVENT_ID
2359 ? mIdGenerator.nextId()
2360 : motionEntry.id;
2361 if (ATRACE_ENABLED() && dispatchEntry->resolvedEventId != motionEntry.id) {
2362 std::string message = StringPrintf("Transmute MotionEvent(id=0x%" PRIx32
2363 ") to MotionEvent(id=0x%" PRIx32 ").",
2364 motionEntry.id, dispatchEntry->resolvedEventId);
2365 ATRACE_NAME(message.c_str());
2366 }
2367
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002368 dispatchPointerDownOutsideFocus(motionEntry.source, dispatchEntry->resolvedAction,
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002369 inputTarget.inputChannel->getConnectionToken());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002370
2371 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002373 case EventEntry::Type::FOCUS: {
2374 break;
2375 }
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002376 case EventEntry::Type::CONFIGURATION_CHANGED:
2377 case EventEntry::Type::DEVICE_RESET: {
2378 LOG_ALWAYS_FATAL("%s events should not go to apps",
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002379 EventEntry::typeToString(newEntry->type));
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002380 break;
2381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382 }
2383
2384 // Remember that we are waiting for this dispatch to complete.
2385 if (dispatchEntry->hasForegroundTarget()) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002386 incrementPendingForegroundDispatches(newEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 }
2388
2389 // Enqueue the dispatch entry.
Siarhei Vishniakou5d6b6612020-01-08 16:03:04 -08002390 connection->outboundQueue.push_back(dispatchEntry.release());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002391 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002392}
2393
Siarhei Vishniakou887b7d92020-06-18 00:43:02 +00002394/**
2395 * This function is purely for debugging. It helps us understand where the user interaction
2396 * was taking place. For example, if user is touching launcher, we will see a log that user
2397 * started interacting with launcher. In that example, the event would go to the wallpaper as well.
2398 * We will see both launcher and wallpaper in that list.
2399 * Once the interaction with a particular set of connections starts, no new logs will be printed
2400 * until the set of interacted connections changes.
2401 *
2402 * The following items are skipped, to reduce the logspam:
2403 * ACTION_OUTSIDE: any windows that are receiving ACTION_OUTSIDE are not logged
2404 * ACTION_UP: any windows that receive ACTION_UP are not logged (for both keys and motions).
2405 * This includes situations like the soft BACK button key. When the user releases (lifts up the
2406 * finger) the back button, then navigation bar will inject KEYCODE_BACK with ACTION_UP.
2407 * Both of those ACTION_UP events would not be logged
2408 * Monitors (both gesture and global): any gesture monitors or global monitors receiving events
2409 * will not be logged. This is omitted to reduce the amount of data printed.
2410 * If you see <none>, it's likely that one of the gesture monitors pilfered the event, and therefore
2411 * gesture monitor is the only connection receiving the remainder of the gesture.
2412 */
2413void InputDispatcher::updateInteractionTokensLocked(const EventEntry& entry,
2414 const std::vector<InputTarget>& targets) {
2415 // Skip ACTION_UP events, and all events other than keys and motions
2416 if (entry.type == EventEntry::Type::KEY) {
2417 const KeyEntry& keyEntry = static_cast<const KeyEntry&>(entry);
2418 if (keyEntry.action == AKEY_EVENT_ACTION_UP) {
2419 return;
2420 }
2421 } else if (entry.type == EventEntry::Type::MOTION) {
2422 const MotionEntry& motionEntry = static_cast<const MotionEntry&>(entry);
2423 if (motionEntry.action == AMOTION_EVENT_ACTION_UP ||
2424 motionEntry.action == AMOTION_EVENT_ACTION_CANCEL) {
2425 return;
2426 }
2427 } else {
2428 return; // Not a key or a motion
2429 }
2430
2431 std::unordered_set<sp<IBinder>, IBinderHash> newConnectionTokens;
2432 std::vector<sp<Connection>> newConnections;
2433 for (const InputTarget& target : targets) {
2434 if ((target.flags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) ==
2435 InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2436 continue; // Skip windows that receive ACTION_OUTSIDE
2437 }
2438
2439 sp<IBinder> token = target.inputChannel->getConnectionToken();
2440 sp<Connection> connection = getConnectionLocked(token);
2441 if (connection == nullptr || connection->monitor) {
2442 continue; // We only need to keep track of the non-monitor connections.
2443 }
2444 newConnectionTokens.insert(std::move(token));
2445 newConnections.emplace_back(connection);
2446 }
2447 if (newConnectionTokens == mInteractionConnectionTokens) {
2448 return; // no change
2449 }
2450 mInteractionConnectionTokens = newConnectionTokens;
2451
2452 std::string windowList;
2453 for (const sp<Connection>& connection : newConnections) {
2454 windowList += connection->getWindowName() + ", ";
2455 }
2456 std::string message = "Interaction with windows: " + windowList;
2457 if (windowList.empty()) {
2458 message += "<none>";
2459 }
2460 android_log_event_list(LOGTAG_INPUT_INTERACTION) << message << LOG_ID_EVENTS;
2461}
2462
chaviwfd6d3512019-03-25 13:23:49 -07002463void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002464 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002465 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002466 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2467 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002468 return;
2469 }
2470
2471 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2472 if (inputWindowHandle == nullptr) {
2473 return;
2474 }
2475
chaviw8c9cf542019-03-25 13:02:48 -07002476 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002477 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002478
2479 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2480
2481 if (!hasFocusChanged) {
2482 return;
2483 }
2484
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002485 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2486 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002487 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002488 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489}
2490
2491void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002492 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002493 if (ATRACE_ENABLED()) {
2494 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002495 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002496 ATRACE_NAME(message.c_str());
2497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002499 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500#endif
2501
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002502 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2503 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 dispatchEntry->deliveryTime = currentTime;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002505 const std::chrono::nanoseconds timeout =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002506 getDispatchingTimeoutLocked(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou70622952020-07-30 11:17:23 -05002507 dispatchEntry->timeoutTime = currentTime + timeout.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508
2509 // Publish the event.
2510 status_t status;
2511 EventEntry* eventEntry = dispatchEntry->eventEntry;
2512 switch (eventEntry->type) {
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002513 case EventEntry::Type::KEY: {
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002514 const KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2515 std::array<uint8_t, 32> hmac = getSignature(*keyEntry, *dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002517 // Publish the key event.
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002518 status =
2519 connection->inputPublisher
2520 .publishKeyEvent(dispatchEntry->seq, dispatchEntry->resolvedEventId,
2521 keyEntry->deviceId, keyEntry->source,
2522 keyEntry->displayId, std::move(hmac),
2523 dispatchEntry->resolvedAction,
2524 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2525 keyEntry->scanCode, keyEntry->metaState,
2526 keyEntry->repeatCount, keyEntry->downTime,
2527 keyEntry->eventTime);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002528 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 }
2530
Siarhei Vishniakou49483272019-10-22 13:13:47 -07002531 case EventEntry::Type::MOTION: {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002532 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002534 PointerCoords scaledCoords[MAX_POINTERS];
2535 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2536
chaviw82357092020-01-28 13:13:06 -08002537 // Set the X and Y offset and X and Y scale depending on the input source.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002538 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2539 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2540 float globalScaleFactor = dispatchEntry->globalScaleFactor;
chaviw82357092020-01-28 13:13:06 -08002541 if (globalScaleFactor != 1.0f) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002542 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2543 scaledCoords[i] = motionEntry->pointerCoords[i];
chaviw82357092020-01-28 13:13:06 -08002544 // Don't apply window scale here since we don't want scale to affect raw
2545 // coordinates. The scale will be sent back to the client and applied
2546 // later when requesting relative coordinates.
2547 scaledCoords[i].scale(globalScaleFactor, 1 /* windowXScale */,
2548 1 /* windowYScale */);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002549 }
2550 usingCoords = scaledCoords;
2551 }
2552 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002553 // We don't want the dispatch target to know.
2554 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2555 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2556 scaledCoords[i].clear();
2557 }
2558 usingCoords = scaledCoords;
2559 }
2560 }
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002561
2562 std::array<uint8_t, 32> hmac = getSignature(*motionEntry, *dispatchEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002563
2564 // Publish the motion event.
2565 status = connection->inputPublisher
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002566 .publishMotionEvent(dispatchEntry->seq,
2567 dispatchEntry->resolvedEventId,
2568 motionEntry->deviceId, motionEntry->source,
2569 motionEntry->displayId, std::move(hmac),
2570 dispatchEntry->resolvedAction,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002571 motionEntry->actionButton,
2572 dispatchEntry->resolvedFlags,
2573 motionEntry->edgeFlags, motionEntry->metaState,
2574 motionEntry->buttonState,
chaviw1ff3d1e2020-07-01 15:53:47 -07002575 motionEntry->classification,
chaviw9eaa22c2020-07-01 16:21:27 -07002576 dispatchEntry->transform,
chaviw1ff3d1e2020-07-01 15:53:47 -07002577 motionEntry->xPrecision,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002578 motionEntry->yPrecision,
2579 motionEntry->xCursorPosition,
2580 motionEntry->yCursorPosition,
2581 motionEntry->downTime, motionEntry->eventTime,
2582 motionEntry->pointerCount,
2583 motionEntry->pointerProperties, usingCoords);
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05002584 reportTouchEventForStatistics(*motionEntry);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002585 break;
2586 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002587 case EventEntry::Type::FOCUS: {
2588 FocusEntry* focusEntry = static_cast<FocusEntry*>(eventEntry);
2589 status = connection->inputPublisher.publishFocusEvent(dispatchEntry->seq,
Garfield Tanff1f1bb2020-01-28 13:24:04 -08002590 focusEntry->id,
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002591 focusEntry->hasFocus,
2592 mInTouchMode);
2593 break;
2594 }
2595
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002596 case EventEntry::Type::CONFIGURATION_CHANGED:
2597 case EventEntry::Type::DEVICE_RESET: {
2598 LOG_ALWAYS_FATAL("Should never start dispatch cycles for %s events",
2599 EventEntry::typeToString(eventEntry->type));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002600 return;
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -08002601 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 }
2603
2604 // Check the result.
2605 if (status) {
2606 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002607 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002608 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002609 "This is unexpected because the wait queue is empty, so the pipe "
2610 "should be empty and we shouldn't have any problems writing an "
2611 "event to it, status=%d",
2612 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002613 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2614 } else {
2615 // Pipe is full and we are waiting for the app to finish process some events
2616 // before sending more events to it.
2617#if DEBUG_DISPATCH_CYCLE
2618 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002619 "waiting for the application to catch up",
2620 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08002622 }
2623 } else {
2624 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002625 "status=%d",
2626 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2628 }
2629 return;
2630 }
2631
2632 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002633 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2634 connection->outboundQueue.end(),
2635 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002636 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002637 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002638 if (connection->responsive) {
2639 mAnrTracker.insert(dispatchEntry->timeoutTime,
2640 connection->inputChannel->getConnectionToken());
2641 }
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002642 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 }
2644}
2645
chaviw09c8d2d2020-08-24 15:48:26 -07002646std::array<uint8_t, 32> InputDispatcher::sign(const VerifiedInputEvent& event) const {
2647 size_t size;
2648 switch (event.type) {
2649 case VerifiedInputEvent::Type::KEY: {
2650 size = sizeof(VerifiedKeyEvent);
2651 break;
2652 }
2653 case VerifiedInputEvent::Type::MOTION: {
2654 size = sizeof(VerifiedMotionEvent);
2655 break;
2656 }
2657 }
2658 const uint8_t* start = reinterpret_cast<const uint8_t*>(&event);
2659 return mHmacKeyManager.sign(start, size);
2660}
2661
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002662const std::array<uint8_t, 32> InputDispatcher::getSignature(
2663 const MotionEntry& motionEntry, const DispatchEntry& dispatchEntry) const {
2664 int32_t actionMasked = dispatchEntry.resolvedAction & AMOTION_EVENT_ACTION_MASK;
2665 if ((actionMasked == AMOTION_EVENT_ACTION_UP) || (actionMasked == AMOTION_EVENT_ACTION_DOWN)) {
2666 // Only sign events up and down events as the purely move events
2667 // are tied to their up/down counterparts so signing would be redundant.
2668 VerifiedMotionEvent verifiedEvent = verifiedMotionEventFromMotionEntry(motionEntry);
2669 verifiedEvent.actionMasked = actionMasked;
2670 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_MOTION_EVENT_FLAGS;
chaviw09c8d2d2020-08-24 15:48:26 -07002671 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002672 }
2673 return INVALID_HMAC;
2674}
2675
2676const std::array<uint8_t, 32> InputDispatcher::getSignature(
2677 const KeyEntry& keyEntry, const DispatchEntry& dispatchEntry) const {
2678 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEntry(keyEntry);
2679 verifiedEvent.flags = dispatchEntry.resolvedFlags & VERIFIED_KEY_EVENT_FLAGS;
2680 verifiedEvent.action = dispatchEntry.resolvedAction;
chaviw09c8d2d2020-08-24 15:48:26 -07002681 return sign(verifiedEvent);
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -07002682}
2683
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002685 const sp<Connection>& connection, uint32_t seq,
2686 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687#if DEBUG_DISPATCH_CYCLE
2688 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002689 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690#endif
2691
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002692 if (connection->status == Connection::STATUS_BROKEN ||
2693 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 return;
2695 }
2696
2697 // Notify other system components and prepare to start the next dispatch cycle.
2698 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2699}
2700
2701void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002702 const sp<Connection>& connection,
2703 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704#if DEBUG_DISPATCH_CYCLE
2705 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002706 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707#endif
2708
2709 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002710 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002711 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002712 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002713 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714
2715 // The connection appears to be unrecoverably broken.
2716 // Ignore already broken or zombie connections.
2717 if (connection->status == Connection::STATUS_NORMAL) {
2718 connection->status = Connection::STATUS_BROKEN;
2719
2720 if (notify) {
2721 // Notify other system components.
2722 onDispatchCycleBrokenLocked(currentTime, connection);
2723 }
2724 }
2725}
2726
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002727void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2728 while (!queue.empty()) {
2729 DispatchEntry* dispatchEntry = queue.front();
2730 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002731 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732 }
2733}
2734
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002735void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002737 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738 }
2739 delete dispatchEntry;
2740}
2741
2742int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2743 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2744
2745 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002746 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002748 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002750 "fd=%d, events=0x%x",
2751 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 return 0; // remove the callback
2753 }
2754
2755 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002756 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2758 if (!(events & ALOOPER_EVENT_INPUT)) {
2759 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002760 "events=0x%x",
2761 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 return 1;
2763 }
2764
2765 nsecs_t currentTime = now();
2766 bool gotOne = false;
2767 status_t status;
2768 for (;;) {
2769 uint32_t seq;
2770 bool handled;
2771 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2772 if (status) {
2773 break;
2774 }
2775 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2776 gotOne = true;
2777 }
2778 if (gotOne) {
2779 d->runCommandsLockedInterruptible();
2780 if (status == WOULD_BLOCK) {
2781 return 1;
2782 }
2783 }
2784
2785 notify = status != DEAD_OBJECT || !connection->monitor;
2786 if (notify) {
2787 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002788 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789 }
2790 } else {
2791 // Monitor channels are never explicitly unregistered.
2792 // We do it automatically when the remote endpoint is closed so don't warn
2793 // about them.
arthurhungd352cb32020-04-28 17:09:28 +08002794 const bool stillHaveWindowHandle =
2795 d->getWindowHandleLocked(connection->inputChannel->getConnectionToken()) !=
2796 nullptr;
2797 notify = !connection->monitor && stillHaveWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798 if (notify) {
2799 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002800 "events=0x%x",
2801 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802 }
2803 }
2804
2805 // Unregister the channel.
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002806 d->unregisterInputChannelLocked(*connection->inputChannel, notify);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002808 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809}
2810
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002811void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002813 for (const auto& pair : mConnectionsByFd) {
2814 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 }
2816}
2817
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002818void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002819 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002820 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2821 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2822}
2823
2824void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2825 const CancelationOptions& options,
2826 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2827 for (const auto& it : monitorsByDisplay) {
2828 const std::vector<Monitor>& monitors = it.second;
2829 for (const Monitor& monitor : monitors) {
2830 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002831 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002832 }
2833}
2834
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05002836 const std::shared_ptr<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07002837 sp<Connection> connection = getConnectionLocked(channel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002838 if (connection == nullptr) {
2839 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002841
2842 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843}
2844
2845void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2846 const sp<Connection>& connection, const CancelationOptions& options) {
2847 if (connection->status == Connection::STATUS_BROKEN) {
2848 return;
2849 }
2850
2851 nsecs_t currentTime = now();
2852
Siarhei Vishniakou00fca7c2019-10-29 13:05:57 -07002853 std::vector<EventEntry*> cancelationEvents =
2854 connection->inputState.synthesizeCancelationEvents(currentTime, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002856 if (cancelationEvents.empty()) {
2857 return;
2858 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002860 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
2861 "with reality: %s, mode=%d.",
2862 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2863 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864#endif
Svet Ganov5d3bc372020-01-26 23:11:07 -08002865
2866 InputTarget target;
2867 sp<InputWindowHandle> windowHandle =
2868 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2869 if (windowHandle != nullptr) {
2870 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002871 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002872 target.globalScaleFactor = windowInfo->globalScaleFactor;
2873 }
2874 target.inputChannel = connection->inputChannel;
2875 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2876
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002877 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2878 EventEntry* cancelationEventEntry = cancelationEvents[i];
2879 switch (cancelationEventEntry->type) {
2880 case EventEntry::Type::KEY: {
2881 logOutboundKeyDetails("cancel - ",
2882 static_cast<const KeyEntry&>(*cancelationEventEntry));
2883 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002885 case EventEntry::Type::MOTION: {
2886 logOutboundMotionDetails("cancel - ",
2887 static_cast<const MotionEntry&>(*cancelationEventEntry));
2888 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002890 case EventEntry::Type::FOCUS: {
2891 LOG_ALWAYS_FATAL("Canceling focus events is not supported");
2892 break;
2893 }
2894 case EventEntry::Type::CONFIGURATION_CHANGED:
2895 case EventEntry::Type::DEVICE_RESET: {
2896 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2897 EventEntry::typeToString(cancelationEventEntry->type));
2898 break;
2899 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 }
2901
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002902 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2903 target, InputTarget::FLAG_DISPATCH_AS_IS);
2904
2905 cancelationEventEntry->release();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 }
Siarhei Vishniakoubd118892020-01-10 14:08:28 -08002907
2908 startDispatchCycleLocked(currentTime, connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909}
2910
Svet Ganov5d3bc372020-01-26 23:11:07 -08002911void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
2912 const sp<Connection>& connection) {
2913 if (connection->status == Connection::STATUS_BROKEN) {
2914 return;
2915 }
2916
2917 nsecs_t currentTime = now();
2918
2919 std::vector<EventEntry*> downEvents =
2920 connection->inputState.synthesizePointerDownEvents(currentTime);
2921
2922 if (downEvents.empty()) {
2923 return;
2924 }
2925
2926#if DEBUG_OUTBOUND_EVENT_DETAILS
2927 ALOGD("channel '%s' ~ Synthesized %zu down events to ensure consistent event stream.",
2928 connection->getInputChannelName().c_str(), downEvents.size());
2929#endif
2930
2931 InputTarget target;
2932 sp<InputWindowHandle> windowHandle =
2933 getWindowHandleLocked(connection->inputChannel->getConnectionToken());
2934 if (windowHandle != nullptr) {
2935 const InputWindowInfo* windowInfo = windowHandle->getInfo();
chaviw1ff3d1e2020-07-01 15:53:47 -07002936 target.setDefaultPointerTransform(windowInfo->transform);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002937 target.globalScaleFactor = windowInfo->globalScaleFactor;
2938 }
2939 target.inputChannel = connection->inputChannel;
2940 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2941
2942 for (EventEntry* downEventEntry : downEvents) {
2943 switch (downEventEntry->type) {
2944 case EventEntry::Type::MOTION: {
2945 logOutboundMotionDetails("down - ",
2946 static_cast<const MotionEntry&>(*downEventEntry));
2947 break;
2948 }
2949
2950 case EventEntry::Type::KEY:
2951 case EventEntry::Type::FOCUS:
2952 case EventEntry::Type::CONFIGURATION_CHANGED:
2953 case EventEntry::Type::DEVICE_RESET: {
2954 LOG_ALWAYS_FATAL("%s event should not be found inside Connections's queue",
2955 EventEntry::typeToString(downEventEntry->type));
2956 break;
2957 }
2958 }
2959
2960 enqueueDispatchEntryLocked(connection, downEventEntry, // increments ref
2961 target, InputTarget::FLAG_DISPATCH_AS_IS);
2962
2963 downEventEntry->release();
2964 }
2965
2966 startDispatchCycleLocked(currentTime, connection);
2967}
2968
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002969MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry& originalMotionEntry,
Garfield Tane84e6f92019-08-29 17:28:41 -07002970 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971 ALOG_ASSERT(pointerIds.value != 0);
2972
2973 uint32_t splitPointerIndexMap[MAX_POINTERS];
2974 PointerProperties splitPointerProperties[MAX_POINTERS];
2975 PointerCoords splitPointerCoords[MAX_POINTERS];
2976
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002977 uint32_t originalPointerCount = originalMotionEntry.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978 uint32_t splitPointerCount = 0;
2979
2980 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002981 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002982 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002983 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002984 uint32_t pointerId = uint32_t(pointerProperties.id);
2985 if (pointerIds.hasBit(pointerId)) {
2986 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2987 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2988 splitPointerCoords[splitPointerCount].copyFrom(
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07002989 originalMotionEntry.pointerCoords[originalPointerIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990 splitPointerCount += 1;
2991 }
2992 }
2993
2994 if (splitPointerCount != pointerIds.count()) {
2995 // This is bad. We are missing some of the pointers that we expected to deliver.
2996 // Most likely this indicates that we received an ACTION_MOVE events that has
2997 // different pointer ids than we expected based on the previous ACTION_DOWN
2998 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2999 // in this way.
3000 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003001 "we expected there to be %d pointers. This probably means we received "
3002 "a broken sequence of pointer ids from the input device.",
3003 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07003004 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 }
3006
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003007 int32_t action = originalMotionEntry.action;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003008 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003009 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
3010 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
3012 const PointerProperties& pointerProperties =
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003013 originalMotionEntry.pointerProperties[originalPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014 uint32_t pointerId = uint32_t(pointerProperties.id);
3015 if (pointerIds.hasBit(pointerId)) {
3016 if (pointerIds.count() == 1) {
3017 // The first/last pointer went down/up.
3018 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003019 ? AMOTION_EVENT_ACTION_DOWN
3020 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021 } else {
3022 // A secondary pointer went down/up.
3023 uint32_t splitPointerIndex = 0;
3024 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
3025 splitPointerIndex += 1;
3026 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003027 action = maskedAction |
3028 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 }
3030 } else {
3031 // An unrelated pointer changed.
3032 action = AMOTION_EVENT_ACTION_MOVE;
3033 }
3034 }
3035
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003036 int32_t newId = mIdGenerator.nextId();
3037 if (ATRACE_ENABLED()) {
3038 std::string message = StringPrintf("Split MotionEvent(id=0x%" PRIx32
3039 ") to MotionEvent(id=0x%" PRIx32 ").",
3040 originalMotionEntry.id, newId);
3041 ATRACE_NAME(message.c_str());
3042 }
Garfield Tan00f511d2019-06-12 16:55:40 -07003043 MotionEntry* splitMotionEntry =
Garfield Tanff1f1bb2020-01-28 13:24:04 -08003044 new MotionEntry(newId, originalMotionEntry.eventTime, originalMotionEntry.deviceId,
3045 originalMotionEntry.source, originalMotionEntry.displayId,
3046 originalMotionEntry.policyFlags, action,
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003047 originalMotionEntry.actionButton, originalMotionEntry.flags,
3048 originalMotionEntry.metaState, originalMotionEntry.buttonState,
3049 originalMotionEntry.classification, originalMotionEntry.edgeFlags,
3050 originalMotionEntry.xPrecision, originalMotionEntry.yPrecision,
3051 originalMotionEntry.xCursorPosition,
3052 originalMotionEntry.yCursorPosition, originalMotionEntry.downTime,
Garfield Tan00f511d2019-06-12 16:55:40 -07003053 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054
Siarhei Vishniakoud2770042019-10-29 11:08:14 -07003055 if (originalMotionEntry.injectionState) {
3056 splitMotionEntry->injectionState = originalMotionEntry.injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057 splitMotionEntry->injectionState->refCount += 1;
3058 }
3059
3060 return splitMotionEntry;
3061}
3062
3063void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
3064#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003065 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066#endif
3067
3068 bool needWake;
3069 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003070 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071
Prabir Pradhan42611e02018-11-27 14:04:02 -08003072 ConfigurationChangedEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003073 new ConfigurationChangedEntry(args->id, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074 needWake = enqueueInboundEventLocked(newEntry);
3075 } // release lock
3076
3077 if (needWake) {
3078 mLooper->wake();
3079 }
3080}
3081
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003082/**
3083 * If one of the meta shortcuts is detected, process them here:
3084 * Meta + Backspace -> generate BACK
3085 * Meta + Enter -> generate HOME
3086 * This will potentially overwrite keyCode and metaState.
3087 */
3088void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003089 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003090 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
3091 int32_t newKeyCode = AKEYCODE_UNKNOWN;
3092 if (keyCode == AKEYCODE_DEL) {
3093 newKeyCode = AKEYCODE_BACK;
3094 } else if (keyCode == AKEYCODE_ENTER) {
3095 newKeyCode = AKEYCODE_HOME;
3096 }
3097 if (newKeyCode != AKEYCODE_UNKNOWN) {
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 mReplacedKeys[replacement] = newKeyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003101 keyCode = newKeyCode;
3102 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3103 }
3104 } else if (action == AKEY_EVENT_ACTION_UP) {
3105 // In order to maintain a consistent stream of up and down events, check to see if the key
3106 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
3107 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003108 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003109 struct KeyReplacement replacement = {keyCode, deviceId};
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003110 auto replacementIt = mReplacedKeys.find(replacement);
3111 if (replacementIt != mReplacedKeys.end()) {
3112 keyCode = replacementIt->second;
3113 mReplacedKeys.erase(replacementIt);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003114 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
3115 }
3116 }
3117}
3118
Michael Wrightd02c5b62014-02-10 15:10:22 -08003119void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
3120#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003121 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
3122 "policyFlags=0x%x, action=0x%x, "
3123 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
3124 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
3125 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
3126 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127#endif
3128 if (!validateKeyEvent(args->action)) {
3129 return;
3130 }
3131
3132 uint32_t policyFlags = args->policyFlags;
3133 int32_t flags = args->flags;
3134 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07003135 // InputDispatcher tracks and generates key repeats on behalf of
3136 // whatever notifies it, so repeatCount should always be set to 0
3137 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
3139 policyFlags |= POLICY_FLAG_VIRTUAL;
3140 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3141 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 if (policyFlags & POLICY_FLAG_FUNCTION) {
3143 metaState |= AMETA_FUNCTION_ON;
3144 }
3145
3146 policyFlags |= POLICY_FLAG_TRUSTED;
3147
Michael Wright78f24442014-08-06 15:55:28 -07003148 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05003149 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07003150
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003152 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08003153 args->action, flags, keyCode, args->scanCode, metaState, repeatCount,
3154 args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155
Michael Wright2b3c3302018-03-02 17:19:13 +00003156 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003158 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3159 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003160 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003161 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 bool needWake;
3164 { // acquire lock
3165 mLock.lock();
3166
3167 if (shouldSendKeyToInputFilterLocked(args)) {
3168 mLock.unlock();
3169
3170 policyFlags |= POLICY_FLAG_FILTERED;
3171 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3172 return; // event was consumed by the filter
3173 }
3174
3175 mLock.lock();
3176 }
3177
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003178 KeyEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003179 new KeyEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003180 args->displayId, policyFlags, args->action, flags, keyCode,
3181 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182
3183 needWake = enqueueInboundEventLocked(newEntry);
3184 mLock.unlock();
3185 } // release lock
3186
3187 if (needWake) {
3188 mLooper->wake();
3189 }
3190}
3191
3192bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
3193 return mInputFilterEnabled;
3194}
3195
3196void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
3197#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003198 ALOGD("notifyMotion - id=%" PRIx32 " eventTime=%" PRId64 ", deviceId=%d, source=0x%x, "
3199 "displayId=%" PRId32 ", policyFlags=0x%x, "
Garfield Tan00f511d2019-06-12 16:55:40 -07003200 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
3201 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07003202 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003203 args->id, args->eventTime, args->deviceId, args->source, args->displayId,
3204 args->policyFlags, args->action, args->actionButton, args->flags, args->metaState,
3205 args->buttonState, args->edgeFlags, args->xPrecision, args->yPrecision,
3206 args->xCursorPosition, args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 for (uint32_t i = 0; i < args->pointerCount; i++) {
3208 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003209 "x=%f, y=%f, pressure=%f, size=%f, "
3210 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
3211 "orientation=%f",
3212 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
3213 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
3214 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
3215 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3216 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
3217 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3218 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3219 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3220 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3221 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 }
3223#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003224 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
3225 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 return;
3227 }
3228
3229 uint32_t policyFlags = args->policyFlags;
3230 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003231
3232 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08003233 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003234 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3235 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003236 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00003237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238
3239 bool needWake;
3240 { // acquire lock
3241 mLock.lock();
3242
3243 if (shouldSendMotionToInputFilterLocked(args)) {
3244 mLock.unlock();
3245
3246 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07003247 ui::Transform transform;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003248 event.initialize(args->id, args->deviceId, args->source, args->displayId, INVALID_HMAC,
3249 args->action, args->actionButton, args->flags, args->edgeFlags,
chaviw9eaa22c2020-07-01 16:21:27 -07003250 args->metaState, args->buttonState, args->classification, transform,
3251 args->xPrecision, args->yPrecision, args->xCursorPosition,
3252 args->yCursorPosition, args->downTime, args->eventTime,
3253 args->pointerCount, args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254
3255 policyFlags |= POLICY_FLAG_FILTERED;
3256 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
3257 return; // event was consumed by the filter
3258 }
3259
3260 mLock.lock();
3261 }
3262
3263 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07003264 MotionEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003265 new MotionEntry(args->id, args->eventTime, args->deviceId, args->source,
Garfield Tan00f511d2019-06-12 16:55:40 -07003266 args->displayId, policyFlags, args->action, args->actionButton,
3267 args->flags, args->metaState, args->buttonState,
3268 args->classification, args->edgeFlags, args->xPrecision,
3269 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
3270 args->downTime, args->pointerCount, args->pointerProperties,
3271 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272
3273 needWake = enqueueInboundEventLocked(newEntry);
3274 mLock.unlock();
3275 } // release lock
3276
3277 if (needWake) {
3278 mLooper->wake();
3279 }
3280}
3281
3282bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08003283 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284}
3285
3286void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
3287#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003288 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003289 "switchMask=0x%08x",
3290 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291#endif
3292
3293 uint32_t policyFlags = args->policyFlags;
3294 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003295 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296}
3297
3298void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
3299#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003300 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
3301 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302#endif
3303
3304 bool needWake;
3305 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003306 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307
Prabir Pradhan42611e02018-11-27 14:04:02 -08003308 DeviceResetEntry* newEntry =
Garfield Tan6a5a14e2020-01-28 13:24:04 -08003309 new DeviceResetEntry(args->id, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 needWake = enqueueInboundEventLocked(newEntry);
3311 } // release lock
3312
3313 if (needWake) {
3314 mLooper->wake();
3315 }
3316}
3317
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
3319 int32_t injectorUid, int32_t syncMode,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003320 std::chrono::milliseconds timeout, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321#if DEBUG_INBOUND_EVENT_DETAILS
3322 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003323 "syncMode=%d, timeout=%lld, policyFlags=0x%08x",
3324 event->getType(), injectorPid, injectorUid, syncMode, timeout.count(), policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325#endif
3326
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003327 nsecs_t endTime = now() + std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328
3329 policyFlags |= POLICY_FLAG_INJECTED;
3330 if (hasInjectionPermission(injectorPid, injectorUid)) {
3331 policyFlags |= POLICY_FLAG_TRUSTED;
3332 }
3333
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003334 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003336 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003337 const KeyEvent& incomingKey = static_cast<const KeyEvent&>(*event);
3338 int32_t action = incomingKey.getAction();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003339 if (!validateKeyEvent(action)) {
3340 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00003341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003343 int32_t flags = incomingKey.getFlags();
3344 int32_t keyCode = incomingKey.getKeyCode();
3345 int32_t metaState = incomingKey.getMetaState();
3346 accelerateMetaShortcuts(VIRTUAL_KEYBOARD_ID, action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003347 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003348 KeyEvent keyEvent;
Garfield Tan4cc839f2020-01-24 11:26:14 -08003349 keyEvent.initialize(incomingKey.getId(), VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003350 incomingKey.getDisplayId(), INVALID_HMAC, action, flags, keyCode,
3351 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
3352 incomingKey.getDownTime(), incomingKey.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003354 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
3355 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00003356 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003357
3358 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3359 android::base::Timer t;
3360 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
3361 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3362 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
3363 std::to_string(t.duration().count()).c_str());
3364 }
3365 }
3366
3367 mLock.lock();
3368 KeyEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003369 new KeyEntry(incomingKey.getId(), incomingKey.getEventTime(),
3370 VIRTUAL_KEYBOARD_ID, incomingKey.getSource(),
arthurhungb1462ec2020-04-20 17:18:37 +08003371 incomingKey.getDisplayId(), policyFlags, action, flags, keyCode,
3372 incomingKey.getScanCode(), metaState, incomingKey.getRepeatCount(),
Garfield Tan4cc839f2020-01-24 11:26:14 -08003373 incomingKey.getDownTime());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003374 injectedEntries.push(injectedEntry);
3375 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 }
3377
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003378 case AINPUT_EVENT_TYPE_MOTION: {
3379 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
3380 int32_t action = motionEvent->getAction();
3381 size_t pointerCount = motionEvent->getPointerCount();
3382 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
3383 int32_t actionButton = motionEvent->getActionButton();
3384 int32_t displayId = motionEvent->getDisplayId();
3385 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
3386 return INPUT_EVENT_INJECTION_FAILED;
3387 }
3388
3389 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
3390 nsecs_t eventTime = motionEvent->getEventTime();
3391 android::base::Timer t;
3392 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
3393 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3394 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
3395 std::to_string(t.duration().count()).c_str());
3396 }
3397 }
3398
3399 mLock.lock();
3400 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
3401 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
3402 MotionEntry* injectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003403 new MotionEntry(motionEvent->getId(), *sampleEventTimes, VIRTUAL_KEYBOARD_ID,
3404 motionEvent->getSource(), motionEvent->getDisplayId(),
3405 policyFlags, action, actionButton, motionEvent->getFlags(),
3406 motionEvent->getMetaState(), motionEvent->getButtonState(),
3407 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
3408 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Garfield Tan00f511d2019-06-12 16:55:40 -07003409 motionEvent->getRawXCursorPosition(),
3410 motionEvent->getRawYCursorPosition(),
3411 motionEvent->getDownTime(), uint32_t(pointerCount),
3412 pointerProperties, samplePointerCoords,
3413 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003414 injectedEntries.push(injectedEntry);
3415 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
3416 sampleEventTimes += 1;
3417 samplePointerCoords += pointerCount;
3418 MotionEntry* nextInjectedEntry =
Garfield Tan4cc839f2020-01-24 11:26:14 -08003419 new MotionEntry(motionEvent->getId(), *sampleEventTimes,
Siarhei Vishniakou0d8ed6e2020-01-17 15:48:59 -08003420 VIRTUAL_KEYBOARD_ID, motionEvent->getSource(),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003421 motionEvent->getDisplayId(), policyFlags, action,
3422 actionButton, motionEvent->getFlags(),
3423 motionEvent->getMetaState(), motionEvent->getButtonState(),
3424 motionEvent->getClassification(),
3425 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
3426 motionEvent->getYPrecision(),
3427 motionEvent->getRawXCursorPosition(),
3428 motionEvent->getRawYCursorPosition(),
3429 motionEvent->getDownTime(), uint32_t(pointerCount),
3430 pointerProperties, samplePointerCoords,
3431 motionEvent->getXOffset(), motionEvent->getYOffset());
3432 injectedEntries.push(nextInjectedEntry);
3433 }
3434 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003437 default:
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08003438 ALOGW("Cannot inject %s events", inputEventTypeToString(event->getType()));
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003439 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 }
3441
3442 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3443 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3444 injectionState->injectionIsAsync = true;
3445 }
3446
3447 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003448 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449
3450 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003451 while (!injectedEntries.empty()) {
3452 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3453 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454 }
3455
3456 mLock.unlock();
3457
3458 if (needWake) {
3459 mLooper->wake();
3460 }
3461
3462 int32_t injectionResult;
3463 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003464 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465
3466 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3467 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3468 } else {
3469 for (;;) {
3470 injectionResult = injectionState->injectionResult;
3471 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3472 break;
3473 }
3474
3475 nsecs_t remainingTimeout = endTime - now();
3476 if (remainingTimeout <= 0) {
3477#if DEBUG_INJECTION
3478 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003479 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480#endif
3481 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3482 break;
3483 }
3484
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003485 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 }
3487
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003488 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3489 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 while (injectionState->pendingForegroundDispatches != 0) {
3491#if DEBUG_INJECTION
3492 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003493 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494#endif
3495 nsecs_t remainingTimeout = endTime - now();
3496 if (remainingTimeout <= 0) {
3497#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003498 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3499 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500#endif
3501 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3502 break;
3503 }
3504
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003505 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 }
3507 }
3508 }
3509
3510 injectionState->release();
3511 } // release lock
3512
3513#if DEBUG_INJECTION
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -07003514 ALOGD("injectInputEvent - Finished with result %d. injectorPid=%d, injectorUid=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003515 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516#endif
3517
3518 return injectionResult;
3519}
3520
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003521std::unique_ptr<VerifiedInputEvent> InputDispatcher::verifyInputEvent(const InputEvent& event) {
Gang Wange9087892020-01-07 12:17:14 -05003522 std::array<uint8_t, 32> calculatedHmac;
3523 std::unique_ptr<VerifiedInputEvent> result;
3524 switch (event.getType()) {
3525 case AINPUT_EVENT_TYPE_KEY: {
3526 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(event);
3527 VerifiedKeyEvent verifiedKeyEvent = verifiedKeyEventFromKeyEvent(keyEvent);
3528 result = std::make_unique<VerifiedKeyEvent>(verifiedKeyEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003529 calculatedHmac = sign(verifiedKeyEvent);
Gang Wange9087892020-01-07 12:17:14 -05003530 break;
3531 }
3532 case AINPUT_EVENT_TYPE_MOTION: {
3533 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(event);
3534 VerifiedMotionEvent verifiedMotionEvent =
3535 verifiedMotionEventFromMotionEvent(motionEvent);
3536 result = std::make_unique<VerifiedMotionEvent>(verifiedMotionEvent);
chaviw09c8d2d2020-08-24 15:48:26 -07003537 calculatedHmac = sign(verifiedMotionEvent);
Gang Wange9087892020-01-07 12:17:14 -05003538 break;
3539 }
3540 default: {
3541 ALOGE("Cannot verify events of type %" PRId32, event.getType());
3542 return nullptr;
3543 }
3544 }
3545 if (calculatedHmac == INVALID_HMAC) {
3546 return nullptr;
3547 }
3548 if (calculatedHmac != event.getHmac()) {
3549 return nullptr;
3550 }
3551 return result;
Siarhei Vishniakou54d3e182020-01-15 17:38:38 -08003552}
3553
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003555 return injectorUid == 0 ||
3556 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557}
3558
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003559void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 InjectionState* injectionState = entry->injectionState;
3561 if (injectionState) {
3562#if DEBUG_INJECTION
3563 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003564 "injectorPid=%d, injectorUid=%d",
3565 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566#endif
3567
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003568 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569 // Log the outcome since the injector did not wait for the injection result.
3570 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003571 case INPUT_EVENT_INJECTION_SUCCEEDED:
3572 ALOGV("Asynchronous input event injection succeeded.");
3573 break;
3574 case INPUT_EVENT_INJECTION_FAILED:
3575 ALOGW("Asynchronous input event injection failed.");
3576 break;
3577 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3578 ALOGW("Asynchronous input event injection permission denied.");
3579 break;
3580 case INPUT_EVENT_INJECTION_TIMED_OUT:
3581 ALOGW("Asynchronous input event injection timed out.");
3582 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 }
3584 }
3585
3586 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003587 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 }
3589}
3590
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003591void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 InjectionState* injectionState = entry->injectionState;
3593 if (injectionState) {
3594 injectionState->pendingForegroundDispatches += 1;
3595 }
3596}
3597
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003598void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 InjectionState* injectionState = entry->injectionState;
3600 if (injectionState) {
3601 injectionState->pendingForegroundDispatches -= 1;
3602
3603 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003604 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 }
3606 }
3607}
3608
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003609std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3610 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003611 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003612}
3613
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003615 const sp<IBinder>& windowHandleToken) const {
arthurhungbe737672020-06-24 12:29:21 +08003616 if (windowHandleToken == nullptr) {
3617 return nullptr;
3618 }
3619
Arthur Hungb92218b2018-08-14 12:00:21 +08003620 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003621 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3622 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003623 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003624 return windowHandle;
3625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
3627 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003628 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629}
3630
Mady Mellor017bcd12020-06-23 19:12:00 +00003631bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
3632 for (auto& it : mWindowHandlesByDisplay) {
3633 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3634 for (const sp<InputWindowHandle>& handle : windowHandles) {
arthurhungbe737672020-06-24 12:29:21 +08003635 if (handle->getId() == windowHandle->getId() &&
3636 handle->getToken() == windowHandle->getToken()) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003637 if (windowHandle->getInfo()->displayId != it.first) {
3638 ALOGE("Found window %s in display %" PRId32
3639 ", but it should belong to display %" PRId32,
3640 windowHandle->getName().c_str(), it.first,
3641 windowHandle->getInfo()->displayId);
3642 }
3643 return true;
Arthur Hungb92218b2018-08-14 12:00:21 +08003644 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 }
3646 }
3647 return false;
3648}
3649
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003650bool InputDispatcher::hasResponsiveConnectionLocked(InputWindowHandle& windowHandle) const {
3651 sp<Connection> connection = getConnectionLocked(windowHandle.getToken());
3652 const bool noInputChannel =
3653 windowHandle.getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3654 if (connection != nullptr && noInputChannel) {
3655 ALOGW("%s has feature NO_INPUT_CHANNEL, but it matched to connection %s",
3656 windowHandle.getName().c_str(), connection->inputChannel->getName().c_str());
3657 return false;
3658 }
3659
3660 if (connection == nullptr) {
3661 if (!noInputChannel) {
3662 ALOGI("Could not find connection for %s", windowHandle.getName().c_str());
3663 }
3664 return false;
3665 }
3666 if (!connection->responsive) {
3667 ALOGW("Window %s is not responsive", windowHandle.getName().c_str());
3668 return false;
3669 }
3670 return true;
3671}
3672
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003673std::shared_ptr<InputChannel> InputDispatcher::getInputChannelLocked(
3674 const sp<IBinder>& token) const {
Robert Carr5c8a0262018-10-03 16:30:44 -07003675 size_t count = mInputChannelsByToken.count(token);
3676 if (count == 0) {
3677 return nullptr;
3678 }
3679 return mInputChannelsByToken.at(token);
3680}
3681
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003682void InputDispatcher::updateWindowHandlesForDisplayLocked(
3683 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3684 if (inputWindowHandles.empty()) {
3685 // Remove all handles on a display if there are no windows left.
3686 mWindowHandlesByDisplay.erase(displayId);
3687 return;
3688 }
3689
3690 // Since we compare the pointer of input window handles across window updates, we need
3691 // to make sure the handle object for the same window stays unchanged across updates.
3692 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
chaviwaf87b3e2019-10-01 16:59:28 -07003693 std::unordered_map<int32_t /*id*/, sp<InputWindowHandle>> oldHandlesById;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003694 for (const sp<InputWindowHandle>& handle : oldHandles) {
chaviwaf87b3e2019-10-01 16:59:28 -07003695 oldHandlesById[handle->getId()] = handle;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003696 }
3697
3698 std::vector<sp<InputWindowHandle>> newHandles;
3699 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3700 if (!handle->updateInfo()) {
3701 // handle no longer valid
3702 continue;
3703 }
3704
3705 const InputWindowInfo* info = handle->getInfo();
3706 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3707 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3708 const bool noInputChannel =
Michael Wright44753b12020-07-08 13:48:11 +01003709 info->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3710 const bool canReceiveInput = !info->flags.test(InputWindowInfo::Flag::NOT_TOUCHABLE) ||
3711 !info->flags.test(InputWindowInfo::Flag::NOT_FOCUSABLE);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003712 if (canReceiveInput && !noInputChannel) {
John Recke0710582019-09-26 13:46:12 -07003713 ALOGV("Window handle %s has no registered input channel",
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003714 handle->getName().c_str());
Robert Carr2984b7a2020-04-13 17:06:45 -07003715 continue;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003716 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003717 }
3718
3719 if (info->displayId != displayId) {
3720 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3721 handle->getName().c_str(), displayId, info->displayId);
3722 continue;
3723 }
3724
Robert Carredd13602020-04-13 17:24:34 -07003725 if ((oldHandlesById.find(handle->getId()) != oldHandlesById.end()) &&
3726 (oldHandlesById.at(handle->getId())->getToken() == handle->getToken())) {
chaviwaf87b3e2019-10-01 16:59:28 -07003727 const sp<InputWindowHandle>& oldHandle = oldHandlesById.at(handle->getId());
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003728 oldHandle->updateFrom(handle);
3729 newHandles.push_back(oldHandle);
3730 } else {
3731 newHandles.push_back(handle);
3732 }
3733 }
3734
3735 // Insert or replace
3736 mWindowHandlesByDisplay[displayId] = newHandles;
3737}
3738
Arthur Hung72d8dc32020-03-28 00:48:39 +00003739void InputDispatcher::setInputWindows(
3740 const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
3741 { // acquire lock
3742 std::scoped_lock _l(mLock);
3743 for (auto const& i : handlesPerDisplay) {
3744 setInputWindowsLocked(i.second, i.first);
3745 }
3746 }
3747 // Wake up poll loop since it may need to make new input dispatching choices.
3748 mLooper->wake();
3749}
3750
Arthur Hungb92218b2018-08-14 12:00:21 +08003751/**
3752 * Called from InputManagerService, update window handle list by displayId that can receive input.
3753 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3754 * If set an empty list, remove all handles from the specific display.
3755 * For focused handle, check if need to change and send a cancel event to previous one.
3756 * For removed handle, check if need to send a cancel event if already in touch.
3757 */
Arthur Hung72d8dc32020-03-28 00:48:39 +00003758void InputDispatcher::setInputWindowsLocked(
3759 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003760 if (DEBUG_FOCUS) {
3761 std::string windowList;
3762 for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
3763 windowList += iwh->getName() + " ";
3764 }
3765 ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
3766 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003768 // Ensure all tokens are null if the window has feature NO_INPUT_CHANNEL
3769 for (const sp<InputWindowHandle>& window : inputWindowHandles) {
3770 const bool noInputWindow =
3771 window->getInfo()->inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3772 if (noInputWindow && window->getToken() != nullptr) {
3773 ALOGE("%s has feature NO_INPUT_WINDOW, but a non-null token. Clearing",
3774 window->getName().c_str());
3775 window->releaseChannel();
3776 }
3777 }
3778
Arthur Hung72d8dc32020-03-28 00:48:39 +00003779 // Copy old handles for release if they are no longer present.
3780 const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781
Arthur Hung72d8dc32020-03-28 00:48:39 +00003782 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003783
Arthur Hung72d8dc32020-03-28 00:48:39 +00003784 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
3785 bool foundHoveredWindow = false;
3786 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3787 // Set newFocusedWindowHandle to the top most focused window instead of the last one
Vishnu Nair47074b82020-08-14 11:54:47 -07003788 if (!newFocusedWindowHandle && windowHandle->getInfo()->focusable &&
Arthur Hung72d8dc32020-03-28 00:48:39 +00003789 windowHandle->getInfo()->visible) {
3790 newFocusedWindowHandle = windowHandle;
3791 }
3792 if (windowHandle == mLastHoverWindowHandle) {
3793 foundHoveredWindow = true;
3794 }
3795 }
3796
3797 if (!foundHoveredWindow) {
3798 mLastHoverWindowHandle = nullptr;
3799 }
3800
3801 sp<InputWindowHandle> oldFocusedWindowHandle =
3802 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3803
3804 if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07003805 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle, displayId,
3806 "setInputWindowsLocked");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003807 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07003809 std::unordered_map<int32_t, TouchState>::iterator stateIt =
3810 mTouchStatesByDisplay.find(displayId);
3811 if (stateIt != mTouchStatesByDisplay.end()) {
3812 TouchState& state = stateIt->second;
Arthur Hung72d8dc32020-03-28 00:48:39 +00003813 for (size_t i = 0; i < state.windows.size();) {
3814 TouchedWindow& touchedWindow = state.windows[i];
Mady Mellor017bcd12020-06-23 19:12:00 +00003815 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003816 if (DEBUG_FOCUS) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003817 ALOGD("Touched window was removed: %s in display %" PRId32,
3818 touchedWindow.windowHandle->getName().c_str(), displayId);
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003819 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003820 std::shared_ptr<InputChannel> touchedInputChannel =
Arthur Hung72d8dc32020-03-28 00:48:39 +00003821 getInputChannelLocked(touchedWindow.windowHandle->getToken());
3822 if (touchedInputChannel != nullptr) {
3823 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3824 "touched window was removed");
3825 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003827 state.windows.erase(state.windows.begin() + i);
3828 } else {
3829 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 }
3831 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003832 }
Arthur Hung25e2af12020-03-26 12:58:37 +00003833
Arthur Hung72d8dc32020-03-28 00:48:39 +00003834 // Release information for windows that are no longer present.
3835 // This ensures that unused input channels are released promptly.
3836 // Otherwise, they might stick around until the window handle is destroyed
3837 // which might not happen until the next GC.
3838 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Mady Mellor017bcd12020-06-23 19:12:00 +00003839 if (!hasWindowHandleLocked(oldWindowHandle)) {
Arthur Hung72d8dc32020-03-28 00:48:39 +00003840 if (DEBUG_FOCUS) {
3841 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Arthur Hung25e2af12020-03-26 12:58:37 +00003842 }
Arthur Hung72d8dc32020-03-28 00:48:39 +00003843 oldWindowHandle->releaseChannel();
Arthur Hung25e2af12020-03-26 12:58:37 +00003844 }
chaviw291d88a2019-02-14 10:33:58 -08003845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846}
3847
3848void InputDispatcher::setFocusedApplication(
Chris Yea209fde2020-07-22 13:54:51 -07003849 int32_t displayId, const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003850 if (DEBUG_FOCUS) {
3851 ALOGD("setFocusedApplication displayId=%" PRId32 " %s", displayId,
3852 inputApplicationHandle ? inputApplicationHandle->getName().c_str() : "<nullptr>");
3853 }
Chris Yea209fde2020-07-22 13:54:51 -07003854 if (inputApplicationHandle != nullptr &&
3855 inputApplicationHandle->getApplicationToken() != nullptr) {
3856 // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003857 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858
Chris Yea209fde2020-07-22 13:54:51 -07003859 std::shared_ptr<InputApplicationHandle> oldFocusedApplicationHandle =
Tiger Huang721e26f2018-07-24 22:26:19 +08003860 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003861
Chris Yea209fde2020-07-22 13:54:51 -07003862 // If oldFocusedApplicationHandle already exists
3863 if (oldFocusedApplicationHandle != nullptr) {
3864 // If a new focused application handle is different from the old one and
3865 // old focus application info is awaited focused application info.
3866 if (*oldFocusedApplicationHandle != *inputApplicationHandle &&
3867 mAwaitedFocusedApplication != nullptr &&
3868 *oldFocusedApplicationHandle == *mAwaitedFocusedApplication) {
3869 resetNoFocusedWindowTimeoutLocked();
3870 }
3871 // Erase the old application from container first
3872 mFocusedApplicationHandlesByDisplay.erase(displayId);
3873 // Should already get freed after removed from container but just double check.
3874 oldFocusedApplicationHandle.reset();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003875 }
3876
Chris Yea209fde2020-07-22 13:54:51 -07003877 // Set the new application handle.
3878 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 } // release lock
3880
3881 // Wake up poll loop since it may need to make new input dispatching choices.
3882 mLooper->wake();
3883}
3884
Tiger Huang721e26f2018-07-24 22:26:19 +08003885/**
3886 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3887 * the display not specified.
3888 *
3889 * We track any unreleased events for each window. If a window loses the ability to receive the
3890 * released event, we will send a cancel event to it. So when the focused display is changed, we
3891 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3892 * display. The display-specified events won't be affected.
3893 */
3894void InputDispatcher::setFocusedDisplay(int32_t displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003895 if (DEBUG_FOCUS) {
3896 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3897 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003898 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003899 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003900
3901 if (mFocusedDisplayId != displayId) {
3902 sp<InputWindowHandle> oldFocusedWindowHandle =
3903 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3904 if (oldFocusedWindowHandle != nullptr) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05003905 std::shared_ptr<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003906 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003907 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003908 CancelationOptions
3909 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3910 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003911 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003912 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3913 }
3914 }
3915 mFocusedDisplayId = displayId;
3916
Chris Ye3c2d6f52020-08-09 10:39:48 -07003917 // Find new focused window and validate
Tiger Huang721e26f2018-07-24 22:26:19 +08003918 sp<InputWindowHandle> newFocusedWindowHandle =
3919 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07003920 notifyFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003921
Tiger Huang721e26f2018-07-24 22:26:19 +08003922 if (newFocusedWindowHandle == nullptr) {
3923 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3924 if (!mFocusedWindowHandlesByDisplay.empty()) {
3925 ALOGE("But another display has a focused window:");
3926 for (auto& it : mFocusedWindowHandlesByDisplay) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003927 const sp<InputWindowHandle>& windowHandle = it.second;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05003928 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", it.first,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003929 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003930 }
3931 }
3932 }
3933 }
3934
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003935 if (DEBUG_FOCUS) {
3936 logDispatchStateLocked();
3937 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003938 } // release lock
3939
3940 // Wake up poll loop since it may need to make new input dispatching choices.
3941 mLooper->wake();
3942}
3943
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003945 if (DEBUG_FOCUS) {
3946 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003948
3949 bool changed;
3950 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003951 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952
3953 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3954 if (mDispatchFrozen && !frozen) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003955 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 }
3957
3958 if (mDispatchEnabled && !enabled) {
3959 resetAndDropEverythingLocked("dispatcher is being disabled");
3960 }
3961
3962 mDispatchEnabled = enabled;
3963 mDispatchFrozen = frozen;
3964 changed = true;
3965 } else {
3966 changed = false;
3967 }
3968
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003969 if (DEBUG_FOCUS) {
3970 logDispatchStateLocked();
3971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 } // release lock
3973
3974 if (changed) {
3975 // Wake up poll loop since it may need to make new input dispatching choices.
3976 mLooper->wake();
3977 }
3978}
3979
3980void InputDispatcher::setInputFilterEnabled(bool enabled) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01003981 if (DEBUG_FOCUS) {
3982 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984
3985 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003986 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987
3988 if (mInputFilterEnabled == enabled) {
3989 return;
3990 }
3991
3992 mInputFilterEnabled = enabled;
3993 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3994 } // release lock
3995
3996 // Wake up poll loop since there might be work to do to drop everything.
3997 mLooper->wake();
3998}
3999
Siarhei Vishniakouf3bc1aa2019-11-25 13:48:53 -08004000void InputDispatcher::setInTouchMode(bool inTouchMode) {
4001 std::scoped_lock lock(mLock);
4002 mInTouchMode = inTouchMode;
4003}
4004
chaviwfbe5d9c2018-12-26 12:23:37 -08004005bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
4006 if (fromToken == toToken) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004007 if (DEBUG_FOCUS) {
4008 ALOGD("Trivial transfer to same window.");
4009 }
chaviwfbe5d9c2018-12-26 12:23:37 -08004010 return true;
4011 }
4012
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004014 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015
chaviwfbe5d9c2018-12-26 12:23:37 -08004016 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
4017 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07004018 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08004019 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004020 return false;
4021 }
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004022 if (DEBUG_FOCUS) {
4023 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
4024 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
4025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004027 if (DEBUG_FOCUS) {
4028 ALOGD("Cannot transfer focus because windows are on different displays.");
4029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030 return false;
4031 }
4032
4033 bool found = false;
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004034 for (std::pair<const int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4035 TouchState& state = pair.second;
Jeff Brownf086ddb2014-02-11 14:28:48 -08004036 for (size_t i = 0; i < state.windows.size(); i++) {
4037 const TouchedWindow& touchedWindow = state.windows[i];
4038 if (touchedWindow.windowHandle == fromWindowHandle) {
4039 int32_t oldTargetFlags = touchedWindow.targetFlags;
4040 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004042 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004043
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004044 int32_t newTargetFlags = oldTargetFlags &
4045 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
4046 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004047 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048
Jeff Brownf086ddb2014-02-11 14:28:48 -08004049 found = true;
4050 goto Found;
4051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052 }
4053 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004054 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004056 if (!found) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004057 if (DEBUG_FOCUS) {
4058 ALOGD("Focus transfer failed because from window did not have focus.");
4059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 return false;
4061 }
4062
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004063 sp<Connection> fromConnection = getConnectionLocked(fromToken);
4064 sp<Connection> toConnection = getConnectionLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004065 if (fromConnection != nullptr && toConnection != nullptr) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08004066 fromConnection->inputState.mergePointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004067 CancelationOptions
4068 options(CancelationOptions::CANCEL_POINTER_EVENTS,
4069 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
Svet Ganov5d3bc372020-01-26 23:11:07 -08004071 synthesizePointerDownEventsForConnectionLocked(toConnection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 }
4073
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004074 if (DEBUG_FOCUS) {
4075 logDispatchStateLocked();
4076 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077 } // release lock
4078
4079 // Wake up poll loop since it may need to make new input dispatching choices.
4080 mLooper->wake();
4081 return true;
4082}
4083
4084void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
Siarhei Vishniakou86587282019-09-09 18:20:15 +01004085 if (DEBUG_FOCUS) {
4086 ALOGD("Resetting and dropping all events (%s).", reason);
4087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088
4089 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
4090 synthesizeCancelationEventsForAllConnectionsLocked(options);
4091
4092 resetKeyRepeatLocked();
4093 releasePendingEventLocked();
4094 drainInboundQueueLocked();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004095 resetNoFocusedWindowTimeoutLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004096
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004097 mAnrTracker.clear();
Jeff Brownf086ddb2014-02-11 14:28:48 -08004098 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07004100 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101}
4102
4103void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004104 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 dumpDispatchStateLocked(dump);
4106
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004107 std::istringstream stream(dump);
4108 std::string line;
4109
4110 while (std::getline(stream, line, '\n')) {
4111 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112 }
4113}
4114
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004115void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07004116 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
4117 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
4118 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08004119 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120
Tiger Huang721e26f2018-07-24 22:26:19 +08004121 if (!mFocusedApplicationHandlesByDisplay.empty()) {
4122 dump += StringPrintf(INDENT "FocusedApplications:\n");
4123 for (auto& it : mFocusedApplicationHandlesByDisplay) {
4124 const int32_t displayId = it.first;
Chris Yea209fde2020-07-22 13:54:51 -07004125 const std::shared_ptr<InputApplicationHandle>& applicationHandle = it.second;
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004126 const std::chrono::duration timeout =
4127 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004128 dump += StringPrintf(INDENT2 "displayId=%" PRId32
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004129 ", name='%s', dispatchingTimeout=%" PRId64 "ms\n",
Siarhei Vishniakou70622952020-07-30 11:17:23 -05004130 displayId, applicationHandle->getName().c_str(), millis(timeout));
Tiger Huang721e26f2018-07-24 22:26:19 +08004131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08004133 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 }
Tiger Huang721e26f2018-07-24 22:26:19 +08004135
4136 if (!mFocusedWindowHandlesByDisplay.empty()) {
4137 dump += StringPrintf(INDENT "FocusedWindows:\n");
4138 for (auto& it : mFocusedWindowHandlesByDisplay) {
4139 const int32_t displayId = it.first;
4140 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004141 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
4142 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08004143 }
4144 } else {
4145 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
4146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004148 if (!mTouchStatesByDisplay.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004149 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004150 for (const std::pair<int32_t, TouchState>& pair : mTouchStatesByDisplay) {
4151 const TouchState& state = pair.second;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004152 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004153 state.displayId, toString(state.down), toString(state.split),
4154 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004155 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004156 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004157 for (size_t i = 0; i < state.windows.size(); i++) {
4158 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004159 dump += StringPrintf(INDENT4
4160 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
4161 i, touchedWindow.windowHandle->getName().c_str(),
4162 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004163 }
4164 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004165 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08004166 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004167 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004168 dump += INDENT3 "Portal windows:\n";
4169 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004170 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004171 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
4172 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004173 }
4174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 }
4176 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004177 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 }
4179
Arthur Hungb92218b2018-08-14 12:00:21 +08004180 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004181 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004182 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08004183 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004184 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08004185 dump += INDENT2 "Windows:\n";
4186 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004187 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08004188 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189
Arthur Hungb92218b2018-08-14 12:00:21 +08004190 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Vishnu Nair47074b82020-08-14 11:54:47 -07004191 "portalToDisplayId=%d, paused=%s, focusable=%s, "
4192 "hasWallpaper=%s, visible=%s, "
Michael Wright44753b12020-07-08 13:48:11 +01004193 "flags=%s, type=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004194 "frame=[%d,%d][%d,%d], globalScale=%f, "
chaviw1ff3d1e2020-07-01 15:53:47 -07004195 "touchableRegion=",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004196 i, windowInfo->name.c_str(), windowInfo->displayId,
4197 windowInfo->portalToDisplayId,
4198 toString(windowInfo->paused),
Vishnu Nair47074b82020-08-14 11:54:47 -07004199 toString(windowInfo->focusable),
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004200 toString(windowInfo->hasWallpaper),
4201 toString(windowInfo->visible),
Michael Wright8759d672020-07-21 00:46:45 +01004202 windowInfo->flags.string().c_str(),
Michael Wright44753b12020-07-08 13:48:11 +01004203 static_cast<int32_t>(windowInfo->type),
4204 windowInfo->frameLeft, windowInfo->frameTop,
4205 windowInfo->frameRight, windowInfo->frameBottom,
chaviw1ff3d1e2020-07-01 15:53:47 -07004206 windowInfo->globalScaleFactor);
Arthur Hungb92218b2018-08-14 12:00:21 +08004207 dumpRegion(dump, windowInfo->touchableRegion);
Michael Wright44753b12020-07-08 13:48:11 +01004208 dump += StringPrintf(", inputFeatures=%s",
4209 windowInfo->inputFeatures.string().c_str());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004210 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%" PRId64
4211 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004212 windowInfo->ownerPid, windowInfo->ownerUid,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004213 millis(windowInfo->dispatchingTimeout));
chaviw85b44202020-07-24 11:46:21 -07004214 windowInfo->transform.dump(dump, "transform", INDENT4);
Arthur Hungb92218b2018-08-14 12:00:21 +08004215 }
4216 } else {
4217 dump += INDENT2 "Windows: <none>\n";
4218 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 }
4220 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08004221 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 }
4223
Michael Wright3dd60e22019-03-27 22:06:44 +00004224 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004225 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004226 const std::vector<Monitor>& monitors = it.second;
4227 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
4228 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004229 }
4230 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004231 const std::vector<Monitor>& monitors = it.second;
4232 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
4233 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004234 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00004236 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 }
4238
4239 nsecs_t currentTime = now();
4240
4241 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004242 if (!mRecentQueue.empty()) {
4243 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
4244 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004245 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004247 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 }
4249 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004250 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 }
4252
4253 // Dump event currently being dispatched.
4254 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004255 dump += INDENT "PendingEvent:\n";
4256 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 mPendingEvent->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004258 dump += StringPrintf(", age=%" PRId64 "ms\n",
4259 ns2ms(currentTime - mPendingEvent->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004261 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 }
4263
4264 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004265 if (!mInboundQueue.empty()) {
4266 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
4267 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004268 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 entry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004270 dump += StringPrintf(", age=%" PRId64 "ms\n", ns2ms(currentTime - entry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 }
4272 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004273 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 }
4275
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004276 if (!mReplacedKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004277 dump += INDENT "ReplacedKeys:\n";
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004278 for (const std::pair<KeyReplacement, int32_t>& pair : mReplacedKeys) {
4279 const KeyReplacement& replacement = pair.first;
4280 int32_t newKeyCode = pair.second;
4281 dump += StringPrintf(INDENT2 "originalKeyCode=%d, deviceId=%d -> newKeyCode=%d\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004282 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07004283 }
4284 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004285 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07004286 }
4287
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004288 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004289 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004290 for (const auto& pair : mConnectionsByFd) {
4291 const sp<Connection>& connection = pair.second;
4292 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004293 "status=%s, monitor=%s, responsive=%s\n",
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004294 pair.first, connection->getInputChannelName().c_str(),
4295 connection->getWindowName().c_str(), connection->getStatusLabel(),
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004296 toString(connection->monitor), toString(connection->responsive));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004298 if (!connection->outboundQueue.empty()) {
4299 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
4300 connection->outboundQueue.size());
4301 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 dump.append(INDENT4);
4303 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004304 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%" PRId64
4305 "ms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004306 entry->targetFlags, entry->resolvedAction,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004307 ns2ms(currentTime - entry->eventEntry->eventTime));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 }
4309 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004310 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 }
4312
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004313 if (!connection->waitQueue.empty()) {
4314 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
4315 connection->waitQueue.size());
4316 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004317 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004319 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004320 "age=%" PRId64 "ms, wait=%" PRId64 "ms seq=%" PRIu32 "\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),
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05004323 ns2ms(currentTime - entry->deliveryTime), entry->seq);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 }
4325 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004326 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
4328 }
4329 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004330 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 }
4332
4333 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004334 dump += StringPrintf(INDENT "AppSwitch: pending, due in %" PRId64 "ms\n",
4335 ns2ms(mAppSwitchDueTime - now()));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004337 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 }
4339
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004340 dump += INDENT "Configuration:\n";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004341 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %" PRId64 "ms\n", ns2ms(mConfig.keyRepeatDelay));
4342 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %" PRId64 "ms\n",
4343 ns2ms(mConfig.keyRepeatTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344}
4345
Michael Wright3dd60e22019-03-27 22:06:44 +00004346void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
4347 const size_t numMonitors = monitors.size();
4348 for (size_t i = 0; i < numMonitors; i++) {
4349 const Monitor& monitor = monitors[i];
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004350 const std::shared_ptr<InputChannel>& channel = monitor.inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004351 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
4352 dump += "\n";
4353 }
4354}
4355
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004356status_t InputDispatcher::registerInputChannel(const std::shared_ptr<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357#if DEBUG_REGISTRATION
Siarhei Vishniakou7c34b232019-10-11 19:08:48 -07004358 ALOGD("channel '%s' ~ registerInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359#endif
4360
4361 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004362 std::scoped_lock _l(mLock);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004363 sp<Connection> existingConnection = getConnectionLocked(inputChannel->getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004364 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004366 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367 return BAD_VALUE;
4368 }
4369
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004370 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/, mIdGenerator);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371
4372 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004373 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004374 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
4377 } // release lock
4378
4379 // Wake the looper because some connections have changed.
4380 mLooper->wake();
4381 return OK;
4382}
4383
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004384status_t InputDispatcher::registerInputMonitor(const std::shared_ptr<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004385 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004386 { // acquire lock
4387 std::scoped_lock _l(mLock);
4388
4389 if (displayId < 0) {
4390 ALOGW("Attempted to register input monitor without a specified display.");
4391 return BAD_VALUE;
4392 }
4393
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004394 if (inputChannel->getConnectionToken() == nullptr) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004395 ALOGW("Attempted to register input monitor without an identifying token.");
4396 return BAD_VALUE;
4397 }
4398
Garfield Tanff1f1bb2020-01-28 13:24:04 -08004399 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/, mIdGenerator);
Michael Wright3dd60e22019-03-27 22:06:44 +00004400
4401 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004402 mConnectionsByFd[fd] = connection;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004403 mInputChannelsByToken[inputChannel->getConnectionToken()] = inputChannel;
Michael Wright3dd60e22019-03-27 22:06:44 +00004404
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004405 auto& monitorsByDisplay =
4406 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00004407 monitorsByDisplay[displayId].emplace_back(inputChannel);
4408
4409 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00004410 }
4411 // Wake the looper because some connections have changed.
4412 mLooper->wake();
4413 return OK;
4414}
4415
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004416status_t InputDispatcher::unregisterInputChannel(const InputChannel& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417#if DEBUG_REGISTRATION
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004418 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004419#endif
4420
4421 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004422 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423
4424 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
4425 if (status) {
4426 return status;
4427 }
4428 } // release lock
4429
4430 // Wake the poll loop because removing the connection may have changed the current
4431 // synchronization state.
4432 mLooper->wake();
4433 return OK;
4434}
4435
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004436status_t InputDispatcher::unregisterInputChannelLocked(const InputChannel& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004437 bool notify) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004438 sp<Connection> connection = getConnectionLocked(inputChannel.getConnectionToken());
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004439 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004441 inputChannel.getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442 return BAD_VALUE;
4443 }
4444
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004445 removeConnectionLocked(connection);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004446 mInputChannelsByToken.erase(inputChannel.getConnectionToken());
Robert Carr5c8a0262018-10-03 16:30:44 -07004447
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448 if (connection->monitor) {
4449 removeMonitorChannelLocked(inputChannel);
4450 }
4451
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004452 mLooper->removeFd(inputChannel.getFd());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453
4454 nsecs_t currentTime = now();
4455 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
4456
4457 connection->status = Connection::STATUS_ZOMBIE;
4458 return OK;
4459}
4460
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004461void InputDispatcher::removeMonitorChannelLocked(const InputChannel& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004462 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
4463 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
4464}
4465
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004466void InputDispatcher::removeMonitorChannelLocked(
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004467 const InputChannel& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00004468 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004469 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004470 std::vector<Monitor>& monitors = it->second;
4471 const size_t numMonitors = monitors.size();
4472 for (size_t i = 0; i < numMonitors; i++) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004473 if (*monitors[i].inputChannel == inputChannel) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004474 monitors.erase(monitors.begin() + i);
4475 break;
4476 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004477 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004478 if (monitors.empty()) {
4479 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004480 } else {
4481 ++it;
4482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483 }
4484}
4485
Michael Wright3dd60e22019-03-27 22:06:44 +00004486status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
4487 { // acquire lock
4488 std::scoped_lock _l(mLock);
4489 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4490
4491 if (!foundDisplayId) {
4492 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4493 return BAD_VALUE;
4494 }
4495 int32_t displayId = foundDisplayId.value();
4496
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004497 std::unordered_map<int32_t, TouchState>::iterator stateIt =
4498 mTouchStatesByDisplay.find(displayId);
4499 if (stateIt == mTouchStatesByDisplay.end()) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004500 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4501 return BAD_VALUE;
4502 }
4503
Siarhei Vishniakou4700f822020-03-24 19:05:54 -07004504 TouchState& state = stateIt->second;
Michael Wright3dd60e22019-03-27 22:06:44 +00004505 std::optional<int32_t> foundDeviceId;
4506 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004507 if (touchedMonitor.monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004508 foundDeviceId = state.deviceId;
4509 }
4510 }
4511 if (!foundDeviceId || !state.down) {
4512 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004513 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004514 return BAD_VALUE;
4515 }
4516 int32_t deviceId = foundDeviceId.value();
4517
4518 // Send cancel events to all the input channels we're stealing from.
4519 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004520 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004521 options.deviceId = deviceId;
4522 options.displayId = displayId;
4523 for (const TouchedWindow& window : state.windows) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -05004524 std::shared_ptr<InputChannel> channel =
4525 getInputChannelLocked(window.windowHandle->getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00004526 if (channel != nullptr) {
4527 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4528 }
Michael Wright3dd60e22019-03-27 22:06:44 +00004529 }
4530 // Then clear the current touch state so we stop dispatching to them as well.
4531 state.filterNonMonitors();
4532 }
4533 return OK;
4534}
4535
Michael Wright3dd60e22019-03-27 22:06:44 +00004536std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4537 const sp<IBinder>& token) {
4538 for (const auto& it : mGestureMonitorsByDisplay) {
4539 const std::vector<Monitor>& monitors = it.second;
4540 for (const Monitor& monitor : monitors) {
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004541 if (monitor.inputChannel->getConnectionToken() == token) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004542 return it.first;
4543 }
4544 }
4545 }
4546 return std::nullopt;
4547}
4548
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004549sp<Connection> InputDispatcher::getConnectionLocked(const sp<IBinder>& inputConnectionToken) const {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004550 if (inputConnectionToken == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004551 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004552 }
4553
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004554 for (const auto& pair : mConnectionsByFd) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004555 const sp<Connection>& connection = pair.second;
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004556 if (connection->inputChannel->getConnectionToken() == inputConnectionToken) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004557 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558 }
4559 }
Robert Carr4e670e52018-08-15 13:26:12 -07004560
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004561 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562}
4563
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004564void InputDispatcher::removeConnectionLocked(const sp<Connection>& connection) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004565 mAnrTracker.eraseToken(connection->inputChannel->getConnectionToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004566 removeByValue(mConnectionsByFd, connection);
4567}
4568
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004569void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4570 const sp<Connection>& connection, uint32_t seq,
4571 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004572 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4573 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574 commandEntry->connection = connection;
4575 commandEntry->eventTime = currentTime;
4576 commandEntry->seq = seq;
4577 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004578 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579}
4580
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004581void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4582 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004584 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004586 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4587 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004589 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004590}
4591
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07004592void InputDispatcher::notifyFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
4593 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004594 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4595 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004596 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4597 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004598 commandEntry->oldToken = oldToken;
4599 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004600 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004601}
4602
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004603void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
4604 // Since we are allowing the policy to extend the timeout, maybe the waitQueue
4605 // is already healthy again. Don't raise ANR in this situation
4606 if (connection->waitQueue.empty()) {
4607 ALOGI("Not raising ANR because the connection %s has recovered",
4608 connection->inputChannel->getName().c_str());
4609 return;
4610 }
4611 /**
4612 * The "oldestEntry" is the entry that was first sent to the application. That entry, however,
4613 * may not be the one that caused the timeout to occur. One possibility is that window timeout
4614 * has changed. This could cause newer entries to time out before the already dispatched
4615 * entries. In that situation, the newest entries caused ANR. But in all likelihood, the app
4616 * processes the events linearly. So providing information about the oldest entry seems to be
4617 * most useful.
4618 */
4619 DispatchEntry* oldestEntry = *connection->waitQueue.begin();
4620 const nsecs_t currentWait = now() - oldestEntry->deliveryTime;
4621 std::string reason =
4622 android::base::StringPrintf("%s is not responding. Waited %" PRId64 "ms for %s",
4623 connection->inputChannel->getName().c_str(),
4624 ns2ms(currentWait),
4625 oldestEntry->eventEntry->getDescription().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004627 updateLastAnrStateLocked(getWindowHandleLocked(connection->inputChannel->getConnectionToken()),
4628 reason);
4629
4630 std::unique_ptr<CommandEntry> commandEntry =
4631 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4632 commandEntry->inputApplicationHandle = nullptr;
4633 commandEntry->inputChannel = connection->inputChannel;
4634 commandEntry->reason = std::move(reason);
4635 postCommandLocked(std::move(commandEntry));
4636}
4637
Chris Yea209fde2020-07-22 13:54:51 -07004638void InputDispatcher::onAnrLocked(const std::shared_ptr<InputApplicationHandle>& application) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004639 std::string reason = android::base::StringPrintf("%s does not have a focused window",
4640 application->getName().c_str());
4641
4642 updateLastAnrStateLocked(application, reason);
4643
4644 std::unique_ptr<CommandEntry> commandEntry =
4645 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyAnrLockedInterruptible);
4646 commandEntry->inputApplicationHandle = application;
4647 commandEntry->inputChannel = nullptr;
4648 commandEntry->reason = std::move(reason);
4649 postCommandLocked(std::move(commandEntry));
4650}
4651
4652void InputDispatcher::updateLastAnrStateLocked(const sp<InputWindowHandle>& window,
4653 const std::string& reason) {
4654 const std::string windowLabel = getApplicationWindowLabel(nullptr, window);
4655 updateLastAnrStateLocked(windowLabel, reason);
4656}
4657
Chris Yea209fde2020-07-22 13:54:51 -07004658void InputDispatcher::updateLastAnrStateLocked(
4659 const std::shared_ptr<InputApplicationHandle>& application, const std::string& reason) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004660 const std::string windowLabel = getApplicationWindowLabel(application, nullptr);
4661 updateLastAnrStateLocked(windowLabel, reason);
4662}
4663
4664void InputDispatcher::updateLastAnrStateLocked(const std::string& windowLabel,
4665 const std::string& reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004667 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668 struct tm tm;
4669 localtime_r(&t, &tm);
4670 char timestr[64];
4671 strftime(timestr, sizeof(timestr), "%F %T", &tm);
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004672 mLastAnrState.clear();
4673 mLastAnrState += INDENT "ANR:\n";
4674 mLastAnrState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004675 mLastAnrState += StringPrintf(INDENT2 "Reason: %s\n", reason.c_str());
4676 mLastAnrState += StringPrintf(INDENT2 "Window: %s\n", windowLabel.c_str());
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004677 dumpDispatchStateLocked(mLastAnrState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004678}
4679
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004680void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 mLock.unlock();
4682
4683 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4684
4685 mLock.lock();
4686}
4687
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004688void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 sp<Connection> connection = commandEntry->connection;
4690
4691 if (connection->status != Connection::STATUS_ZOMBIE) {
4692 mLock.unlock();
4693
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004694 mPolicy->notifyInputChannelBroken(connection->inputChannel->getConnectionToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695
4696 mLock.lock();
4697 }
4698}
4699
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004700void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004701 sp<IBinder> oldToken = commandEntry->oldToken;
4702 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004703 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004704 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004705 mLock.lock();
4706}
4707
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004708void InputDispatcher::doNotifyAnrLockedInterruptible(CommandEntry* commandEntry) {
Siarhei Vishniakoud0d71b62019-10-14 14:50:45 -07004709 sp<IBinder> token =
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004710 commandEntry->inputChannel ? commandEntry->inputChannel->getConnectionToken() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 mLock.unlock();
4712
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004713 const std::chrono::nanoseconds timeoutExtension =
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07004714 mPolicy->notifyAnr(commandEntry->inputApplicationHandle, token, commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715
4716 mLock.lock();
4717
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004718 if (timeoutExtension > 0s) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004719 extendAnrTimeoutsLocked(commandEntry->inputApplicationHandle, token, timeoutExtension);
4720 } else {
4721 // stop waking up for events in this connection, it is already not responding
4722 sp<Connection> connection = getConnectionLocked(token);
4723 if (connection == nullptr) {
4724 return;
4725 }
4726 cancelEventsForAnrLocked(connection);
4727 }
4728}
4729
Chris Yea209fde2020-07-22 13:54:51 -07004730void InputDispatcher::extendAnrTimeoutsLocked(
4731 const std::shared_ptr<InputApplicationHandle>& application,
4732 const sp<IBinder>& connectionToken, std::chrono::nanoseconds timeoutExtension) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004733 sp<Connection> connection = getConnectionLocked(connectionToken);
4734 if (connection == nullptr) {
4735 if (mNoFocusedWindowTimeoutTime.has_value() && application != nullptr) {
4736 // Maybe ANR happened because there's no focused window?
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004737 mNoFocusedWindowTimeoutTime = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004738 mAwaitedFocusedApplication = application;
4739 } else {
4740 // It's also possible that the connection already disappeared. No action necessary.
4741 }
4742 return;
4743 }
4744
4745 ALOGI("Raised ANR, but the policy wants to keep waiting on %s for %" PRId64 "ms longer",
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004746 connection->inputChannel->getName().c_str(), millis(timeoutExtension));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004747
4748 connection->responsive = true;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05004749 const nsecs_t newTimeout = now() + timeoutExtension.count();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004750 for (DispatchEntry* entry : connection->waitQueue) {
4751 if (newTimeout >= entry->timeoutTime) {
4752 // Already removed old entries when connection was marked unresponsive
4753 entry->timeoutTime = newTimeout;
4754 mAnrTracker.insert(entry->timeoutTime, connectionToken);
4755 }
4756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757}
4758
4759void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4760 CommandEntry* commandEntry) {
4761 KeyEntry* entry = commandEntry->keyEntry;
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004762 KeyEvent event = createKeyEvent(*entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763
4764 mLock.unlock();
4765
Michael Wright2b3c3302018-03-02 17:19:13 +00004766 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004767 sp<IBinder> token = commandEntry->inputChannel != nullptr
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004768 ? commandEntry->inputChannel->getConnectionToken()
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004769 : nullptr;
4770 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004771 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4772 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004773 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004774 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775
4776 mLock.lock();
4777
4778 if (delay < 0) {
4779 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4780 } else if (!delay) {
4781 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4782 } else {
4783 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4784 entry->interceptKeyWakeupTime = now() + delay;
4785 }
4786 entry->release();
4787}
4788
chaviwfd6d3512019-03-25 13:23:49 -07004789void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4790 mLock.unlock();
4791 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4792 mLock.lock();
4793}
4794
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004795/**
4796 * Connection is responsive if it has no events in the waitQueue that are older than the
4797 * current time.
4798 */
4799static bool isConnectionResponsive(const Connection& connection) {
4800 const nsecs_t currentTime = now();
4801 for (const DispatchEntry* entry : connection.waitQueue) {
4802 if (entry->timeoutTime < currentTime) {
4803 return false;
4804 }
4805 }
4806 return true;
4807}
4808
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004809void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004811 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004813 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814
4815 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004816 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004817 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004818 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004820 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004821 const nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004822 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004823 ALOGI("%s spent %" PRId64 "ms processing %s", connection->getWindowName().c_str(),
4824 ns2ms(eventDuration), dispatchEntry->eventEntry->getDescription().c_str());
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004825 }
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07004826 reportDispatchStatistics(std::chrono::nanoseconds(eventDuration), *connection, handled);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004827
4828 bool restartEvent;
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004829 if (dispatchEntry->eventEntry->type == EventEntry::Type::KEY) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004830 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4831 restartEvent =
4832 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
Siarhei Vishniakou49483272019-10-22 13:13:47 -07004833 } else if (dispatchEntry->eventEntry->type == EventEntry::Type::MOTION) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004834 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4835 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4836 handled);
4837 } else {
4838 restartEvent = false;
4839 }
4840
4841 // Dequeue the event and start the next cycle.
Siarhei Vishniakou850ce122020-05-26 22:39:43 -07004842 // Because the lock might have been released, it is possible that the
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004843 // contents of the wait queue to have been drained, so we need to double-check
4844 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004845 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4846 if (dispatchEntryIt != connection->waitQueue.end()) {
4847 dispatchEntry = *dispatchEntryIt;
4848 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004849 mAnrTracker.erase(dispatchEntry->timeoutTime,
4850 connection->inputChannel->getConnectionToken());
4851 if (!connection->responsive) {
4852 connection->responsive = isConnectionResponsive(*connection);
4853 }
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004854 traceWaitQueueLength(connection);
4855 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004856 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004857 traceOutboundQueueLength(connection);
4858 } else {
4859 releaseDispatchEntry(dispatchEntry);
4860 }
4861 }
4862
4863 // Start the next dispatch cycle for this connection.
4864 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865}
4866
4867bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004868 DispatchEntry* dispatchEntry,
4869 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004870 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004871 if (!handled) {
4872 // Report the key as unhandled, since the fallback was not handled.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08004873 mReporter->reportUnhandledKey(keyEntry->id);
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004874 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004875 return false;
4876 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004877
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004878 // Get the fallback key state.
4879 // Clear it out after dispatching the UP.
4880 int32_t originalKeyCode = keyEntry->keyCode;
4881 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4882 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4883 connection->inputState.removeFallbackKey(originalKeyCode);
4884 }
4885
4886 if (handled || !dispatchEntry->hasForegroundTarget()) {
4887 // If the application handles the original key for which we previously
4888 // generated a fallback or if the window is not a foreground window,
4889 // then cancel the associated fallback key, if any.
4890 if (fallbackKeyCode != -1) {
4891 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004893 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004894 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4895 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4896 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004898 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004899 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900
4901 mLock.unlock();
4902
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004903 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(), &event,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004904 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905
4906 mLock.lock();
4907
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004908 // Cancel the fallback key.
4909 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004911 "application handled the original non-fallback key "
4912 "or is no longer a foreground target, "
4913 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914 options.keyCode = fallbackKeyCode;
4915 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004917 connection->inputState.removeFallbackKey(originalKeyCode);
4918 }
4919 } else {
4920 // If the application did not handle a non-fallback key, first check
4921 // that we are in a good state to perform unhandled key event processing
4922 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004923 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004924 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004926 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004927 "since this is not an initial down. "
4928 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4929 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004931 return false;
4932 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004934 // Dispatch the unhandled key to the policy.
4935#if DEBUG_OUTBOUND_EVENT_DETAILS
4936 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004937 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4938 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004939#endif
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07004940 KeyEvent event = createKeyEvent(*keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004941
4942 mLock.unlock();
4943
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -07004944 bool fallback =
4945 mPolicy->dispatchUnhandledKey(connection->inputChannel->getConnectionToken(),
4946 &event, keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004947
4948 mLock.lock();
4949
4950 if (connection->status != Connection::STATUS_NORMAL) {
4951 connection->inputState.removeFallbackKey(originalKeyCode);
4952 return false;
4953 }
4954
4955 // Latch the fallback keycode for this key on an initial down.
4956 // The fallback keycode cannot change at any other point in the lifecycle.
4957 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004959 fallbackKeyCode = event.getKeyCode();
4960 } else {
4961 fallbackKeyCode = AKEYCODE_UNKNOWN;
4962 }
4963 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4964 }
4965
4966 ALOG_ASSERT(fallbackKeyCode != -1);
4967
4968 // Cancel the fallback key if the policy decides not to send it anymore.
4969 // We will continue to dispatch the key to the policy but we will no
4970 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004971 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4972 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004973#if DEBUG_OUTBOUND_EVENT_DETAILS
4974 if (fallback) {
4975 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004976 "as a fallback for %d, but on the DOWN it had requested "
4977 "to send %d instead. Fallback canceled.",
4978 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004979 } else {
4980 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004981 "but on the DOWN it had requested to send %d. "
4982 "Fallback canceled.",
4983 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004984 }
4985#endif
4986
4987 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4988 "canceling fallback, policy no longer desires it");
4989 options.keyCode = fallbackKeyCode;
4990 synthesizeCancelationEventsForConnectionLocked(connection, options);
4991
4992 fallback = false;
4993 fallbackKeyCode = AKEYCODE_UNKNOWN;
4994 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004995 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004996 }
4997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004998
4999#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005000 {
5001 std::string msg;
5002 const KeyedVector<int32_t, int32_t>& fallbackKeys =
5003 connection->inputState.getFallbackKeys();
5004 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005005 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005007 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005008 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005009 }
5010#endif
5011
5012 if (fallback) {
5013 // Restart the dispatch cycle using the fallback key.
5014 keyEntry->eventTime = event.getEventTime();
5015 keyEntry->deviceId = event.getDeviceId();
5016 keyEntry->source = event.getSource();
5017 keyEntry->displayId = event.getDisplayId();
5018 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
5019 keyEntry->keyCode = fallbackKeyCode;
5020 keyEntry->scanCode = event.getScanCode();
5021 keyEntry->metaState = event.getMetaState();
5022 keyEntry->repeatCount = event.getRepeatCount();
5023 keyEntry->downTime = event.getDownTime();
5024 keyEntry->syntheticRepeat = false;
5025
5026#if DEBUG_OUTBOUND_EVENT_DETAILS
5027 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005028 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
5029 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08005030#endif
5031 return true; // restart the event
5032 } else {
5033#if DEBUG_OUTBOUND_EVENT_DETAILS
5034 ALOGD("Unhandled key event: No fallback key.");
5035#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08005036
5037 // Report the key as unhandled, since there is no fallback key.
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005038 mReporter->reportUnhandledKey(keyEntry->id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039 }
5040 }
5041 return false;
5042}
5043
5044bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07005045 DispatchEntry* dispatchEntry,
5046 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005047 return false;
5048}
5049
5050void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
5051 mLock.unlock();
5052
5053 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
5054
5055 mLock.lock();
5056}
5057
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005058KeyEvent InputDispatcher::createKeyEvent(const KeyEntry& entry) {
5059 KeyEvent event;
Garfield Tan6a5a14e2020-01-28 13:24:04 -08005060 event.initialize(entry.id, entry.deviceId, entry.source, entry.displayId, INVALID_HMAC,
Garfield Tan4cc839f2020-01-24 11:26:14 -08005061 entry.action, entry.flags, entry.keyCode, entry.scanCode, entry.metaState,
5062 entry.repeatCount, entry.downTime, entry.eventTime);
Siarhei Vishniakou9757f782019-10-29 12:53:08 -07005063 return event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005064}
5065
Siarhei Vishniakou767917f2020-03-24 20:49:09 -07005066void InputDispatcher::reportDispatchStatistics(std::chrono::nanoseconds eventDuration,
5067 const Connection& connection, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068 // TODO Write some statistics about how long we spend waiting.
5069}
5070
Siarhei Vishniakoude4bf152019-08-16 11:12:52 -05005071/**
5072 * Report the touch event latency to the statsd server.
5073 * Input events are reported for statistics if:
5074 * - This is a touchscreen event
5075 * - InputFilter is not enabled
5076 * - Event is not injected or synthesized
5077 *
5078 * Statistics should be reported before calling addValue, to prevent a fresh new sample
5079 * from getting aggregated with the "old" data.
5080 */
5081void InputDispatcher::reportTouchEventForStatistics(const MotionEntry& motionEntry)
5082 REQUIRES(mLock) {
5083 const bool reportForStatistics = (motionEntry.source == AINPUT_SOURCE_TOUCHSCREEN) &&
5084 !(motionEntry.isSynthesized()) && !mInputFilterEnabled;
5085 if (!reportForStatistics) {
5086 return;
5087 }
5088
5089 if (mTouchStatistics.shouldReport()) {
5090 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED, mTouchStatistics.getMin(),
5091 mTouchStatistics.getMax(), mTouchStatistics.getMean(),
5092 mTouchStatistics.getStDev(), mTouchStatistics.getCount());
5093 mTouchStatistics.reset();
5094 }
5095 const float latencyMicros = nanoseconds_to_microseconds(now() - motionEntry.eventTime);
5096 mTouchStatistics.addValue(latencyMicros);
5097}
5098
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099void InputDispatcher::traceInboundQueueLengthLocked() {
5100 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07005101 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102 }
5103}
5104
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005105void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106 if (ATRACE_ENABLED()) {
5107 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005108 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005109 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 }
5111}
5112
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08005113void InputDispatcher::traceWaitQueueLength(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), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07005117 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118 }
5119}
5120
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005121void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005122 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005124 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125 dumpDispatchStateLocked(dump);
5126
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005127 if (!mLastAnrState.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08005128 dump += "\nInput Dispatcher State at time of last ANR:\n";
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -07005129 dump += mLastAnrState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130 }
5131}
5132
5133void InputDispatcher::monitor() {
5134 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005135 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08005137 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138}
5139
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08005140/**
5141 * Wake up the dispatcher and wait until it processes all events and commands.
5142 * The notification of mDispatcherEnteredIdle is guaranteed to happen after wake(), so
5143 * this method can be safely called from any thread, as long as you've ensured that
5144 * the work you are interested in completing has already been queued.
5145 */
5146bool InputDispatcher::waitForIdle() {
5147 /**
5148 * Timeout should represent the longest possible time that a device might spend processing
5149 * events and commands.
5150 */
5151 constexpr std::chrono::duration TIMEOUT = 100ms;
5152 std::unique_lock lock(mLock);
5153 mLooper->wake();
5154 std::cv_status result = mDispatcherEnteredIdle.wait_for(lock, TIMEOUT);
5155 return result == std::cv_status::no_timeout;
5156}
5157
Vishnu Naire798b472020-07-23 13:52:21 -07005158/**
5159 * Sets focus to the window identified by the token. This must be called
5160 * after updating any input window handles.
5161 *
5162 * Params:
5163 * request.token - input channel token used to identify the window that should gain focus.
5164 * request.focusedToken - the token that the caller expects currently to be focused. If the
5165 * specified token does not match the currently focused window, this request will be dropped.
5166 * If the specified focused token matches the currently focused window, the call will succeed.
5167 * Set this to "null" if this call should succeed no matter what the currently focused token is.
5168 * request.timestamp - SYSTEM_TIME_MONOTONIC timestamp in nanos set by the client (wm)
5169 * when requesting the focus change. This determines which request gets
5170 * precedence if there is a focus change request from another source such as pointer down.
5171 */
Vishnu Nair7d3d00d2020-08-03 11:20:42 -07005172void InputDispatcher::setFocusedWindow(const FocusRequest& request) {}
5173
5174void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocusedWindowHandle,
5175 const sp<InputWindowHandle>& newFocusedWindowHandle,
5176 int32_t displayId, std::string_view reason) {
5177 if (oldFocusedWindowHandle) {
5178 if (DEBUG_FOCUS) {
5179 ALOGD("Focus left window: %s in display %" PRId32,
5180 oldFocusedWindowHandle->getName().c_str(), displayId);
5181 }
5182 std::shared_ptr<InputChannel> focusedInputChannel =
5183 getInputChannelLocked(oldFocusedWindowHandle->getToken());
5184 if (focusedInputChannel) {
5185 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
5186 "focus left window");
5187 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
5188 enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/, reason);
5189 }
5190 mFocusedWindowHandlesByDisplay.erase(displayId);
5191 }
5192 if (newFocusedWindowHandle) {
5193 if (DEBUG_FOCUS) {
5194 ALOGD("Focus entered window: %s in display %" PRId32,
5195 newFocusedWindowHandle->getName().c_str(), displayId);
5196 }
5197 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
5198 enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/, reason);
5199 }
5200
5201 if (mFocusedDisplayId == displayId) {
5202 notifyFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
5203 }
5204}
Garfield Tane84e6f92019-08-29 17:28:41 -07005205} // namespace android::inputdispatcher