blob: 039462e23bf29d73e2c258fb3fab64604da8c2bf [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
Michael Wright3dd60e22019-03-27 22:06:44 +000020#define LOG_NDEBUG 0
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.
38#define DEBUG_FOCUS 0
39
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
Garfield Tane84e6f92019-08-29 17:28:41 -070048#include "Connection.h"
49
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080051#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <limits.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070053#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080054#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070055#include <unistd.h>
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -070056#include <queue>
57#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058
Michael Wright2b3c3302018-03-02 17:19:13 +000059#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080060#include <android-base/stringprintf.h>
Robert Carr4e670e52018-08-15 13:26:12 -070061#include <binder/Binder.h>
Garfield Tan0fc2fa72019-08-29 17:22:15 -070062#include <log/log.h>
63#include <powermanager/PowerManager.h>
64#include <utils/Trace.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
66#define INDENT " "
67#define INDENT2 " "
68#define INDENT3 " "
69#define INDENT4 " "
70
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080071using android::base::StringPrintf;
72
Garfield Tane84e6f92019-08-29 17:28:41 -070073namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080074
75// Default input dispatching timeout if there is no focused application or paused window
76// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000077constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
79// Amount of time to allow for all pending events to be processed when an app switch
80// key is on the way. This is used to preempt input dispatch and drop input events
81// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000082constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080083
84// Amount of time to allow for an event to be dispatched (measured since its eventTime)
85// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000086constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080087
88// Amount of time to allow touch events to be streamed out to a connection before requiring
89// that the first event be finished. This value extends the ANR timeout by the specified
90// amount. For example, if streaming is allowed to get ahead by one second relative to the
91// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
94// 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
100// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +0000101constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
102
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103static inline nsecs_t now() {
104 return systemTime(SYSTEM_TIME_MONOTONIC);
105}
106
107static inline const char* toString(bool value) {
108 return value ? "true" : "false";
109}
110
111static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700112 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
113 AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114}
115
116static bool isValidKeyAction(int32_t action) {
117 switch (action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700118 case AKEY_EVENT_ACTION_DOWN:
119 case AKEY_EVENT_ACTION_UP:
120 return true;
121 default:
122 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800123 }
124}
125
126static bool validateKeyEvent(int32_t action) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700127 if (!isValidKeyAction(action)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800128 ALOGE("Key event has invalid action code 0x%x", action);
129 return false;
130 }
131 return true;
132}
133
Michael Wright7b159c92015-05-14 14:48:03 +0100134static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800135 switch (action & AMOTION_EVENT_ACTION_MASK) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700136 case AMOTION_EVENT_ACTION_DOWN:
137 case AMOTION_EVENT_ACTION_UP:
138 case AMOTION_EVENT_ACTION_CANCEL:
139 case AMOTION_EVENT_ACTION_MOVE:
140 case AMOTION_EVENT_ACTION_OUTSIDE:
141 case AMOTION_EVENT_ACTION_HOVER_ENTER:
142 case AMOTION_EVENT_ACTION_HOVER_MOVE:
143 case AMOTION_EVENT_ACTION_HOVER_EXIT:
144 case AMOTION_EVENT_ACTION_SCROLL:
145 return true;
146 case AMOTION_EVENT_ACTION_POINTER_DOWN:
147 case AMOTION_EVENT_ACTION_POINTER_UP: {
148 int32_t index = getMotionEventActionPointerIndex(action);
149 return index >= 0 && index < pointerCount;
150 }
151 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
152 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
153 return actionButton != 0;
154 default:
155 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800156 }
157}
158
Michael Wright7b159c92015-05-14 14:48:03 +0100159static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700160 const PointerProperties* pointerProperties) {
161 if (!isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800162 ALOGE("Motion event has invalid action code 0x%x", action);
163 return false;
164 }
165 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000166 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700167 pointerCount, MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800168 return false;
169 }
170 BitSet32 pointerIdBits;
171 for (size_t i = 0; i < pointerCount; i++) {
172 int32_t id = pointerProperties[i].id;
173 if (id < 0 || id > MAX_POINTER_ID) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700174 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", id,
175 MAX_POINTER_ID);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800176 return false;
177 }
178 if (pointerIdBits.hasBit(id)) {
179 ALOGE("Motion event has duplicate pointer id %d", id);
180 return false;
181 }
182 pointerIdBits.markBit(id);
183 }
184 return true;
185}
186
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800187static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800188 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800189 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190 return;
191 }
192
193 bool first = true;
194 Region::const_iterator cur = region.begin();
195 Region::const_iterator const tail = region.end();
196 while (cur != tail) {
197 if (first) {
198 first = false;
199 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800200 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800202 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 cur++;
204 }
205}
206
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700207/**
208 * Find the entry in std::unordered_map by key, and return it.
209 * If the entry is not found, return a default constructed entry.
210 *
211 * Useful when the entries are vectors, since an empty vector will be returned
212 * if the entry is not found.
213 * Also useful when the entries are sp<>. If an entry is not found, nullptr is returned.
214 */
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700215template <typename K, typename V>
216static V getValueByKey(const std::unordered_map<K, V>& map, K key) {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -0700217 auto it = map.find(key);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700218 return it != map.end() ? it->second : V{};
Tiger Huang721e26f2018-07-24 22:26:19 +0800219}
220
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700221/**
222 * Find the entry in std::unordered_map by value, and remove it.
223 * If more than one entry has the same value, then all matching
224 * key-value pairs will be removed.
225 *
226 * Return true if at least one value has been removed.
227 */
228template <typename K, typename V>
229static bool removeByValue(std::unordered_map<K, V>& map, const V& value) {
230 bool removed = false;
231 for (auto it = map.begin(); it != map.end();) {
232 if (it->second == value) {
233 it = map.erase(it);
234 removed = true;
235 } else {
236 it++;
237 }
238 }
239 return removed;
240}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241
242// --- InputDispatcher ---
243
Garfield Tan00f511d2019-06-12 16:55:40 -0700244InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy)
245 : mPolicy(policy),
246 mPendingEvent(nullptr),
247 mLastDropReason(DROP_REASON_NOT_DROPPED),
248 mAppSwitchSawKeyDown(false),
249 mAppSwitchDueTime(LONG_LONG_MAX),
250 mNextUnblockedEvent(nullptr),
251 mDispatchEnabled(false),
252 mDispatchFrozen(false),
253 mInputFilterEnabled(false),
254 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
255 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800257 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258
Yi Kong9b14ac62018-07-17 13:48:38 -0700259 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260
261 policy->getDispatcherConfiguration(&mConfig);
262}
263
264InputDispatcher::~InputDispatcher() {
265 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800266 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267
268 resetKeyRepeatLocked();
269 releasePendingEventLocked();
270 drainInboundQueueLocked();
271 }
272
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -0700273 while (!mConnectionsByFd.empty()) {
274 sp<Connection> connection = mConnectionsByFd.begin()->second;
275 unregisterInputChannel(connection->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800276 }
277}
278
279void InputDispatcher::dispatchOnce() {
280 nsecs_t nextWakeupTime = LONG_LONG_MAX;
281 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800282 std::scoped_lock _l(mLock);
283 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800284
285 // Run a dispatch loop if there are no pending commands.
286 // The dispatch loop might enqueue commands to run afterwards.
287 if (!haveCommandsLocked()) {
288 dispatchOnceInnerLocked(&nextWakeupTime);
289 }
290
291 // Run all pending commands if there are any.
292 // If any commands were run then force the next poll to wake up immediately.
293 if (runCommandsLockedInterruptible()) {
294 nextWakeupTime = LONG_LONG_MIN;
295 }
296 } // release lock
297
298 // Wait for callback or timeout or wake. (make sure we round up, not down)
299 nsecs_t currentTime = now();
300 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
301 mLooper->pollOnce(timeoutMillis);
302}
303
304void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
305 nsecs_t currentTime = now();
306
Jeff Browndc5992e2014-04-11 01:27:26 -0700307 // Reset the key repeat timer whenever normal dispatch is suspended while the
308 // device is in a non-interactive state. This is to ensure that we abort a key
309 // repeat if the device is just coming out of sleep.
310 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800311 resetKeyRepeatLocked();
312 }
313
314 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
315 if (mDispatchFrozen) {
316#if DEBUG_FOCUS
317 ALOGD("Dispatch frozen. Waiting some more.");
318#endif
319 return;
320 }
321
322 // Optimize latency of app switches.
323 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
324 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
325 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
326 if (mAppSwitchDueTime < *nextWakeupTime) {
327 *nextWakeupTime = mAppSwitchDueTime;
328 }
329
330 // Ready to start a new event.
331 // If we don't already have a pending event, go grab one.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700332 if (!mPendingEvent) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700333 if (mInboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800334 if (isAppSwitchDue) {
335 // The inbound queue is empty so the app switch key we were waiting
336 // for will never arrive. Stop waiting for it.
337 resetPendingAppSwitchLocked(false);
338 isAppSwitchDue = false;
339 }
340
341 // Synthesize a key repeat if appropriate.
342 if (mKeyRepeatState.lastKeyEntry) {
343 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
344 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
345 } else {
346 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
347 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
348 }
349 }
350 }
351
352 // Nothing to do if there is no pending event.
353 if (!mPendingEvent) {
354 return;
355 }
356 } else {
357 // Inbound queue has at least one entry.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700358 mPendingEvent = mInboundQueue.front();
359 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800360 traceInboundQueueLengthLocked();
361 }
362
363 // Poke user activity for this event.
364 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
365 pokeUserActivityLocked(mPendingEvent);
366 }
367
368 // Get ready to dispatch the event.
369 resetANRTimeoutsLocked();
370 }
371
372 // Now we have an event to dispatch.
373 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700374 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800375 bool done = false;
376 DropReason dropReason = DROP_REASON_NOT_DROPPED;
377 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
378 dropReason = DROP_REASON_POLICY;
379 } else if (!mDispatchEnabled) {
380 dropReason = DROP_REASON_DISABLED;
381 }
382
383 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700384 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800385 }
386
387 switch (mPendingEvent->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700388 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
389 ConfigurationChangedEntry* typedEntry =
390 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
391 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
392 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
393 break;
394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800395
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700396 case EventEntry::TYPE_DEVICE_RESET: {
397 DeviceResetEntry* typedEntry = static_cast<DeviceResetEntry*>(mPendingEvent);
398 done = dispatchDeviceResetLocked(currentTime, typedEntry);
399 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
400 break;
401 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800402
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700403 case EventEntry::TYPE_KEY: {
404 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
405 if (isAppSwitchDue) {
406 if (isAppSwitchKeyEvent(typedEntry)) {
407 resetPendingAppSwitchLocked(true);
408 isAppSwitchDue = false;
409 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
410 dropReason = DROP_REASON_APP_SWITCH;
411 }
412 }
413 if (dropReason == DROP_REASON_NOT_DROPPED && isStaleEvent(currentTime, typedEntry)) {
414 dropReason = DROP_REASON_STALE;
415 }
416 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
417 dropReason = DROP_REASON_BLOCKED;
418 }
419 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
420 break;
421 }
422
423 case EventEntry::TYPE_MOTION: {
424 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
425 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 dropReason = DROP_REASON_APP_SWITCH;
427 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700428 if (dropReason == DROP_REASON_NOT_DROPPED && isStaleEvent(currentTime, typedEntry)) {
429 dropReason = DROP_REASON_STALE;
430 }
431 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
432 dropReason = DROP_REASON_BLOCKED;
433 }
434 done = dispatchMotionLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
435 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700438 default:
439 ALOG_ASSERT(false);
440 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800441 }
442
443 if (done) {
444 if (dropReason != DROP_REASON_NOT_DROPPED) {
445 dropInboundEventLocked(mPendingEvent, dropReason);
446 }
Michael Wright3a981722015-06-10 15:26:13 +0100447 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448
449 releasePendingEventLocked();
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700450 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
Michael Wrightd02c5b62014-02-10 15:10:22 -0800451 }
452}
453
454bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700455 bool needWake = mInboundQueue.empty();
456 mInboundQueue.push_back(entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800457 traceInboundQueueLengthLocked();
458
459 switch (entry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700460 case EventEntry::TYPE_KEY: {
461 // Optimize app switch latency.
462 // If the application takes too long to catch up then we drop all events preceding
463 // the app switch key.
464 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
465 if (isAppSwitchKeyEvent(keyEntry)) {
466 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
467 mAppSwitchSawKeyDown = true;
468 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
469 if (mAppSwitchSawKeyDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470#if DEBUG_APP_SWITCH
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700471 ALOGD("App switch is pending!");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700473 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
474 mAppSwitchSawKeyDown = false;
475 needWake = true;
476 }
477 }
478 }
479 break;
480 }
481
482 case EventEntry::TYPE_MOTION: {
483 // Optimize case where the current application is unresponsive and the user
484 // decides to touch a window in a different application.
485 // If the application takes too long to catch up then we drop all events preceding
486 // the touch into the other window.
487 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
488 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN &&
489 (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
490 mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY &&
491 mInputTargetWaitApplicationToken != nullptr) {
492 int32_t displayId = motionEntry->displayId;
493 int32_t x =
494 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
495 int32_t y =
496 int32_t(motionEntry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
497 sp<InputWindowHandle> touchedWindowHandle =
498 findTouchedWindowAtLocked(displayId, x, y);
499 if (touchedWindowHandle != nullptr &&
500 touchedWindowHandle->getApplicationToken() !=
501 mInputTargetWaitApplicationToken) {
502 // User touched a different application than the one we are waiting on.
503 // Flag the event, and start pruning the input queue.
504 mNextUnblockedEvent = motionEntry;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 needWake = true;
506 }
507 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700508 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 }
511
512 return needWake;
513}
514
515void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
516 entry->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700517 mRecentQueue.push_back(entry);
518 if (mRecentQueue.size() > RECENT_QUEUE_MAX_SIZE) {
519 mRecentQueue.front()->release();
520 mRecentQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521 }
522}
523
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700524sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, int32_t x,
525 int32_t y, bool addOutsideTargets,
526 bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800528 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
529 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 const InputWindowInfo* windowInfo = windowHandle->getInfo();
531 if (windowInfo->displayId == displayId) {
532 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533
534 if (windowInfo->visible) {
535 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700536 bool isTouchModal = (flags &
537 (InputWindowInfo::FLAG_NOT_FOCUSABLE |
538 InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800540 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700541 if (portalToDisplayId != ADISPLAY_ID_NONE &&
542 portalToDisplayId != displayId) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800543 if (addPortalWindows) {
544 // For the monitoring channels of the display.
545 mTempTouchState.addPortalWindow(windowHandle);
546 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700547 return findTouchedWindowAtLocked(portalToDisplayId, x, y,
548 addOutsideTargets, addPortalWindows);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 // Found window.
551 return windowHandle;
552 }
553 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800554
555 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700556 mTempTouchState.addOrUpdateWindow(windowHandle,
557 InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
558 BitSet32(0));
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800559 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561 }
562 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700563 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564}
565
Garfield Tane84e6f92019-08-29 17:28:41 -0700566std::vector<TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +0000567 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
568 std::vector<TouchedMonitor> touchedMonitors;
569
570 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
571 addGestureMonitors(monitors, touchedMonitors);
572 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
573 const InputWindowInfo* windowInfo = portalWindow->getInfo();
574 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700575 addGestureMonitors(monitors, touchedMonitors, -windowInfo->frameLeft,
576 -windowInfo->frameTop);
Michael Wright3dd60e22019-03-27 22:06:44 +0000577 }
578 return touchedMonitors;
579}
580
581void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700582 std::vector<TouchedMonitor>& outTouchedMonitors,
583 float xOffset, float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000584 if (monitors.empty()) {
585 return;
586 }
587 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
588 for (const Monitor& monitor : monitors) {
589 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
590 }
591}
592
Michael Wrightd02c5b62014-02-10 15:10:22 -0800593void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
594 const char* reason;
595 switch (dropReason) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700596 case DROP_REASON_POLICY:
Michael Wrightd02c5b62014-02-10 15:10:22 -0800597#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700598 ALOGD("Dropped event because policy consumed it.");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700600 reason = "inbound event was dropped because the policy consumed it";
601 break;
602 case DROP_REASON_DISABLED:
603 if (mLastDropReason != DROP_REASON_DISABLED) {
604 ALOGI("Dropped event because input dispatch is disabled.");
605 }
606 reason = "inbound event was dropped because input dispatch is disabled";
607 break;
608 case DROP_REASON_APP_SWITCH:
609 ALOGI("Dropped event because of pending overdue app switch.");
610 reason = "inbound event was dropped because of pending overdue app switch";
611 break;
612 case DROP_REASON_BLOCKED:
613 ALOGI("Dropped event because the current application is not responding and the user "
614 "has started interacting with a different application.");
615 reason = "inbound event was dropped because the current application is not responding "
616 "and the user has started interacting with a different application";
617 break;
618 case DROP_REASON_STALE:
619 ALOGI("Dropped event because it is stale.");
620 reason = "inbound event was dropped because it is stale";
621 break;
622 default:
623 ALOG_ASSERT(false);
624 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 }
626
627 switch (entry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700628 case EventEntry::TYPE_KEY: {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800629 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
630 synthesizeCancelationEventsForAllConnectionsLocked(options);
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700631 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700633 case EventEntry::TYPE_MOTION: {
634 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
635 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
636 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
637 synthesizeCancelationEventsForAllConnectionsLocked(options);
638 } else {
639 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
640 synthesizeCancelationEventsForAllConnectionsLocked(options);
641 }
642 break;
643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644 }
645}
646
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800647static bool isAppSwitchKeyCode(int32_t keyCode) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700648 return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL ||
649 keyCode == AKEYCODE_APP_SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650}
651
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800652bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700653 return !(keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) && isAppSwitchKeyCode(keyEntry->keyCode) &&
654 (keyEntry->policyFlags & POLICY_FLAG_TRUSTED) &&
655 (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656}
657
658bool InputDispatcher::isAppSwitchPendingLocked() {
659 return mAppSwitchDueTime != LONG_LONG_MAX;
660}
661
662void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
663 mAppSwitchDueTime = LONG_LONG_MAX;
664
665#if DEBUG_APP_SWITCH
666 if (handled) {
667 ALOGD("App switch has arrived.");
668 } else {
669 ALOGD("App switch was abandoned.");
670 }
671#endif
672}
673
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800674bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
676}
677
678bool InputDispatcher::haveCommandsLocked() const {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700679 return !mCommandQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680}
681
682bool InputDispatcher::runCommandsLockedInterruptible() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700683 if (mCommandQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684 return false;
685 }
686
687 do {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700688 std::unique_ptr<CommandEntry> commandEntry = std::move(mCommandQueue.front());
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700689 mCommandQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 Command command = commandEntry->command;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700691 command(*this, commandEntry.get()); // commands are implicitly 'LockedInterruptible'
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692
693 commandEntry->connection.clear();
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700694 } while (!mCommandQueue.empty());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695 return true;
696}
697
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700698void InputDispatcher::postCommandLocked(std::unique_ptr<CommandEntry> commandEntry) {
699 mCommandQueue.push_back(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700}
701
702void InputDispatcher::drainInboundQueueLocked() {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -0700703 while (!mInboundQueue.empty()) {
704 EventEntry* entry = mInboundQueue.front();
705 mInboundQueue.pop_front();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706 releaseInboundEventLocked(entry);
707 }
708 traceInboundQueueLengthLocked();
709}
710
711void InputDispatcher::releasePendingEventLocked() {
712 if (mPendingEvent) {
713 resetANRTimeoutsLocked();
714 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700715 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 }
717}
718
719void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
720 InjectionState* injectionState = entry->injectionState;
721 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
722#if DEBUG_DISPATCH_CYCLE
723 ALOGD("Injected inbound event was dropped.");
724#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800725 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726 }
727 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700728 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 }
730 addRecentEventLocked(entry);
731 entry->release();
732}
733
734void InputDispatcher::resetKeyRepeatLocked() {
735 if (mKeyRepeatState.lastKeyEntry) {
736 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700737 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 }
739}
740
Garfield Tane84e6f92019-08-29 17:28:41 -0700741KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
743
744 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700745 uint32_t policyFlags = entry->policyFlags &
746 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800747 if (entry->refCount == 1) {
748 entry->recycle();
749 entry->eventTime = currentTime;
750 entry->policyFlags = policyFlags;
751 entry->repeatCount += 1;
752 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700753 KeyEntry* newEntry =
754 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime, entry->deviceId,
755 entry->source, entry->displayId, policyFlags, entry->action,
756 entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
757 entry->repeatCount + 1, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800758
759 mKeyRepeatState.lastKeyEntry = newEntry;
760 entry->release();
761
762 entry = newEntry;
763 }
764 entry->syntheticRepeat = true;
765
766 // Increment reference count since we keep a reference to the event in
767 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
768 entry->refCount += 1;
769
770 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
771 return entry;
772}
773
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700774bool InputDispatcher::dispatchConfigurationChangedLocked(nsecs_t currentTime,
775 ConfigurationChangedEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800776#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700777 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778#endif
779
780 // Reset key repeating in case a keyboard device was added or removed or something.
781 resetKeyRepeatLocked();
782
783 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700784 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
785 &InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800786 commandEntry->eventTime = entry->eventTime;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700787 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 return true;
789}
790
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700791bool InputDispatcher::dispatchDeviceResetLocked(nsecs_t currentTime, DeviceResetEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700793 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700794 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795#endif
796
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700797 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, "device was reset");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800798 options.deviceId = entry->deviceId;
799 synthesizeCancelationEventsForAllConnectionsLocked(options);
800 return true;
801}
802
803bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700804 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700806 if (!entry->dispatchInProgress) {
807 if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN &&
808 (entry->policyFlags & POLICY_FLAG_TRUSTED) &&
809 (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
810 if (mKeyRepeatState.lastKeyEntry &&
811 mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 // We have seen two identical key downs in a row which indicates that the device
813 // driver is automatically generating key repeats itself. We take note of the
814 // repeat here, but we disable our own next key repeat timer since it is clear that
815 // we will not need to synthesize key repeats ourselves.
816 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
817 resetKeyRepeatLocked();
818 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
819 } else {
820 // Not a repeat. Save key down state in case we do see a repeat later.
821 resetKeyRepeatLocked();
822 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
823 }
824 mKeyRepeatState.lastKeyEntry = entry;
825 entry->refCount += 1;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700826 } else if (!entry->syntheticRepeat) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 resetKeyRepeatLocked();
828 }
829
830 if (entry->repeatCount == 1) {
831 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
832 } else {
833 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
834 }
835
836 entry->dispatchInProgress = true;
837
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800838 logOutboundKeyDetails("dispatchKey - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 }
840
841 // Handle case where the policy asked us to try again later last time.
842 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
843 if (currentTime < entry->interceptKeyWakeupTime) {
844 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
845 *nextWakeupTime = entry->interceptKeyWakeupTime;
846 }
847 return false; // wait until next wakeup
848 }
849 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
850 entry->interceptKeyWakeupTime = 0;
851 }
852
853 // Give the policy a chance to intercept the key.
854 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
855 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700856 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
Siarhei Vishniakou49a350a2019-07-26 18:44:23 -0700857 &InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800858 sp<InputWindowHandle> focusedWindowHandle =
859 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
860 if (focusedWindowHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700861 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 }
863 commandEntry->keyEntry = entry;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -0700864 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 entry->refCount += 1;
866 return false; // wait for the command to run
867 } else {
868 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
869 }
870 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
871 if (*dropReason == DROP_REASON_NOT_DROPPED) {
872 *dropReason = DROP_REASON_POLICY;
873 }
874 }
875
876 // Clean up if dropping the event.
877 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700878 setInjectionResult(entry,
879 *dropReason == DROP_REASON_POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
880 : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800881 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 return true;
883 }
884
885 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800886 std::vector<InputTarget> inputTargets;
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700887 int32_t injectionResult =
888 findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
890 return false;
891 }
892
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800893 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
895 return true;
896 }
897
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800898 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000899 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900
901 // Dispatch the key.
902 dispatchEventLocked(currentTime, entry, inputTargets);
903 return true;
904}
905
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800906void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100908 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700909 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
910 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
911 prefix, entry->eventTime, entry->deviceId, entry->source, entry->displayId,
912 entry->policyFlags, entry->action, entry->flags, entry->keyCode, entry->scanCode,
913 entry->metaState, entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914#endif
915}
916
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700917bool InputDispatcher::dispatchMotionLocked(nsecs_t currentTime, MotionEntry* entry,
918 DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000919 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 // Preprocessing.
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700921 if (!entry->dispatchInProgress) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 entry->dispatchInProgress = true;
923
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800924 logOutboundMotionDetails("dispatchMotion - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 }
926
927 // Clean up if dropping the event.
928 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700929 setInjectionResult(entry,
930 *dropReason == DROP_REASON_POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED
931 : INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 return true;
933 }
934
935 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
936
937 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800938 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939
940 bool conflictingPointerActions = false;
941 int32_t injectionResult;
942 if (isPointerEvent) {
943 // Pointer event. (eg. touchscreen)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700944 injectionResult =
945 findTouchedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime,
946 &conflictingPointerActions);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 } else {
948 // Non touch event. (eg. trackball)
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700949 injectionResult =
950 findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 }
952 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
953 return false;
954 }
955
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800956 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100958 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700959 CancelationOptions::Mode mode(isPointerEvent
960 ? CancelationOptions::CANCEL_POINTER_EVENTS
961 : CancelationOptions::CANCEL_NON_POINTER_EVENTS);
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100962 CancelationOptions options(mode, "input event injection failed");
963 synthesizeCancelationEventsForMonitorsLocked(options);
964 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 return true;
966 }
967
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800968 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000969 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800970
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800971 if (isPointerEvent) {
972 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
973 if (stateIndex >= 0) {
974 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800975 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800976 // The event has gone through these portal windows, so we add monitoring targets of
977 // the corresponding displays as well.
978 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800979 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +0000980 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700981 -windowInfo->frameLeft, -windowInfo->frameTop);
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800982 }
983 }
984 }
985 }
986
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 // Dispatch the motion.
988 if (conflictingPointerActions) {
989 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -0700990 "conflicting pointer actions");
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 synthesizeCancelationEventsForAllConnectionsLocked(options);
992 }
993 dispatchEventLocked(currentTime, entry, inputTargets);
994 return true;
995}
996
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800997void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800999 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001000 ", policyFlags=0x%x, "
1001 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1002 "metaState=0x%x, buttonState=0x%x,"
1003 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
1004 prefix, entry->eventTime, entry->deviceId, entry->source, entry->displayId,
1005 entry->policyFlags, entry->action, entry->actionButton, entry->flags, entry->metaState,
1006 entry->buttonState, entry->edgeFlags, entry->xPrecision, entry->yPrecision,
1007 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008
1009 for (uint32_t i = 0; i < entry->pointerCount; i++) {
1010 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001011 "x=%f, y=%f, pressure=%f, size=%f, "
1012 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
1013 "orientation=%f",
1014 i, entry->pointerProperties[i].id, entry->pointerProperties[i].toolType,
1015 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1016 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1017 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1018 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1019 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1020 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1021 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1022 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
1023 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 }
1025#endif
1026}
1027
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001028void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, EventEntry* eventEntry,
1029 const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001030 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031#if DEBUG_DISPATCH_CYCLE
1032 ALOGD("dispatchEventToCurrentInputTargets");
1033#endif
1034
1035 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1036
1037 pokeUserActivityLocked(eventEntry);
1038
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001039 for (const InputTarget& inputTarget : inputTargets) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001040 sp<Connection> connection = getConnectionLocked(inputTarget.inputChannel);
1041 if (connection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1043 } else {
1044#if DEBUG_FOCUS
1045 ALOGD("Dropping event delivery to target with channel '%s' because it "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001046 "is no longer registered with the input dispatcher.",
1047 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048#endif
1049 }
1050 }
1051}
1052
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001053int32_t InputDispatcher::handleTargetsNotReadyLocked(
1054 nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 const sp<InputApplicationHandle>& applicationHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001056 const sp<InputWindowHandle>& windowHandle, nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001057 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1059#if DEBUG_FOCUS
1060 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1061#endif
1062 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1063 mInputTargetWaitStartTime = currentTime;
1064 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1065 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001066 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067 }
1068 } else {
1069 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1070#if DEBUG_FOCUS
1071 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001072 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073#endif
1074 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001075 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001077 } else if (applicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001078 timeout =
1079 applicationHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 } else {
1081 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1082 }
1083
1084 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1085 mInputTargetWaitStartTime = currentTime;
1086 mInputTargetWaitTimeoutTime = currentTime + timeout;
1087 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001088 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089
Yi Kong9b14ac62018-07-17 13:48:38 -07001090 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001091 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 }
Robert Carr740167f2018-10-11 19:03:41 -07001093 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1094 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 }
1096 }
1097 }
1098
1099 if (mInputTargetWaitTimeoutExpired) {
1100 return INPUT_EVENT_INJECTION_TIMED_OUT;
1101 }
1102
1103 if (currentTime >= mInputTargetWaitTimeoutTime) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001104 onANRLocked(currentTime, applicationHandle, windowHandle, entry->eventTime,
1105 mInputTargetWaitStartTime, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106
1107 // Force poll loop to wake up immediately on next iteration once we get the
1108 // ANR response back from the policy.
1109 *nextWakeupTime = LONG_LONG_MIN;
1110 return INPUT_EVENT_INJECTION_PENDING;
1111 } else {
1112 // Force poll loop to wake up when timeout is due.
1113 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1114 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1115 }
1116 return INPUT_EVENT_INJECTION_PENDING;
1117 }
1118}
1119
Robert Carr803535b2018-08-02 16:38:15 -07001120void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1121 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1122 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1123 state.removeWindowByToken(token);
1124 }
1125}
1126
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001127void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(
1128 nsecs_t newTimeout, const sp<InputChannel>& inputChannel) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001129 if (newTimeout > 0) {
1130 // Extend the timeout.
1131 mInputTargetWaitTimeoutTime = now() + newTimeout;
1132 } else {
1133 // Give up.
1134 mInputTargetWaitTimeoutExpired = true;
1135
1136 // Input state will not be realistic. Mark it out of sync.
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001137 sp<Connection> connection = getConnectionLocked(inputChannel);
1138 if (connection != nullptr) {
1139 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001141 if (token != nullptr) {
1142 removeWindowByTokenLocked(token);
1143 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001145 if (connection->status == Connection::STATUS_NORMAL) {
1146 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1147 "application not responding");
1148 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 }
1150 }
1151 }
1152}
1153
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001154nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001155 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1156 return currentTime - mInputTargetWaitStartTime;
1157 }
1158 return 0;
1159}
1160
1161void InputDispatcher::resetANRTimeoutsLocked() {
1162#if DEBUG_FOCUS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001163 ALOGD("Resetting ANR timeouts.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164#endif
1165
1166 // Reset input target wait timeout.
1167 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001168 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169}
1170
Tiger Huang721e26f2018-07-24 22:26:19 +08001171/**
1172 * Get the display id that the given event should go to. If this event specifies a valid display id,
1173 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1174 * Focused display is the display that the user most recently interacted with.
1175 */
1176int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1177 int32_t displayId;
1178 switch (entry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001179 case EventEntry::TYPE_KEY: {
1180 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1181 displayId = typedEntry->displayId;
1182 break;
1183 }
1184 case EventEntry::TYPE_MOTION: {
1185 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1186 displayId = typedEntry->displayId;
1187 break;
1188 }
1189 default: {
1190 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1191 return ADISPLAY_ID_NONE;
1192 }
Tiger Huang721e26f2018-07-24 22:26:19 +08001193 }
1194 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1195}
1196
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001198 const EventEntry* entry,
1199 std::vector<InputTarget>& inputTargets,
1200 nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001202 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203
Tiger Huang721e26f2018-07-24 22:26:19 +08001204 int32_t displayId = getTargetDisplayId(entry);
1205 sp<InputWindowHandle> focusedWindowHandle =
1206 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1207 sp<InputApplicationHandle> focusedApplicationHandle =
1208 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1209
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 // If there is no currently focused window and no focused application
1211 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001212 if (focusedWindowHandle == nullptr) {
1213 if (focusedApplicationHandle != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001214 injectionResult =
1215 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1216 nullptr, nextWakeupTime,
1217 "Waiting because no window has focus but there is "
1218 "a focused application that may eventually add a "
1219 "window when it finishes starting up.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 goto Unresponsive;
1221 }
1222
Arthur Hung3b413f22018-10-26 18:05:34 +08001223 ALOGI("Dropping event because there is no focused window or focused application in display "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001224 "%" PRId32 ".",
1225 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1227 goto Failed;
1228 }
1229
1230 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001231 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1233 goto Failed;
1234 }
1235
Jeff Brownffb49772014-10-10 19:01:34 -07001236 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001237 reason = checkWindowReadyForMoreInputLocked(currentTime, focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001238 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001239 injectionResult =
1240 handleTargetsNotReadyLocked(currentTime, entry, focusedApplicationHandle,
1241 focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 goto Unresponsive;
1243 }
1244
1245 // Success! Output targets.
1246 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001247 addWindowTargetLocked(focusedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001248 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS,
1249 BitSet32(0), inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250
1251 // Done.
1252Failed:
1253Unresponsive:
1254 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001255 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001256#if DEBUG_FOCUS
1257 ALOGD("findFocusedWindow finished: injectionResult=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001258 "timeSpentWaitingForApplication=%0.1fms",
1259 injectionResult, timeSpentWaitingForApplication / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260#endif
1261 return injectionResult;
1262}
1263
1264int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001265 const MotionEntry* entry,
1266 std::vector<InputTarget>& inputTargets,
1267 nsecs_t* nextWakeupTime,
1268 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001269 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 enum InjectionPermission {
1271 INJECTION_PERMISSION_UNKNOWN,
1272 INJECTION_PERMISSION_GRANTED,
1273 INJECTION_PERMISSION_DENIED
1274 };
1275
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 // For security reasons, we defer updating the touch state until we are sure that
1277 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 int32_t displayId = entry->displayId;
1279 int32_t action = entry->action;
1280 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1281
1282 // Update the touch state as needed based on the properties of the touch event.
1283 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1284 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1285 sp<InputWindowHandle> newHoverWindowHandle;
1286
Jeff Brownf086ddb2014-02-11 14:28:48 -08001287 // Copy current touch state into mTempTouchState.
1288 // This state is always reset at the end of this function, so if we don't find state
1289 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001290 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001291 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1292 if (oldStateIndex >= 0) {
1293 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1294 mTempTouchState.copyFrom(*oldState);
1295 }
1296
1297 bool isSplit = mTempTouchState.split;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001298 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0 &&
1299 (mTempTouchState.deviceId != entry->deviceId ||
1300 mTempTouchState.source != entry->source || mTempTouchState.displayId != displayId);
1301 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE ||
1302 maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1303 maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1304 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
1305 maskedAction == AMOTION_EVENT_ACTION_SCROLL || isHoverAction);
Garfield Tan00f511d2019-06-12 16:55:40 -07001306 const bool isFromMouse = entry->source == AINPUT_SOURCE_MOUSE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 bool wrongDevice = false;
1308 if (newGesture) {
1309 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001310 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001312 ALOGD("Dropping event because a pointer for a different device is already down "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001313 "in display %" PRId32,
1314 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001316 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1318 switchedDevice = false;
1319 wrongDevice = true;
1320 goto Failed;
1321 }
1322 mTempTouchState.reset();
1323 mTempTouchState.down = down;
1324 mTempTouchState.deviceId = entry->deviceId;
1325 mTempTouchState.source = entry->source;
1326 mTempTouchState.displayId = displayId;
1327 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001328 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1329#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001330 ALOGI("Dropping move event because a pointer for a different device is already active "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001331 "in display %" PRId32,
1332 displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001333#endif
1334 // TODO: test multiple simultaneous input streams.
1335 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1336 switchedDevice = false;
1337 wrongDevice = true;
1338 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 }
1340
1341 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1342 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1343
Garfield Tan00f511d2019-06-12 16:55:40 -07001344 int32_t x;
1345 int32_t y;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
Garfield Tan00f511d2019-06-12 16:55:40 -07001347 // Always dispatch mouse events to cursor position.
1348 if (isFromMouse) {
1349 x = int32_t(entry->xCursorPosition);
1350 y = int32_t(entry->yCursorPosition);
1351 } else {
1352 x = int32_t(entry->pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_X));
1353 y = int32_t(entry->pointerCoords[pointerIndex].getAxisValue(AMOTION_EVENT_AXIS_Y));
1354 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001355 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001356 sp<InputWindowHandle> newTouchedWindowHandle =
1357 findTouchedWindowAtLocked(displayId, x, y, isDown /*addOutsideTargets*/,
1358 true /*addPortalWindows*/);
Michael Wright3dd60e22019-03-27 22:06:44 +00001359
1360 std::vector<TouchedMonitor> newGestureMonitors = isDown
1361 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1362 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363
Michael Wrightd02c5b62014-02-10 15:10:22 -08001364 // Figure out whether splitting will be allowed for this window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001365 if (newTouchedWindowHandle != nullptr &&
1366 newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
Garfield Tanaddb02b2019-06-25 16:36:13 -07001367 // New window supports splitting, but we should never split mouse events.
1368 isSplit = !isFromMouse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369 } else if (isSplit) {
1370 // New window does not support splitting but we have already split events.
1371 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001372 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373 }
1374
1375 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001376 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 // Try to assign the pointer to the first foreground window we find, if there is one.
1378 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001379 }
1380
1381 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1382 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001383 "(%d, %d) in display %" PRId32 ".",
1384 x, y, displayId);
Michael Wright3dd60e22019-03-27 22:06:44 +00001385 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1386 goto Failed;
1387 }
1388
1389 if (newTouchedWindowHandle != nullptr) {
1390 // Set target flags.
1391 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1392 if (isSplit) {
1393 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001395 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1396 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1397 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1398 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1399 }
1400
1401 // Update hover state.
1402 if (isHoverAction) {
1403 newHoverWindowHandle = newTouchedWindowHandle;
1404 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1405 newHoverWindowHandle = mLastHoverWindowHandle;
1406 }
1407
1408 // Update the temporary touch state.
1409 BitSet32 pointerIds;
1410 if (isSplit) {
1411 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1412 pointerIds.markBit(pointerId);
1413 }
1414 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001415 }
1416
Michael Wright3dd60e22019-03-27 22:06:44 +00001417 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001418 } else {
1419 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1420
1421 // If the pointer is not currently down, then ignore the event.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001422 if (!mTempTouchState.down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423#if DEBUG_FOCUS
1424 ALOGD("Dropping event because the pointer is not down or we previously "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001425 "dropped the pointer down event in display %" PRId32,
1426 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427#endif
1428 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1429 goto Failed;
1430 }
1431
1432 // Check whether touches should slip outside of the current foreground window.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001433 if (maskedAction == AMOTION_EVENT_ACTION_MOVE && entry->pointerCount == 1 &&
1434 mTempTouchState.isSlippery()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1436 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1437
1438 sp<InputWindowHandle> oldTouchedWindowHandle =
1439 mTempTouchState.getFirstForegroundWindowHandle();
1440 sp<InputWindowHandle> newTouchedWindowHandle =
1441 findTouchedWindowAtLocked(displayId, x, y);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001442 if (oldTouchedWindowHandle != newTouchedWindowHandle &&
1443 oldTouchedWindowHandle != nullptr && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001445 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001446 oldTouchedWindowHandle->getName().c_str(),
1447 newTouchedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448#endif
1449 // Make a slippery exit from the old window.
1450 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001451 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT,
1452 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453
1454 // Make a slippery entrance into the new window.
1455 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1456 isSplit = true;
1457 }
1458
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001459 int32_t targetFlags =
1460 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461 if (isSplit) {
1462 targetFlags |= InputTarget::FLAG_SPLIT;
1463 }
1464 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1465 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1466 }
1467
1468 BitSet32 pointerIds;
1469 if (isSplit) {
1470 pointerIds.markBit(entry->pointerProperties[0].id);
1471 }
1472 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1473 }
1474 }
1475 }
1476
1477 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1478 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001479 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480#if DEBUG_HOVER
1481 ALOGD("Sending hover exit event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001482 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483#endif
1484 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001485 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT,
1486 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 }
1488
1489 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001490 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491#if DEBUG_HOVER
1492 ALOGD("Sending hover enter event to window %s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001493 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494#endif
1495 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001496 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER,
1497 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001498 }
1499 }
1500
1501 // Check permission to inject into all touched foreground windows and ensure there
1502 // is at least one touched foreground window.
1503 {
1504 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001505 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1507 haveForegroundWindow = true;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001508 if (!checkInjectionPermission(touchedWindow.windowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1510 injectionPermission = INJECTION_PERMISSION_DENIED;
1511 goto Failed;
1512 }
1513 }
1514 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001515 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1516 if (!haveForegroundWindow && !hasGestureMonitor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517#if DEBUG_FOCUS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001518 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1519 " or gesture monitor to receive it.",
1520 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001521#endif
1522 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1523 goto Failed;
1524 }
1525
1526 // Permission granted to injection into all touched foreground windows.
1527 injectionPermission = INJECTION_PERMISSION_GRANTED;
1528 }
1529
1530 // Check whether windows listening for outside touches are owned by the same UID. If it is
1531 // set the policy flag that we will not reveal coordinate information to this window.
1532 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1533 sp<InputWindowHandle> foregroundWindowHandle =
1534 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001535 if (foregroundWindowHandle) {
1536 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1537 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1538 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1539 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1540 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1541 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001542 InputTarget::FLAG_ZERO_COORDS,
1543 BitSet32(0));
Michael Wright3dd60e22019-03-27 22:06:44 +00001544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 }
1546 }
1547 }
1548 }
1549
1550 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001551 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001553 // Check whether the window is ready for more input.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001554 std::string reason =
1555 checkWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle,
1556 entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001557 if (!reason.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001558 injectionResult = handleTargetsNotReadyLocked(currentTime, entry, nullptr,
1559 touchedWindow.windowHandle,
1560 nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 goto Unresponsive;
1562 }
1563 }
1564 }
1565
1566 // If this is the first pointer going down and the touched window has a wallpaper
1567 // then also add the touched wallpaper windows so they are locked in for the duration
1568 // of the touch gesture.
1569 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1570 // engine only supports touch events. We would need to add a mechanism similar
1571 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1572 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1573 sp<InputWindowHandle> foregroundWindowHandle =
1574 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001575 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001576 const std::vector<sp<InputWindowHandle>> windowHandles =
1577 getWindowHandlesLocked(displayId);
1578 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 const InputWindowInfo* info = windowHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001580 if (info->displayId == displayId &&
1581 windowHandle->getInfo()->layoutParamsType == InputWindowInfo::TYPE_WALLPAPER) {
1582 mTempTouchState
1583 .addOrUpdateWindow(windowHandle,
1584 InputTarget::FLAG_WINDOW_IS_OBSCURED |
1585 InputTarget::
1586 FLAG_WINDOW_IS_PARTIALLY_OBSCURED |
1587 InputTarget::FLAG_DISPATCH_AS_IS,
1588 BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001589 }
1590 }
1591 }
1592 }
1593
1594 // Success! Output targets.
1595 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1596
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001597 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001599 touchedWindow.pointerIds, inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 }
1601
Michael Wright3dd60e22019-03-27 22:06:44 +00001602 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1603 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001604 touchedMonitor.yOffset, inputTargets);
Michael Wright3dd60e22019-03-27 22:06:44 +00001605 }
1606
Michael Wrightd02c5b62014-02-10 15:10:22 -08001607 // Drop the outside or hover touch windows since we will not care about them
1608 // in the next iteration.
1609 mTempTouchState.filterNonAsIsTouchWindows();
1610
1611Failed:
1612 // Check injection permission once and for all.
1613 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001614 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001615 injectionPermission = INJECTION_PERMISSION_GRANTED;
1616 } else {
1617 injectionPermission = INJECTION_PERMISSION_DENIED;
1618 }
1619 }
1620
1621 // Update final pieces of touch state if the injector had permission.
1622 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1623 if (!wrongDevice) {
1624 if (switchedDevice) {
1625#if DEBUG_FOCUS
1626 ALOGD("Conflicting pointer actions: Switched to a different device.");
1627#endif
1628 *outConflictingPointerActions = true;
1629 }
1630
1631 if (isHoverAction) {
1632 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001633 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634#if DEBUG_FOCUS
1635 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1636#endif
1637 *outConflictingPointerActions = true;
1638 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001639 mTempTouchState.reset();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001640 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER ||
1641 maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001642 mTempTouchState.deviceId = entry->deviceId;
1643 mTempTouchState.source = entry->source;
1644 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001646 } else if (maskedAction == AMOTION_EVENT_ACTION_UP ||
1647 maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001649 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1651 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001652 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653#if DEBUG_FOCUS
1654 ALOGD("Conflicting pointer actions: Down received while already down.");
1655#endif
1656 *outConflictingPointerActions = true;
1657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001658 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1659 // One pointer went up.
1660 if (isSplit) {
1661 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1662 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1663
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001664 for (size_t i = 0; i < mTempTouchState.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001665 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1667 touchedWindow.pointerIds.clearBit(pointerId);
1668 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001669 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 continue;
1671 }
1672 }
1673 i += 1;
1674 }
1675 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001676 }
1677
1678 // Save changes unless the action was scroll in which case the temporary touch
1679 // state was only valid for this one action.
1680 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1681 if (mTempTouchState.displayId >= 0) {
1682 if (oldStateIndex >= 0) {
1683 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1684 } else {
1685 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1686 }
1687 } else if (oldStateIndex >= 0) {
1688 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1689 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690 }
1691
1692 // Update hover state.
1693 mLastHoverWindowHandle = newHoverWindowHandle;
1694 }
1695 } else {
1696#if DEBUG_FOCUS
1697 ALOGD("Not updating touch focus because injection was denied.");
1698#endif
1699 }
1700
1701Unresponsive:
1702 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1703 mTempTouchState.reset();
1704
1705 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001706 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707#if DEBUG_FOCUS
1708 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001709 "timeSpentWaitingForApplication=%0.1fms",
1710 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711#endif
1712 return injectionResult;
1713}
1714
1715void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001716 int32_t targetFlags, BitSet32 pointerIds,
1717 std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001718 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1719 if (inputChannel == nullptr) {
1720 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1721 return;
1722 }
1723
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001725 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001726 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001727 target.flags = targetFlags;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001728 target.xOffset = -windowInfo->frameLeft;
1729 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001730 target.globalScaleFactor = windowInfo->globalScaleFactor;
1731 target.windowXScale = windowInfo->windowXScale;
1732 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001734 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735}
1736
Michael Wright3dd60e22019-03-27 22:06:44 +00001737void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001738 int32_t displayId, float xOffset,
1739 float yOffset) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001740 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1741 mGlobalMonitorsByDisplay.find(displayId);
1742
1743 if (it != mGlobalMonitorsByDisplay.end()) {
1744 const std::vector<Monitor>& monitors = it->second;
1745 for (const Monitor& monitor : monitors) {
1746 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 }
1749}
1750
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001751void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor, float xOffset,
1752 float yOffset,
1753 std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001754 InputTarget target;
1755 target.inputChannel = monitor.inputChannel;
1756 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1757 target.xOffset = xOffset;
1758 target.yOffset = yOffset;
1759 target.pointerIds.clear();
1760 target.globalScaleFactor = 1.0f;
1761 inputTargets.push_back(target);
1762}
1763
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001765 const InjectionState* injectionState) {
1766 if (injectionState &&
1767 (windowHandle == nullptr ||
1768 windowHandle->getInfo()->ownerUid != injectionState->injectorUid) &&
1769 !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001770 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001772 "owned by uid %d",
1773 injectionState->injectorPid, injectionState->injectorUid,
1774 windowHandle->getName().c_str(), windowHandle->getInfo()->ownerUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775 } else {
1776 ALOGW("Permission denied: injecting event from pid %d uid %d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001777 injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778 }
1779 return false;
1780 }
1781 return true;
1782}
1783
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001784bool InputDispatcher::isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
1785 int32_t x, int32_t y) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001787 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1788 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001789 if (otherHandle == windowHandle) {
1790 break;
1791 }
1792
1793 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001794 if (otherInfo->displayId == displayId && otherInfo->visible &&
1795 !otherInfo->isTrustedOverlay() && otherInfo->frameContainsPoint(x, y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 return true;
1797 }
1798 }
1799 return false;
1800}
1801
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001802bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1803 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001804 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001805 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001806 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001807 if (otherHandle == windowHandle) {
1808 break;
1809 }
1810
1811 const InputWindowInfo* otherInfo = otherHandle->getInfo();
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001812 if (otherInfo->displayId == displayId && otherInfo->visible &&
1813 !otherInfo->isTrustedOverlay() && otherInfo->overlaps(windowInfo)) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001814 return true;
1815 }
1816 }
1817 return false;
1818}
1819
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001820std::string InputDispatcher::checkWindowReadyForMoreInputLocked(
1821 nsecs_t currentTime, const sp<InputWindowHandle>& windowHandle,
1822 const EventEntry* eventEntry, const char* targetType) {
Jeff Brownffb49772014-10-10 19:01:34 -07001823 // If the window is paused then keep waiting.
1824 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001825 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001826 }
1827
1828 // If the window's connection is not registered then keep waiting.
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07001829 sp<Connection> connection =
1830 getConnectionLocked(getInputChannelLocked(windowHandle->getToken()));
1831 if (connection == nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001832 return StringPrintf("Waiting because the %s window's input channel is not "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001833 "registered with the input dispatcher. The window may be in the "
1834 "process of being removed.",
1835 targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001836 }
1837
1838 // If the connection is dead then keep waiting.
Jeff Brownffb49772014-10-10 19:01:34 -07001839 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001840 return StringPrintf("Waiting because the %s window's input connection is %s."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001841 "The window may be in the process of being removed.",
1842 targetType, connection->getStatusLabel());
Jeff Brownffb49772014-10-10 19:01:34 -07001843 }
1844
1845 // If the connection is backed up then keep waiting.
1846 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001847 return StringPrintf("Waiting because the %s window's input channel is full. "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001848 "Outbound queue length: %zu. Wait queue length: %zu.",
1849 targetType, connection->outboundQueue.size(),
1850 connection->waitQueue.size());
Jeff Brownffb49772014-10-10 19:01:34 -07001851 }
1852
1853 // Ensure that the dispatch queues aren't too far backed up for this event.
1854 if (eventEntry->type == EventEntry::TYPE_KEY) {
1855 // If the event is a key event, then we must wait for all previous events to
1856 // complete before delivering it because previous events may have the
1857 // side-effect of transferring focus to a different window and we want to
1858 // ensure that the following keys are sent to the new window.
1859 //
1860 // Suppose the user touches a button in a window then immediately presses "A".
1861 // If the button causes a pop-up window to appear then we want to ensure that
1862 // the "A" key is delivered to the new pop-up window. This is because users
1863 // often anticipate pending UI changes when typing on a keyboard.
1864 // To obtain this behavior, we must serialize key events with respect to all
1865 // prior input events.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001866 if (!connection->outboundQueue.empty() || !connection->waitQueue.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001867 return StringPrintf("Waiting to send key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001868 "finished processing all of the input events that were previously "
1869 "delivered to it. Outbound queue length: %zu. Wait queue length: "
1870 "%zu.",
1871 targetType, connection->outboundQueue.size(),
1872 connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 }
Jeff Brownffb49772014-10-10 19:01:34 -07001874 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 // Touch events can always be sent to a window immediately because the user intended
1876 // to touch whatever was visible at the time. Even if focus changes or a new
1877 // window appears moments later, the touch event was meant to be delivered to
1878 // whatever window happened to be on screen at the time.
1879 //
1880 // Generic motion events, such as trackball or joystick events are a little trickier.
1881 // Like key events, generic motion events are delivered to the focused window.
1882 // Unlike key events, generic motion events don't tend to transfer focus to other
1883 // windows and it is not important for them to be serialized. So we prefer to deliver
1884 // generic motion events as soon as possible to improve efficiency and reduce lag
1885 // through batching.
1886 //
1887 // The one case where we pause input event delivery is when the wait queue is piling
1888 // up with lots of events because the application is not responding.
1889 // This condition ensures that ANRs are detected reliably.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001890 if (!connection->waitQueue.empty() &&
1891 currentTime >=
1892 connection->waitQueue.front()->deliveryTime + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001893 return StringPrintf("Waiting to send non-key event because the %s window has not "
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07001894 "finished processing certain input events that were delivered to "
1895 "it over "
1896 "%0.1fms ago. Wait queue length: %zu. Wait queue head age: "
1897 "%0.1fms.",
1898 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1899 connection->waitQueue.size(),
1900 (currentTime - connection->waitQueue.front()->deliveryTime) *
1901 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001902 }
1903 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001904 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905}
1906
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001907std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 const sp<InputApplicationHandle>& applicationHandle,
1909 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001910 if (applicationHandle != nullptr) {
1911 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001912 std::string label(applicationHandle->getName());
1913 label += " - ";
1914 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 return label;
1916 } else {
1917 return applicationHandle->getName();
1918 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001919 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920 return windowHandle->getName();
1921 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001922 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 }
1924}
1925
1926void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001927 int32_t displayId = getTargetDisplayId(eventEntry);
1928 sp<InputWindowHandle> focusedWindowHandle =
1929 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1930 if (focusedWindowHandle != nullptr) {
1931 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1933#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001934 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935#endif
1936 return;
1937 }
1938 }
1939
1940 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1941 switch (eventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001942 case EventEntry::TYPE_MOTION: {
1943 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1944 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1945 return;
1946 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001947
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001948 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1949 eventType = USER_ACTIVITY_EVENT_TOUCH;
1950 }
1951 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001953 case EventEntry::TYPE_KEY: {
1954 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1955 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1956 return;
1957 }
1958 eventType = USER_ACTIVITY_EVENT_BUTTON;
1959 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001961 }
1962
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001963 std::unique_ptr<CommandEntry> commandEntry =
1964 std::make_unique<CommandEntry>(&InputDispatcher::doPokeUserActivityLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 commandEntry->eventTime = eventEntry->eventTime;
1966 commandEntry->userActivityEventType = eventType;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07001967 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968}
1969
1970void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001971 const sp<Connection>& connection,
1972 EventEntry* eventEntry,
1973 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001974 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001975 std::string message =
1976 StringPrintf("prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
1977 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00001978 ATRACE_NAME(message.c_str());
1979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980#if DEBUG_DISPATCH_CYCLE
1981 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001982 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1983 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
1984 connection->getInputChannelName().c_str(), inputTarget->flags, inputTarget->xOffset,
1985 inputTarget->yOffset, inputTarget->globalScaleFactor, inputTarget->windowXScale,
1986 inputTarget->windowYScale, inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987#endif
1988
1989 // Skip this event if the connection status is not normal.
1990 // We don't want to enqueue additional outbound events if the connection is broken.
1991 if (connection->status != Connection::STATUS_NORMAL) {
1992#if DEBUG_DISPATCH_CYCLE
1993 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07001994 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995#endif
1996 return;
1997 }
1998
1999 // Split a motion event if needed.
2000 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
2001 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
2002
2003 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
2004 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002005 MotionEntry* splitMotionEntry =
2006 splitMotionEvent(originalMotionEntry, inputTarget->pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 if (!splitMotionEntry) {
2008 return; // split event was dropped
2009 }
2010#if DEBUG_FOCUS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002011 ALOGD("channel '%s' ~ Split motion event.", connection->getInputChannelName().c_str());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002012 logOutboundMotionDetails(" ", splitMotionEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002014 enqueueDispatchEntriesLocked(currentTime, connection, splitMotionEntry, inputTarget);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 splitMotionEntry->release();
2016 return;
2017 }
2018 }
2019
2020 // Not splitting. Enqueue dispatch entries for the event as is.
2021 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2022}
2023
2024void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002025 const sp<Connection>& connection,
2026 EventEntry* eventEntry,
2027 const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002028 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002029 std::string message =
2030 StringPrintf("enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32
2031 ")",
2032 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
Michael Wright3dd60e22019-03-27 22:06:44 +00002033 ATRACE_NAME(message.c_str());
2034 }
2035
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002036 bool wasEmpty = connection->outboundQueue.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037
2038 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002039 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002040 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002041 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002042 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002043 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002044 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002045 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002046 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002047 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002048 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002049 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002050 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051
2052 // If the outbound queue was previously empty, start the dispatch cycle going.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002053 if (wasEmpty && !connection->outboundQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 startDispatchCycleLocked(currentTime, connection);
2055 }
2056}
2057
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002058void InputDispatcher::enqueueDispatchEntryLocked(const sp<Connection>& connection,
2059 EventEntry* eventEntry,
2060 const InputTarget* inputTarget,
2061 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002062 if (ATRACE_ENABLED()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002063 std::string message = StringPrintf("enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2064 connection->getInputChannelName().c_str(),
2065 dispatchModeToString(dispatchMode).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002066 ATRACE_NAME(message.c_str());
2067 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068 int32_t inputTargetFlags = inputTarget->flags;
2069 if (!(inputTargetFlags & dispatchMode)) {
2070 return;
2071 }
2072 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2073
2074 // This is a new event.
2075 // Enqueue a new dispatch entry onto the outbound queue for this connection.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002076 DispatchEntry* dispatchEntry =
2077 new DispatchEntry(eventEntry, // increments ref
2078 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
2079 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2080 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081
2082 // Apply target flags and update the connection's input state.
2083 switch (eventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002084 case EventEntry::TYPE_KEY: {
2085 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2086 dispatchEntry->resolvedAction = keyEntry->action;
2087 dispatchEntry->resolvedFlags = keyEntry->flags;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002088
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002089 if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction,
2090 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002092 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
2093 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002095 delete dispatchEntry;
2096 return; // skip the inconsistent event
2097 }
2098 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002101 case EventEntry::TYPE_MOTION: {
2102 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2103 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2104 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2105 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2106 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2107 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2108 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2109 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2110 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2111 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2112 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2113 } else {
2114 dispatchEntry->resolvedAction = motionEntry->action;
2115 }
2116 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE &&
2117 !connection->inputState.isHovering(motionEntry->deviceId, motionEntry->source,
2118 motionEntry->displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002120 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter "
2121 "event",
2122 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002124 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002127 dispatchEntry->resolvedFlags = motionEntry->flags;
2128 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2129 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2130 }
2131 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2132 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2133 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002135 if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction,
2136 dispatchEntry->resolvedFlags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002138 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion "
2139 "event",
2140 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002142 delete dispatchEntry;
2143 return; // skip the inconsistent event
2144 }
2145
2146 dispatchPointerDownOutsideFocus(motionEntry->source, dispatchEntry->resolvedAction,
2147 inputTarget->inputChannel->getToken());
2148
2149 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002151 }
2152
2153 // Remember that we are waiting for this dispatch to complete.
2154 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002155 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 }
2157
2158 // Enqueue the dispatch entry.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002159 connection->outboundQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002160 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002161}
2162
chaviwfd6d3512019-03-25 13:23:49 -07002163void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002164 const sp<IBinder>& newToken) {
chaviw8c9cf542019-03-25 13:02:48 -07002165 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002166 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2167 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002168 return;
2169 }
2170
2171 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2172 if (inputWindowHandle == nullptr) {
2173 return;
2174 }
2175
chaviw8c9cf542019-03-25 13:02:48 -07002176 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002177 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002178
2179 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2180
2181 if (!hasFocusChanged) {
2182 return;
2183 }
2184
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002185 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
2186 &InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
chaviwfd6d3512019-03-25 13:23:49 -07002187 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07002188 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189}
2190
2191void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002192 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002193 if (ATRACE_ENABLED()) {
2194 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002195 connection->getInputChannelName().c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +00002196 ATRACE_NAME(message.c_str());
2197 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198#if DEBUG_DISPATCH_CYCLE
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002199 ALOGD("channel '%s' ~ startDispatchCycle", connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200#endif
2201
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002202 while (connection->status == Connection::STATUS_NORMAL && !connection->outboundQueue.empty()) {
2203 DispatchEntry* dispatchEntry = connection->outboundQueue.front();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204 dispatchEntry->deliveryTime = currentTime;
2205
2206 // Publish the event.
2207 status_t status;
2208 EventEntry* eventEntry = dispatchEntry->eventEntry;
2209 switch (eventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002210 case EventEntry::TYPE_KEY: {
2211 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002213 // Publish the key event.
2214 status = connection->inputPublisher
2215 .publishKeyEvent(dispatchEntry->seq, keyEntry->deviceId,
2216 keyEntry->source, keyEntry->displayId,
2217 dispatchEntry->resolvedAction,
2218 dispatchEntry->resolvedFlags, keyEntry->keyCode,
2219 keyEntry->scanCode, keyEntry->metaState,
2220 keyEntry->repeatCount, keyEntry->downTime,
2221 keyEntry->eventTime);
2222 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 }
2224
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002225 case EventEntry::TYPE_MOTION: {
2226 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002228 PointerCoords scaledCoords[MAX_POINTERS];
2229 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2230
2231 // Set the X and Y offset depending on the input source.
2232 float xOffset, yOffset;
2233 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) &&
2234 !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2235 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2236 float wxs = dispatchEntry->windowXScale;
2237 float wys = dispatchEntry->windowYScale;
2238 xOffset = dispatchEntry->xOffset * wxs;
2239 yOffset = dispatchEntry->yOffset * wys;
2240 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
2241 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2242 scaledCoords[i] = motionEntry->pointerCoords[i];
2243 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
2244 }
2245 usingCoords = scaledCoords;
2246 }
2247 } else {
2248 xOffset = 0.0f;
2249 yOffset = 0.0f;
2250
2251 // We don't want the dispatch target to know.
2252 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
2253 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
2254 scaledCoords[i].clear();
2255 }
2256 usingCoords = scaledCoords;
2257 }
2258 }
2259
2260 // Publish the motion event.
2261 status = connection->inputPublisher
2262 .publishMotionEvent(dispatchEntry->seq, motionEntry->deviceId,
2263 motionEntry->source, motionEntry->displayId,
2264 dispatchEntry->resolvedAction,
2265 motionEntry->actionButton,
2266 dispatchEntry->resolvedFlags,
2267 motionEntry->edgeFlags, motionEntry->metaState,
2268 motionEntry->buttonState,
2269 motionEntry->classification, xOffset, yOffset,
2270 motionEntry->xPrecision,
2271 motionEntry->yPrecision,
2272 motionEntry->xCursorPosition,
2273 motionEntry->yCursorPosition,
2274 motionEntry->downTime, motionEntry->eventTime,
2275 motionEntry->pointerCount,
2276 motionEntry->pointerProperties, usingCoords);
2277 break;
2278 }
2279
2280 default:
2281 ALOG_ASSERT(false);
2282 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 }
2284
2285 // Check the result.
2286 if (status) {
2287 if (status == WOULD_BLOCK) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002288 if (connection->waitQueue.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002290 "This is unexpected because the wait queue is empty, so the pipe "
2291 "should be empty and we shouldn't have any problems writing an "
2292 "event to it, status=%d",
2293 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2295 } else {
2296 // Pipe is full and we are waiting for the app to finish process some events
2297 // before sending more events to it.
2298#if DEBUG_DISPATCH_CYCLE
2299 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002300 "waiting for the application to catch up",
2301 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302#endif
2303 connection->inputPublisherBlocked = true;
2304 }
2305 } else {
2306 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002307 "status=%d",
2308 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2310 }
2311 return;
2312 }
2313
2314 // Re-enqueue the event on the wait queue.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002315 connection->outboundQueue.erase(std::remove(connection->outboundQueue.begin(),
2316 connection->outboundQueue.end(),
2317 dispatchEntry));
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002318 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002319 connection->waitQueue.push_back(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002320 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 }
2322}
2323
2324void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002325 const sp<Connection>& connection, uint32_t seq,
2326 bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327#if DEBUG_DISPATCH_CYCLE
2328 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002329 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330#endif
2331
2332 connection->inputPublisherBlocked = false;
2333
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002334 if (connection->status == Connection::STATUS_BROKEN ||
2335 connection->status == Connection::STATUS_ZOMBIE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 return;
2337 }
2338
2339 // Notify other system components and prepare to start the next dispatch cycle.
2340 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2341}
2342
2343void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002344 const sp<Connection>& connection,
2345 bool notify) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346#if DEBUG_DISPATCH_CYCLE
2347 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002348 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002349#endif
2350
2351 // Clear the dispatch queues.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002352 drainDispatchQueue(connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002353 traceOutboundQueueLength(connection);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002354 drainDispatchQueue(connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002355 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356
2357 // The connection appears to be unrecoverably broken.
2358 // Ignore already broken or zombie connections.
2359 if (connection->status == Connection::STATUS_NORMAL) {
2360 connection->status = Connection::STATUS_BROKEN;
2361
2362 if (notify) {
2363 // Notify other system components.
2364 onDispatchCycleBrokenLocked(currentTime, connection);
2365 }
2366 }
2367}
2368
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07002369void InputDispatcher::drainDispatchQueue(std::deque<DispatchEntry*>& queue) {
2370 while (!queue.empty()) {
2371 DispatchEntry* dispatchEntry = queue.front();
2372 queue.pop_front();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002373 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 }
2375}
2376
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002377void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002379 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 }
2381 delete dispatchEntry;
2382}
2383
2384int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2385 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2386
2387 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002388 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002390 if (d->mConnectionsByFd.find(fd) == d->mConnectionsByFd.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391 ALOGE("Received spurious receive callback for unknown input channel. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002392 "fd=%d, events=0x%x",
2393 fd, events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 return 0; // remove the callback
2395 }
2396
2397 bool notify;
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002398 sp<Connection> connection = d->mConnectionsByFd[fd];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2400 if (!(events & ALOOPER_EVENT_INPUT)) {
2401 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002402 "events=0x%x",
2403 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 return 1;
2405 }
2406
2407 nsecs_t currentTime = now();
2408 bool gotOne = false;
2409 status_t status;
2410 for (;;) {
2411 uint32_t seq;
2412 bool handled;
2413 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2414 if (status) {
2415 break;
2416 }
2417 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2418 gotOne = true;
2419 }
2420 if (gotOne) {
2421 d->runCommandsLockedInterruptible();
2422 if (status == WOULD_BLOCK) {
2423 return 1;
2424 }
2425 }
2426
2427 notify = status != DEAD_OBJECT || !connection->monitor;
2428 if (notify) {
2429 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002430 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431 }
2432 } else {
2433 // Monitor channels are never explicitly unregistered.
2434 // We do it automatically when the remote endpoint is closed so don't warn
2435 // about them.
2436 notify = !connection->monitor;
2437 if (notify) {
2438 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002439 "events=0x%x",
2440 connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 }
2442 }
2443
2444 // Unregister the channel.
2445 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2446 return 0; // remove the callback
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002447 } // release lock
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448}
2449
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002450void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002452 for (const auto& pair : mConnectionsByFd) {
2453 synthesizeCancelationEventsForConnectionLocked(pair.second, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 }
2455}
2456
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002457void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002458 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002459 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2460 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2461}
2462
2463void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2464 const CancelationOptions& options,
2465 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2466 for (const auto& it : monitorsByDisplay) {
2467 const std::vector<Monitor>& monitors = it.second;
2468 for (const Monitor& monitor : monitors) {
2469 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002470 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002471 }
2472}
2473
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2475 const sp<InputChannel>& channel, const CancelationOptions& options) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002476 sp<Connection> connection = getConnectionLocked(channel);
2477 if (connection == nullptr) {
2478 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 }
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07002480
2481 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482}
2483
2484void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2485 const sp<Connection>& connection, const CancelationOptions& options) {
2486 if (connection->status == Connection::STATUS_BROKEN) {
2487 return;
2488 }
2489
2490 nsecs_t currentTime = now();
2491
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002492 std::vector<EventEntry*> cancelationEvents;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002493 connection->inputState.synthesizeCancelationEvents(currentTime, cancelationEvents, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002495 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002497 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002498 "with reality: %s, mode=%d.",
2499 connection->getInputChannelName().c_str(), cancelationEvents.size(), options.reason,
2500 options.mode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501#endif
2502 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002503 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 switch (cancelationEventEntry->type) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002505 case EventEntry::TYPE_KEY:
2506 logOutboundKeyDetails("cancel - ",
2507 static_cast<KeyEntry*>(cancelationEventEntry));
2508 break;
2509 case EventEntry::TYPE_MOTION:
2510 logOutboundMotionDetails("cancel - ",
2511 static_cast<MotionEntry*>(cancelationEventEntry));
2512 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513 }
2514
2515 InputTarget target;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002516 sp<InputWindowHandle> windowHandle =
2517 getWindowHandleLocked(connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002518 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002519 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2520 target.xOffset = -windowInfo->frameLeft;
2521 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002522 target.globalScaleFactor = windowInfo->globalScaleFactor;
2523 target.windowXScale = windowInfo->windowXScale;
2524 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 } else {
2526 target.xOffset = 0;
2527 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002528 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 }
2530 target.inputChannel = connection->inputChannel;
2531 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2532
chaviw8c9cf542019-03-25 13:02:48 -07002533 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002534 &target, InputTarget::FLAG_DISPATCH_AS_IS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535
2536 cancelationEventEntry->release();
2537 }
2538
2539 startDispatchCycleLocked(currentTime, connection);
2540 }
2541}
2542
Garfield Tane84e6f92019-08-29 17:28:41 -07002543MotionEntry* InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry,
2544 BitSet32 pointerIds) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545 ALOG_ASSERT(pointerIds.value != 0);
2546
2547 uint32_t splitPointerIndexMap[MAX_POINTERS];
2548 PointerProperties splitPointerProperties[MAX_POINTERS];
2549 PointerCoords splitPointerCoords[MAX_POINTERS];
2550
2551 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2552 uint32_t splitPointerCount = 0;
2553
2554 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002555 originalPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 const PointerProperties& pointerProperties =
2557 originalMotionEntry->pointerProperties[originalPointerIndex];
2558 uint32_t pointerId = uint32_t(pointerProperties.id);
2559 if (pointerIds.hasBit(pointerId)) {
2560 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2561 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2562 splitPointerCoords[splitPointerCount].copyFrom(
2563 originalMotionEntry->pointerCoords[originalPointerIndex]);
2564 splitPointerCount += 1;
2565 }
2566 }
2567
2568 if (splitPointerCount != pointerIds.count()) {
2569 // This is bad. We are missing some of the pointers that we expected to deliver.
2570 // Most likely this indicates that we received an ACTION_MOVE events that has
2571 // different pointer ids than we expected based on the previous ACTION_DOWN
2572 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2573 // in this way.
2574 ALOGW("Dropping split motion event because the pointer count is %d but "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002575 "we expected there to be %d pointers. This probably means we received "
2576 "a broken sequence of pointer ids from the input device.",
2577 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002578 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579 }
2580
2581 int32_t action = originalMotionEntry->action;
2582 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002583 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN ||
2584 maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2586 const PointerProperties& pointerProperties =
2587 originalMotionEntry->pointerProperties[originalPointerIndex];
2588 uint32_t pointerId = uint32_t(pointerProperties.id);
2589 if (pointerIds.hasBit(pointerId)) {
2590 if (pointerIds.count() == 1) {
2591 // The first/last pointer went down/up.
2592 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002593 ? AMOTION_EVENT_ACTION_DOWN
2594 : AMOTION_EVENT_ACTION_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595 } else {
2596 // A secondary pointer went down/up.
2597 uint32_t splitPointerIndex = 0;
2598 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2599 splitPointerIndex += 1;
2600 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002601 action = maskedAction |
2602 (splitPointerIndex << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 }
2604 } else {
2605 // An unrelated pointer changed.
2606 action = AMOTION_EVENT_ACTION_MOVE;
2607 }
2608 }
2609
Garfield Tan00f511d2019-06-12 16:55:40 -07002610 MotionEntry* splitMotionEntry =
2611 new MotionEntry(originalMotionEntry->sequenceNum, originalMotionEntry->eventTime,
2612 originalMotionEntry->deviceId, originalMotionEntry->source,
2613 originalMotionEntry->displayId, originalMotionEntry->policyFlags,
2614 action, originalMotionEntry->actionButton, originalMotionEntry->flags,
2615 originalMotionEntry->metaState, originalMotionEntry->buttonState,
2616 originalMotionEntry->classification, originalMotionEntry->edgeFlags,
2617 originalMotionEntry->xPrecision, originalMotionEntry->yPrecision,
2618 originalMotionEntry->xCursorPosition,
2619 originalMotionEntry->yCursorPosition, originalMotionEntry->downTime,
2620 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621
2622 if (originalMotionEntry->injectionState) {
2623 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2624 splitMotionEntry->injectionState->refCount += 1;
2625 }
2626
2627 return splitMotionEntry;
2628}
2629
2630void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2631#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002632 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002633#endif
2634
2635 bool needWake;
2636 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002637 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638
Prabir Pradhan42611e02018-11-27 14:04:02 -08002639 ConfigurationChangedEntry* newEntry =
2640 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641 needWake = enqueueInboundEventLocked(newEntry);
2642 } // release lock
2643
2644 if (needWake) {
2645 mLooper->wake();
2646 }
2647}
2648
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002649/**
2650 * If one of the meta shortcuts is detected, process them here:
2651 * Meta + Backspace -> generate BACK
2652 * Meta + Enter -> generate HOME
2653 * This will potentially overwrite keyCode and metaState.
2654 */
2655void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002656 int32_t& keyCode, int32_t& metaState) {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002657 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2658 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2659 if (keyCode == AKEYCODE_DEL) {
2660 newKeyCode = AKEYCODE_BACK;
2661 } else if (keyCode == AKEYCODE_ENTER) {
2662 newKeyCode = AKEYCODE_HOME;
2663 }
2664 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002665 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002666 struct KeyReplacement replacement = {keyCode, deviceId};
2667 mReplacedKeys.add(replacement, newKeyCode);
2668 keyCode = newKeyCode;
2669 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2670 }
2671 } else if (action == AKEY_EVENT_ACTION_UP) {
2672 // In order to maintain a consistent stream of up and down events, check to see if the key
2673 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2674 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002675 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002676 struct KeyReplacement replacement = {keyCode, deviceId};
2677 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2678 if (index >= 0) {
2679 keyCode = mReplacedKeys.valueAt(index);
2680 mReplacedKeys.removeItemsAt(index);
2681 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2682 }
2683 }
2684}
2685
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2687#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002688 ALOGD("notifyKey - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2689 "policyFlags=0x%x, action=0x%x, "
2690 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
2691 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2692 args->action, args->flags, args->keyCode, args->scanCode, args->metaState,
2693 args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694#endif
2695 if (!validateKeyEvent(args->action)) {
2696 return;
2697 }
2698
2699 uint32_t policyFlags = args->policyFlags;
2700 int32_t flags = args->flags;
2701 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002702 // InputDispatcher tracks and generates key repeats on behalf of
2703 // whatever notifies it, so repeatCount should always be set to 0
2704 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2706 policyFlags |= POLICY_FLAG_VIRTUAL;
2707 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2708 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 if (policyFlags & POLICY_FLAG_FUNCTION) {
2710 metaState |= AMETA_FUNCTION_ON;
2711 }
2712
2713 policyFlags |= POLICY_FLAG_TRUSTED;
2714
Michael Wright78f24442014-08-06 15:55:28 -07002715 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002716 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002717
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718 KeyEvent event;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002719 event.initialize(args->deviceId, args->source, args->displayId, args->action, flags, keyCode,
2720 args->scanCode, metaState, repeatCount, args->downTime, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721
Michael Wright2b3c3302018-03-02 17:19:13 +00002722 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002724 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2725 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002726 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002727 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729 bool needWake;
2730 { // acquire lock
2731 mLock.lock();
2732
2733 if (shouldSendKeyToInputFilterLocked(args)) {
2734 mLock.unlock();
2735
2736 policyFlags |= POLICY_FLAG_FILTERED;
2737 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2738 return; // event was consumed by the filter
2739 }
2740
2741 mLock.lock();
2742 }
2743
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002744 KeyEntry* newEntry =
2745 new KeyEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2746 args->displayId, policyFlags, args->action, flags, keyCode,
2747 args->scanCode, metaState, repeatCount, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748
2749 needWake = enqueueInboundEventLocked(newEntry);
2750 mLock.unlock();
2751 } // release lock
2752
2753 if (needWake) {
2754 mLooper->wake();
2755 }
2756}
2757
2758bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2759 return mInputFilterEnabled;
2760}
2761
2762void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2763#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002764 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
Garfield Tan00f511d2019-06-12 16:55:40 -07002765 ", policyFlags=0x%x, "
2766 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, "
2767 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, xCursorPosition=%f, "
Garfield Tanab0ab9c2019-07-10 18:58:28 -07002768 "yCursorPosition=%f, downTime=%" PRId64,
Garfield Tan00f511d2019-06-12 16:55:40 -07002769 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
2770 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
2771 args->edgeFlags, args->xPrecision, args->yPrecision, arg->xCursorPosition,
2772 args->yCursorPosition, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773 for (uint32_t i = 0; i < args->pointerCount; i++) {
2774 ALOGD(" Pointer %d: id=%d, toolType=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002775 "x=%f, y=%f, pressure=%f, size=%f, "
2776 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2777 "orientation=%f",
2778 i, args->pointerProperties[i].id, args->pointerProperties[i].toolType,
2779 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2780 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2781 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2782 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2783 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2784 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2785 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2786 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2787 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 }
2789#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002790 if (!validateMotionEvent(args->action, args->actionButton, args->pointerCount,
2791 args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 return;
2793 }
2794
2795 uint32_t policyFlags = args->policyFlags;
2796 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002797
2798 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002799 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002800 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2801 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002802 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00002803 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002804
2805 bool needWake;
2806 { // acquire lock
2807 mLock.lock();
2808
2809 if (shouldSendMotionToInputFilterLocked(args)) {
2810 mLock.unlock();
2811
2812 MotionEvent event;
Garfield Tan00f511d2019-06-12 16:55:40 -07002813 event.initialize(args->deviceId, args->source, args->displayId, args->action,
2814 args->actionButton, args->flags, args->edgeFlags, args->metaState,
2815 args->buttonState, args->classification, 0, 0, args->xPrecision,
2816 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2817 args->downTime, args->eventTime, args->pointerCount,
2818 args->pointerProperties, args->pointerCoords);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819
2820 policyFlags |= POLICY_FLAG_FILTERED;
2821 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2822 return; // event was consumed by the filter
2823 }
2824
2825 mLock.lock();
2826 }
2827
2828 // Just enqueue a new motion event.
Garfield Tan00f511d2019-06-12 16:55:40 -07002829 MotionEntry* newEntry =
2830 new MotionEntry(args->sequenceNum, args->eventTime, args->deviceId, args->source,
2831 args->displayId, policyFlags, args->action, args->actionButton,
2832 args->flags, args->metaState, args->buttonState,
2833 args->classification, args->edgeFlags, args->xPrecision,
2834 args->yPrecision, args->xCursorPosition, args->yCursorPosition,
2835 args->downTime, args->pointerCount, args->pointerProperties,
2836 args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837
2838 needWake = enqueueInboundEventLocked(newEntry);
2839 mLock.unlock();
2840 } // release lock
2841
2842 if (needWake) {
2843 mLooper->wake();
2844 }
2845}
2846
2847bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002848 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849}
2850
2851void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2852#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002853 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002854 "switchMask=0x%08x",
2855 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856#endif
2857
2858 uint32_t policyFlags = args->policyFlags;
2859 policyFlags |= POLICY_FLAG_TRUSTED;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002860 mPolicy->notifySwitch(args->eventTime, args->switchValues, args->switchMask, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861}
2862
2863void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2864#if DEBUG_INBOUND_EVENT_DETAILS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002865 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d", args->eventTime,
2866 args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867#endif
2868
2869 bool needWake;
2870 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002871 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002872
Prabir Pradhan42611e02018-11-27 14:04:02 -08002873 DeviceResetEntry* newEntry =
2874 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 needWake = enqueueInboundEventLocked(newEntry);
2876 } // release lock
2877
2878 if (needWake) {
2879 mLooper->wake();
2880 }
2881}
2882
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002883int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t injectorPid,
2884 int32_t injectorUid, int32_t syncMode,
2885 int32_t timeoutMillis, uint32_t policyFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886#if DEBUG_INBOUND_EVENT_DETAILS
2887 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002888 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2889 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890#endif
2891
2892 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2893
2894 policyFlags |= POLICY_FLAG_INJECTED;
2895 if (hasInjectionPermission(injectorPid, injectorUid)) {
2896 policyFlags |= POLICY_FLAG_TRUSTED;
2897 }
2898
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07002899 std::queue<EventEntry*> injectedEntries;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 switch (event->getType()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002901 case AINPUT_EVENT_TYPE_KEY: {
2902 KeyEvent keyEvent;
2903 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2904 int32_t action = keyEvent.getAction();
2905 if (!validateKeyEvent(action)) {
2906 return INPUT_EVENT_INJECTION_FAILED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002907 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002909 int32_t flags = keyEvent.getFlags();
2910 int32_t keyCode = keyEvent.getKeyCode();
2911 int32_t metaState = keyEvent.getMetaState();
2912 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2913 /*byref*/ keyCode, /*byref*/ metaState);
2914 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(),
2915 keyEvent.getDisplayId(), action, flags, keyCode,
2916 keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
2917 keyEvent.getDownTime(), keyEvent.getEventTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002919 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2920 policyFlags |= POLICY_FLAG_VIRTUAL;
Michael Wright2b3c3302018-03-02 17:19:13 +00002921 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002922
2923 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2924 android::base::Timer t;
2925 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
2926 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2927 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2928 std::to_string(t.duration().count()).c_str());
2929 }
2930 }
2931
2932 mLock.lock();
2933 KeyEntry* injectedEntry =
2934 new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
2935 keyEvent.getDeviceId(), keyEvent.getSource(),
2936 keyEvent.getDisplayId(), policyFlags, action, flags,
2937 keyEvent.getKeyCode(), keyEvent.getScanCode(),
2938 keyEvent.getMetaState(), keyEvent.getRepeatCount(),
2939 keyEvent.getDownTime());
2940 injectedEntries.push(injectedEntry);
2941 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942 }
2943
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002944 case AINPUT_EVENT_TYPE_MOTION: {
2945 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2946 int32_t action = motionEvent->getAction();
2947 size_t pointerCount = motionEvent->getPointerCount();
2948 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2949 int32_t actionButton = motionEvent->getActionButton();
2950 int32_t displayId = motionEvent->getDisplayId();
2951 if (!validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
2952 return INPUT_EVENT_INJECTION_FAILED;
2953 }
2954
2955 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2956 nsecs_t eventTime = motionEvent->getEventTime();
2957 android::base::Timer t;
2958 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
2959 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2960 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2961 std::to_string(t.duration().count()).c_str());
2962 }
2963 }
2964
2965 mLock.lock();
2966 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2967 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2968 MotionEntry* injectedEntry =
Garfield Tan00f511d2019-06-12 16:55:40 -07002969 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2970 motionEvent->getDeviceId(), motionEvent->getSource(),
2971 motionEvent->getDisplayId(), policyFlags, action, actionButton,
2972 motionEvent->getFlags(), motionEvent->getMetaState(),
2973 motionEvent->getButtonState(), motionEvent->getClassification(),
2974 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2975 motionEvent->getYPrecision(),
2976 motionEvent->getRawXCursorPosition(),
2977 motionEvent->getRawYCursorPosition(),
2978 motionEvent->getDownTime(), uint32_t(pointerCount),
2979 pointerProperties, samplePointerCoords,
2980 motionEvent->getXOffset(), motionEvent->getYOffset());
Garfield Tan0fc2fa72019-08-29 17:22:15 -07002981 injectedEntries.push(injectedEntry);
2982 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2983 sampleEventTimes += 1;
2984 samplePointerCoords += pointerCount;
2985 MotionEntry* nextInjectedEntry =
2986 new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
2987 motionEvent->getDeviceId(), motionEvent->getSource(),
2988 motionEvent->getDisplayId(), policyFlags, action,
2989 actionButton, motionEvent->getFlags(),
2990 motionEvent->getMetaState(), motionEvent->getButtonState(),
2991 motionEvent->getClassification(),
2992 motionEvent->getEdgeFlags(), motionEvent->getXPrecision(),
2993 motionEvent->getYPrecision(),
2994 motionEvent->getRawXCursorPosition(),
2995 motionEvent->getRawYCursorPosition(),
2996 motionEvent->getDownTime(), uint32_t(pointerCount),
2997 pointerProperties, samplePointerCoords,
2998 motionEvent->getXOffset(), motionEvent->getYOffset());
2999 injectedEntries.push(nextInjectedEntry);
3000 }
3001 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003004 default:
3005 ALOGW("Cannot inject event of type %d", event->getType());
3006 return INPUT_EVENT_INJECTION_FAILED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003007 }
3008
3009 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
3010 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3011 injectionState->injectionIsAsync = true;
3012 }
3013
3014 injectionState->refCount += 1;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003015 injectedEntries.back()->injectionState = injectionState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016
3017 bool needWake = false;
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003018 while (!injectedEntries.empty()) {
3019 needWake |= enqueueInboundEventLocked(injectedEntries.front());
3020 injectedEntries.pop();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021 }
3022
3023 mLock.unlock();
3024
3025 if (needWake) {
3026 mLooper->wake();
3027 }
3028
3029 int32_t injectionResult;
3030 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003031 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032
3033 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3034 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3035 } else {
3036 for (;;) {
3037 injectionResult = injectionState->injectionResult;
3038 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3039 break;
3040 }
3041
3042 nsecs_t remainingTimeout = endTime - now();
3043 if (remainingTimeout <= 0) {
3044#if DEBUG_INJECTION
3045 ALOGD("injectInputEvent - Timed out waiting for injection result "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003046 "to become available.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003047#endif
3048 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3049 break;
3050 }
3051
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003052 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053 }
3054
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003055 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED &&
3056 syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057 while (injectionState->pendingForegroundDispatches != 0) {
3058#if DEBUG_INJECTION
3059 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003060 injectionState->pendingForegroundDispatches);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003061#endif
3062 nsecs_t remainingTimeout = endTime - now();
3063 if (remainingTimeout <= 0) {
3064#if DEBUG_INJECTION
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003065 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3066 "dispatches to finish.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067#endif
3068 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3069 break;
3070 }
3071
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003072 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073 }
3074 }
3075 }
3076
3077 injectionState->release();
3078 } // release lock
3079
3080#if DEBUG_INJECTION
3081 ALOGD("injectInputEvent - Finished with result %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003082 "injectorPid=%d, injectorUid=%d",
3083 injectionResult, injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084#endif
3085
3086 return injectionResult;
3087}
3088
3089bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003090 return injectorUid == 0 ||
3091 mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092}
3093
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003094void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095 InjectionState* injectionState = entry->injectionState;
3096 if (injectionState) {
3097#if DEBUG_INJECTION
3098 ALOGD("Setting input event injection result to %d. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003099 "injectorPid=%d, injectorUid=%d",
3100 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101#endif
3102
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003103 if (injectionState->injectionIsAsync && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003104 // Log the outcome since the injector did not wait for the injection result.
3105 switch (injectionResult) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003106 case INPUT_EVENT_INJECTION_SUCCEEDED:
3107 ALOGV("Asynchronous input event injection succeeded.");
3108 break;
3109 case INPUT_EVENT_INJECTION_FAILED:
3110 ALOGW("Asynchronous input event injection failed.");
3111 break;
3112 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3113 ALOGW("Asynchronous input event injection permission denied.");
3114 break;
3115 case INPUT_EVENT_INJECTION_TIMED_OUT:
3116 ALOGW("Asynchronous input event injection timed out.");
3117 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118 }
3119 }
3120
3121 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003122 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003123 }
3124}
3125
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003126void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127 InjectionState* injectionState = entry->injectionState;
3128 if (injectionState) {
3129 injectionState->pendingForegroundDispatches += 1;
3130 }
3131}
3132
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003133void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003134 InjectionState* injectionState = entry->injectionState;
3135 if (injectionState) {
3136 injectionState->pendingForegroundDispatches -= 1;
3137
3138 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003139 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140 }
3141 }
3142}
3143
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003144std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3145 int32_t displayId) const {
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003146 return getValueByKey(mWindowHandlesByDisplay, displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003147}
3148
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003150 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003151 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003152 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3153 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003154 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003155 return windowHandle;
3156 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
3158 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003159 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160}
3161
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003162bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003163 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003164 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3165 for (const sp<InputWindowHandle>& handle : windowHandles) {
3166 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003167 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003168 ALOGE("Found window %s in display %" PRId32
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003169 ", but it should belong to display %" PRId32,
3170 windowHandle->getName().c_str(), it.first,
3171 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003172 }
3173 return true;
3174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 }
3176 }
3177 return false;
3178}
3179
Robert Carr5c8a0262018-10-03 16:30:44 -07003180sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3181 size_t count = mInputChannelsByToken.count(token);
3182 if (count == 0) {
3183 return nullptr;
3184 }
3185 return mInputChannelsByToken.at(token);
3186}
3187
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003188void InputDispatcher::updateWindowHandlesForDisplayLocked(
3189 const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
3190 if (inputWindowHandles.empty()) {
3191 // Remove all handles on a display if there are no windows left.
3192 mWindowHandlesByDisplay.erase(displayId);
3193 return;
3194 }
3195
3196 // Since we compare the pointer of input window handles across window updates, we need
3197 // to make sure the handle object for the same window stays unchanged across updates.
3198 const std::vector<sp<InputWindowHandle>>& oldHandles = getWindowHandlesLocked(displayId);
3199 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3200 for (const sp<InputWindowHandle>& handle : oldHandles) {
3201 oldHandlesByTokens[handle->getToken()] = handle;
3202 }
3203
3204 std::vector<sp<InputWindowHandle>> newHandles;
3205 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
3206 if (!handle->updateInfo()) {
3207 // handle no longer valid
3208 continue;
3209 }
3210
3211 const InputWindowInfo* info = handle->getInfo();
3212 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3213 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3214 const bool noInputChannel =
3215 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3216 const bool canReceiveInput =
3217 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3218 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3219 if (canReceiveInput && !noInputChannel) {
3220 ALOGE("Window handle %s has no registered input channel",
3221 handle->getName().c_str());
3222 }
3223 continue;
3224 }
3225
3226 if (info->displayId != displayId) {
3227 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3228 handle->getName().c_str(), displayId, info->displayId);
3229 continue;
3230 }
3231
3232 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3233 const sp<InputWindowHandle> oldHandle = oldHandlesByTokens.at(handle->getToken());
3234 oldHandle->updateFrom(handle);
3235 newHandles.push_back(oldHandle);
3236 } else {
3237 newHandles.push_back(handle);
3238 }
3239 }
3240
3241 // Insert or replace
3242 mWindowHandlesByDisplay[displayId] = newHandles;
3243}
3244
Arthur Hungb92218b2018-08-14 12:00:21 +08003245/**
3246 * Called from InputManagerService, update window handle list by displayId that can receive input.
3247 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3248 * If set an empty list, remove all handles from the specific display.
3249 * For focused handle, check if need to change and send a cancel event to previous one.
3250 * For removed handle, check if need to send a cancel event if already in touch.
3251 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003252void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003253 int32_t displayId,
3254 const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003256 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257#endif
3258 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003259 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260
Arthur Hungb92218b2018-08-14 12:00:21 +08003261 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003262 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3263 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003265 updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
3266
Tiger Huang721e26f2018-07-24 22:26:19 +08003267 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268 bool foundHoveredWindow = false;
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003269 for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
3270 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3271 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
3272 windowHandle->getInfo()->visible) {
3273 newFocusedWindowHandle = windowHandle;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003274 }
Siarhei Vishniakoub3ad35c2019-04-05 10:50:52 -07003275 if (windowHandle == mLastHoverWindowHandle) {
3276 foundHoveredWindow = true;
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003277 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278 }
3279
3280 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003281 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282 }
3283
Tiger Huang721e26f2018-07-24 22:26:19 +08003284 sp<InputWindowHandle> oldFocusedWindowHandle =
3285 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3286
3287 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3288 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003290 ALOGD("Focus left window: %s in display %" PRId32,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003291 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292#endif
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003293 sp<InputChannel> focusedInputChannel =
3294 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003295 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003297 "focus left window");
3298 synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003300 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003302 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003304 ALOGD("Focus entered window: %s in display %" PRId32,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003305 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003307 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308 }
Robert Carrf759f162018-11-13 12:57:11 -08003309
3310 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003311 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313 }
3314
Arthur Hungb92218b2018-08-14 12:00:21 +08003315 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3316 if (stateIndex >= 0) {
3317 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003318 for (size_t i = 0; i < state.windows.size();) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003319 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003320 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003322 ALOGD("Touched window was removed: %s in display %" PRId32,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003323 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003325 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003326 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003327 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003328 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003329 "touched window was removed");
3330 synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
3331 options);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003332 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003333 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003334 } else {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003335 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 }
3338 }
3339
3340 // Release information for windows that are no longer present.
3341 // This ensures that unused input channels are released promptly.
3342 // Otherwise, they might stick around until the window handle is destroyed
3343 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003344 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003345 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003347 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003349 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 }
3351 }
3352 } // release lock
3353
3354 // Wake up poll loop since it may need to make new input dispatching choices.
3355 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003356
3357 if (setInputWindowsListener) {
3358 setInputWindowsListener->onSetInputWindowsFinished();
3359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360}
3361
3362void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003363 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003365 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366#endif
3367 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003368 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369
Tiger Huang721e26f2018-07-24 22:26:19 +08003370 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3371 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003372 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003373 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3374 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003377 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003379 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003381 oldFocusedApplicationHandle.clear();
3382 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 }
3384
3385#if DEBUG_FOCUS
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003386 // logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387#endif
3388 } // release lock
3389
3390 // Wake up poll loop since it may need to make new input dispatching choices.
3391 mLooper->wake();
3392}
3393
Tiger Huang721e26f2018-07-24 22:26:19 +08003394/**
3395 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3396 * the display not specified.
3397 *
3398 * We track any unreleased events for each window. If a window loses the ability to receive the
3399 * released event, we will send a cancel event to it. So when the focused display is changed, we
3400 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3401 * display. The display-specified events won't be affected.
3402 */
3403void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3404#if DEBUG_FOCUS
3405 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3406#endif
3407 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003408 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003409
3410 if (mFocusedDisplayId != displayId) {
3411 sp<InputWindowHandle> oldFocusedWindowHandle =
3412 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3413 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003414 sp<InputChannel> inputChannel =
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003415 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003416 if (inputChannel != nullptr) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003417 CancelationOptions
3418 options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3419 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003420 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003421 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3422 }
3423 }
3424 mFocusedDisplayId = displayId;
3425
3426 // Sanity check
3427 sp<InputWindowHandle> newFocusedWindowHandle =
3428 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003429 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003430
Tiger Huang721e26f2018-07-24 22:26:19 +08003431 if (newFocusedWindowHandle == nullptr) {
3432 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3433 if (!mFocusedWindowHandlesByDisplay.empty()) {
3434 ALOGE("But another display has a focused window:");
3435 for (auto& it : mFocusedWindowHandlesByDisplay) {
3436 const int32_t displayId = it.first;
3437 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003438 ALOGE("Display #%" PRId32 " has focused window: '%s'\n", displayId,
3439 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003440 }
3441 }
3442 }
3443 }
3444
3445#if DEBUG_FOCUS
3446 logDispatchStateLocked();
3447#endif
3448 } // release lock
3449
3450 // Wake up poll loop since it may need to make new input dispatching choices.
3451 mLooper->wake();
3452}
3453
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3455#if DEBUG_FOCUS
3456 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3457#endif
3458
3459 bool changed;
3460 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003461 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462
3463 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3464 if (mDispatchFrozen && !frozen) {
3465 resetANRTimeoutsLocked();
3466 }
3467
3468 if (mDispatchEnabled && !enabled) {
3469 resetAndDropEverythingLocked("dispatcher is being disabled");
3470 }
3471
3472 mDispatchEnabled = enabled;
3473 mDispatchFrozen = frozen;
3474 changed = true;
3475 } else {
3476 changed = false;
3477 }
3478
3479#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003480 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481#endif
3482 } // release lock
3483
3484 if (changed) {
3485 // Wake up poll loop since it may need to make new input dispatching choices.
3486 mLooper->wake();
3487 }
3488}
3489
3490void InputDispatcher::setInputFilterEnabled(bool enabled) {
3491#if DEBUG_FOCUS
3492 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3493#endif
3494
3495 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003496 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497
3498 if (mInputFilterEnabled == enabled) {
3499 return;
3500 }
3501
3502 mInputFilterEnabled = enabled;
3503 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3504 } // release lock
3505
3506 // Wake up poll loop since there might be work to do to drop everything.
3507 mLooper->wake();
3508}
3509
chaviwfbe5d9c2018-12-26 12:23:37 -08003510bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3511 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003513 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003515 return true;
3516 }
3517
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003519 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520
chaviwfbe5d9c2018-12-26 12:23:37 -08003521 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3522 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003523 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003524 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525 return false;
3526 }
chaviw4f2dd402018-12-26 15:30:27 -08003527#if DEBUG_FOCUS
3528 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003529 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
chaviw4f2dd402018-12-26 15:30:27 -08003530#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3532#if DEBUG_FOCUS
3533 ALOGD("Cannot transfer focus because windows are on different displays.");
3534#endif
3535 return false;
3536 }
3537
3538 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003539 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3540 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3541 for (size_t i = 0; i < state.windows.size(); i++) {
3542 const TouchedWindow& touchedWindow = state.windows[i];
3543 if (touchedWindow.windowHandle == fromWindowHandle) {
3544 int32_t oldTargetFlags = touchedWindow.targetFlags;
3545 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003547 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003549 int32_t newTargetFlags = oldTargetFlags &
3550 (InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_SPLIT |
3551 InputTarget::FLAG_DISPATCH_AS_IS);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003552 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553
Jeff Brownf086ddb2014-02-11 14:28:48 -08003554 found = true;
3555 goto Found;
3556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 }
3558 }
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003559 Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003561 if (!found) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562#if DEBUG_FOCUS
3563 ALOGD("Focus transfer failed because from window did not have focus.");
3564#endif
3565 return false;
3566 }
3567
chaviwfbe5d9c2018-12-26 12:23:37 -08003568 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3569 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003570 sp<Connection> fromConnection = getConnectionLocked(fromChannel);
3571 sp<Connection> toConnection = getConnectionLocked(toChannel);
3572 if (fromConnection != nullptr && toConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003574 CancelationOptions
3575 options(CancelationOptions::CANCEL_POINTER_EVENTS,
3576 "transferring touch focus from this window to another window");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3578 }
3579
3580#if DEBUG_FOCUS
3581 logDispatchStateLocked();
3582#endif
3583 } // release lock
3584
3585 // Wake up poll loop since it may need to make new input dispatching choices.
3586 mLooper->wake();
3587 return true;
3588}
3589
3590void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3591#if DEBUG_FOCUS
3592 ALOGD("Resetting and dropping all events (%s).", reason);
3593#endif
3594
3595 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3596 synthesizeCancelationEventsForAllConnectionsLocked(options);
3597
3598 resetKeyRepeatLocked();
3599 releasePendingEventLocked();
3600 drainInboundQueueLocked();
3601 resetANRTimeoutsLocked();
3602
Jeff Brownf086ddb2014-02-11 14:28:48 -08003603 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003605 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606}
3607
3608void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003609 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 dumpDispatchStateLocked(dump);
3611
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003612 std::istringstream stream(dump);
3613 std::string line;
3614
3615 while (std::getline(stream, line, '\n')) {
3616 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
3618}
3619
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003620void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003621 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3622 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3623 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003624 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625
Tiger Huang721e26f2018-07-24 22:26:19 +08003626 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3627 dump += StringPrintf(INDENT "FocusedApplications:\n");
3628 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3629 const int32_t displayId = it.first;
3630 const sp<InputApplicationHandle>& applicationHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003631 dump += StringPrintf(INDENT2 "displayId=%" PRId32
3632 ", name='%s', dispatchingTimeout=%0.3fms\n",
3633 displayId, applicationHandle->getName().c_str(),
3634 applicationHandle->getDispatchingTimeout(
3635 DEFAULT_INPUT_DISPATCHING_TIMEOUT) /
3636 1000000.0);
Tiger Huang721e26f2018-07-24 22:26:19 +08003637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003639 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003641
3642 if (!mFocusedWindowHandlesByDisplay.empty()) {
3643 dump += StringPrintf(INDENT "FocusedWindows:\n");
3644 for (auto& it : mFocusedWindowHandlesByDisplay) {
3645 const int32_t displayId = it.first;
3646 const sp<InputWindowHandle>& windowHandle = it.second;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003647 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n", displayId,
3648 windowHandle->getName().c_str());
Tiger Huang721e26f2018-07-24 22:26:19 +08003649 }
3650 } else {
3651 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653
Jeff Brownf086ddb2014-02-11 14:28:48 -08003654 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003655 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003656 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3657 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003658 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003659 state.displayId, toString(state.down), toString(state.split),
3660 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003661 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003662 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003663 for (size_t i = 0; i < state.windows.size(); i++) {
3664 const TouchedWindow& touchedWindow = state.windows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003665 dump += StringPrintf(INDENT4
3666 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3667 i, touchedWindow.windowHandle->getName().c_str(),
3668 touchedWindow.pointerIds.value, touchedWindow.targetFlags);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003669 }
3670 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003671 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003672 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003673 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003674 dump += INDENT3 "Portal windows:\n";
3675 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003676 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003677 dump += StringPrintf(INDENT4 "%zu: name='%s'\n", i,
3678 portalWindowHandle->getName().c_str());
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003679 }
3680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 }
3682 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003683 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 }
3685
Arthur Hungb92218b2018-08-14 12:00:21 +08003686 if (!mWindowHandlesByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003687 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003688 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003689 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003690 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003691 dump += INDENT2 "Windows:\n";
3692 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003693 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003694 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695
Arthur Hungb92218b2018-08-14 12:00:21 +08003696 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003697 "portalToDisplayId=%d, paused=%s, hasFocus=%s, "
3698 "hasWallpaper=%s, "
3699 "visible=%s, canReceiveKeys=%s, flags=0x%08x, "
3700 "type=0x%08x, layer=%d, "
3701 "frame=[%d,%d][%d,%d], globalScale=%f, "
3702 "windowScale=(%f,%f), "
3703 "touchableRegion=",
3704 i, windowInfo->name.c_str(), windowInfo->displayId,
3705 windowInfo->portalToDisplayId,
3706 toString(windowInfo->paused),
3707 toString(windowInfo->hasFocus),
3708 toString(windowInfo->hasWallpaper),
3709 toString(windowInfo->visible),
3710 toString(windowInfo->canReceiveKeys),
3711 windowInfo->layoutParamsFlags,
3712 windowInfo->layoutParamsType, windowInfo->layer,
3713 windowInfo->frameLeft, windowInfo->frameTop,
3714 windowInfo->frameRight, windowInfo->frameBottom,
3715 windowInfo->globalScaleFactor, windowInfo->windowXScale,
3716 windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003717 dumpRegion(dump, windowInfo->touchableRegion);
3718 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3719 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003720 windowInfo->ownerPid, windowInfo->ownerUid,
3721 windowInfo->dispatchingTimeout / 1000000.0);
Arthur Hungb92218b2018-08-14 12:00:21 +08003722 }
3723 } else {
3724 dump += INDENT2 "Windows: <none>\n";
3725 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 }
3727 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003728 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 }
3730
Michael Wright3dd60e22019-03-27 22:06:44 +00003731 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003732 for (auto& it : mGlobalMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003733 const std::vector<Monitor>& monitors = it.second;
3734 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3735 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003736 }
3737 for (auto& it : mGestureMonitorsByDisplay) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003738 const std::vector<Monitor>& monitors = it.second;
3739 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3740 dumpMonitors(dump, monitors);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003743 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 }
3745
3746 nsecs_t currentTime = now();
3747
3748 // Dump recently dispatched or dropped events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003749 if (!mRecentQueue.empty()) {
3750 dump += StringPrintf(INDENT "RecentQueue: length=%zu\n", mRecentQueue.size());
3751 for (EventEntry* entry : mRecentQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003752 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003754 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 }
3756 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003757 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 }
3759
3760 // Dump event currently being dispatched.
3761 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003762 dump += INDENT "PendingEvent:\n";
3763 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003765 dump += StringPrintf(", age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003766 (currentTime - mPendingEvent->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003768 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 }
3770
3771 // Dump inbound events from oldest to newest.
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07003772 if (!mInboundQueue.empty()) {
3773 dump += StringPrintf(INDENT "InboundQueue: length=%zu\n", mInboundQueue.size());
3774 for (EventEntry* entry : mInboundQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003775 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 entry->appendDescription(dump);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003777 dump += StringPrintf(", age=%0.1fms\n", (currentTime - entry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 }
3779 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003780 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 }
3782
Michael Wright78f24442014-08-06 15:55:28 -07003783 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003784 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003785 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3786 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3787 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003788 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n", i,
3789 replacement.keyCode, replacement.deviceId, newKeyCode);
Michael Wright78f24442014-08-06 15:55:28 -07003790 }
3791 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003792 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003793 }
3794
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003795 if (!mConnectionsByFd.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003796 dump += INDENT "Connections:\n";
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003797 for (const auto& pair : mConnectionsByFd) {
3798 const sp<Connection>& connection = pair.second;
3799 dump += StringPrintf(INDENT2 "%i: channelName='%s', windowName='%s', "
3800 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3801 pair.first, connection->getInputChannelName().c_str(),
3802 connection->getWindowName().c_str(), connection->getStatusLabel(),
3803 toString(connection->monitor),
3804 toString(connection->inputPublisherBlocked));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003806 if (!connection->outboundQueue.empty()) {
3807 dump += StringPrintf(INDENT3 "OutboundQueue: length=%zu\n",
3808 connection->outboundQueue.size());
3809 for (DispatchEntry* entry : connection->outboundQueue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 dump.append(INDENT4);
3811 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003812 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003813 entry->targetFlags, entry->resolvedAction,
3814 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 }
3816 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003817 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 }
3819
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07003820 if (!connection->waitQueue.empty()) {
3821 dump += StringPrintf(INDENT3 "WaitQueue: length=%zu\n",
3822 connection->waitQueue.size());
3823 for (DispatchEntry* entry : connection->waitQueue) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003824 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003826 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003827 "age=%0.1fms, wait=%0.1fms\n",
3828 entry->targetFlags, entry->resolvedAction,
3829 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3830 (currentTime - entry->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 }
3832 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003833 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 }
3835 }
3836 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003837 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
3839
3840 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003841 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003842 (mAppSwitchDueTime - now()) / 1000000.0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003844 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845 }
3846
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003847 dump += INDENT "Configuration:\n";
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003848 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n", mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003849 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003850 mConfig.keyRepeatTimeout * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851}
3852
Michael Wright3dd60e22019-03-27 22:06:44 +00003853void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3854 const size_t numMonitors = monitors.size();
3855 for (size_t i = 0; i < numMonitors; i++) {
3856 const Monitor& monitor = monitors[i];
3857 const sp<InputChannel>& channel = monitor.inputChannel;
3858 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3859 dump += "\n";
3860 }
3861}
3862
3863status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003864 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003866 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003867 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868#endif
3869
3870 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003871 std::scoped_lock _l(mLock);
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003872 sp<Connection> existingConnection = getConnectionLocked(inputChannel);
3873 if (existingConnection != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 ALOGW("Attempted to register already registered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003875 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 return BAD_VALUE;
3877 }
3878
Michael Wright3dd60e22019-03-27 22:06:44 +00003879 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880
3881 int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003882 mConnectionsByFd[fd] = connection;
Robert Carr5c8a0262018-10-03 16:30:44 -07003883 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3886 } // release lock
3887
3888 // Wake the looper because some connections have changed.
3889 mLooper->wake();
3890 return OK;
3891}
3892
Michael Wright3dd60e22019-03-27 22:06:44 +00003893status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003894 int32_t displayId, bool isGestureMonitor) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003895 { // acquire lock
3896 std::scoped_lock _l(mLock);
3897
3898 if (displayId < 0) {
3899 ALOGW("Attempted to register input monitor without a specified display.");
3900 return BAD_VALUE;
3901 }
3902
3903 if (inputChannel->getToken() == nullptr) {
3904 ALOGW("Attempted to register input monitor without an identifying token.");
3905 return BAD_VALUE;
3906 }
3907
3908 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3909
3910 const int fd = inputChannel->getFd();
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003911 mConnectionsByFd[fd] = connection;
Michael Wright3dd60e22019-03-27 22:06:44 +00003912 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
3913
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003914 auto& monitorsByDisplay =
3915 isGestureMonitor ? mGestureMonitorsByDisplay : mGlobalMonitorsByDisplay;
Michael Wright3dd60e22019-03-27 22:06:44 +00003916 monitorsByDisplay[displayId].emplace_back(inputChannel);
3917
3918 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Michael Wright3dd60e22019-03-27 22:06:44 +00003919 }
3920 // Wake the looper because some connections have changed.
3921 mLooper->wake();
3922 return OK;
3923}
3924
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3926#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003927 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928#endif
3929
3930 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003931 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932
3933 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3934 if (status) {
3935 return status;
3936 }
3937 } // release lock
3938
3939 // Wake the poll loop because removing the connection may have changed the current
3940 // synchronization state.
3941 mLooper->wake();
3942 return OK;
3943}
3944
3945status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003946 bool notify) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003947 sp<Connection> connection = getConnectionLocked(inputChannel);
3948 if (connection == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003950 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 return BAD_VALUE;
3952 }
3953
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07003954 const bool removed = removeByValue(mConnectionsByFd, connection);
3955 ALOG_ASSERT(removed);
Robert Carr5c8a0262018-10-03 16:30:44 -07003956 mInputChannelsByToken.erase(inputChannel->getToken());
3957
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 if (connection->monitor) {
3959 removeMonitorChannelLocked(inputChannel);
3960 }
3961
3962 mLooper->removeFd(inputChannel->getFd());
3963
3964 nsecs_t currentTime = now();
3965 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3966
3967 connection->status = Connection::STATUS_ZOMBIE;
3968 return OK;
3969}
3970
3971void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003972 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
3973 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
3974}
3975
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003976void InputDispatcher::removeMonitorChannelLocked(
3977 const sp<InputChannel>& inputChannel,
Michael Wright3dd60e22019-03-27 22:06:44 +00003978 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003979 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end();) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003980 std::vector<Monitor>& monitors = it->second;
3981 const size_t numMonitors = monitors.size();
3982 for (size_t i = 0; i < numMonitors; i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07003983 if (monitors[i].inputChannel == inputChannel) {
3984 monitors.erase(monitors.begin() + i);
3985 break;
3986 }
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003987 }
Michael Wright3dd60e22019-03-27 22:06:44 +00003988 if (monitors.empty()) {
3989 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003990 } else {
3991 ++it;
3992 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 }
3994}
3995
Michael Wright3dd60e22019-03-27 22:06:44 +00003996status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
3997 { // acquire lock
3998 std::scoped_lock _l(mLock);
3999 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
4000
4001 if (!foundDisplayId) {
4002 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
4003 return BAD_VALUE;
4004 }
4005 int32_t displayId = foundDisplayId.value();
4006
4007 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4008 if (stateIndex < 0) {
4009 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4010 return BAD_VALUE;
4011 }
4012
4013 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4014 std::optional<int32_t> foundDeviceId;
4015 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
4016 if (touchedMonitor.monitor.inputChannel->getToken() == token) {
4017 foundDeviceId = state.deviceId;
4018 }
4019 }
4020 if (!foundDeviceId || !state.down) {
4021 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004022 " Ignoring.");
Michael Wright3dd60e22019-03-27 22:06:44 +00004023 return BAD_VALUE;
4024 }
4025 int32_t deviceId = foundDeviceId.value();
4026
4027 // Send cancel events to all the input channels we're stealing from.
4028 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004029 "gesture monitor stole pointer stream");
Michael Wright3dd60e22019-03-27 22:06:44 +00004030 options.deviceId = deviceId;
4031 options.displayId = displayId;
4032 for (const TouchedWindow& window : state.windows) {
4033 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
4034 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4035 }
4036 // Then clear the current touch state so we stop dispatching to them as well.
4037 state.filterNonMonitors();
4038 }
4039 return OK;
4040}
4041
Michael Wright3dd60e22019-03-27 22:06:44 +00004042std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4043 const sp<IBinder>& token) {
4044 for (const auto& it : mGestureMonitorsByDisplay) {
4045 const std::vector<Monitor>& monitors = it.second;
4046 for (const Monitor& monitor : monitors) {
4047 if (monitor.inputChannel->getToken() == token) {
4048 return it.first;
4049 }
4050 }
4051 }
4052 return std::nullopt;
4053}
4054
Garfield Tane84e6f92019-08-29 17:28:41 -07004055sp<Connection> InputDispatcher::getConnectionLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07004056 if (inputChannel == nullptr) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004057 return nullptr;
Arthur Hung3b413f22018-10-26 18:05:34 +08004058 }
4059
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004060 for (const auto& pair : mConnectionsByFd) {
4061 sp<Connection> connection = pair.second;
Robert Carr4e670e52018-08-15 13:26:12 -07004062 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004063 return connection;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064 }
4065 }
Robert Carr4e670e52018-08-15 13:26:12 -07004066
Siarhei Vishniakou146ecfd2019-07-29 16:04:31 -07004067 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068}
4069
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004070void InputDispatcher::onDispatchCycleFinishedLocked(nsecs_t currentTime,
4071 const sp<Connection>& connection, uint32_t seq,
4072 bool handled) {
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004073 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4074 &InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 commandEntry->connection = connection;
4076 commandEntry->eventTime = currentTime;
4077 commandEntry->seq = seq;
4078 commandEntry->handled = handled;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004079 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080}
4081
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004082void InputDispatcher::onDispatchCycleBrokenLocked(nsecs_t currentTime,
4083 const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004085 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004087 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4088 &InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 commandEntry->connection = connection;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004090 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091}
4092
chaviw0c06c6e2019-01-09 13:27:07 -08004093void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004094 const sp<InputWindowHandle>& newFocus) {
chaviw0c06c6e2019-01-09 13:27:07 -08004095 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4096 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004097 std::unique_ptr<CommandEntry> commandEntry = std::make_unique<CommandEntry>(
4098 &InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004099 commandEntry->oldToken = oldToken;
4100 commandEntry->newToken = newToken;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004101 postCommandLocked(std::move(commandEntry));
Robert Carrf759f162018-11-13 12:57:11 -08004102}
4103
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004104void InputDispatcher::onANRLocked(nsecs_t currentTime,
4105 const sp<InputApplicationHandle>& applicationHandle,
4106 const sp<InputWindowHandle>& windowHandle, nsecs_t eventTime,
4107 nsecs_t waitStartTime, const char* reason) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4109 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4110 ALOGI("Application is not responding: %s. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004111 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
4112 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(), dispatchLatency,
4113 waitDuration, reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114
4115 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004116 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 struct tm tm;
4118 localtime_r(&t, &tm);
4119 char timestr[64];
4120 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4121 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004122 mLastANRState += INDENT "ANR:\n";
4123 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004124 mLastANRState +=
4125 StringPrintf(INDENT2 "Window: %s\n",
4126 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004127 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4128 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4129 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130 dumpDispatchStateLocked(mLastANRState);
4131
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004132 std::unique_ptr<CommandEntry> commandEntry =
4133 std::make_unique<CommandEntry>(&InputDispatcher::doNotifyANRLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134 commandEntry->inputApplicationHandle = applicationHandle;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004135 commandEntry->inputChannel =
4136 windowHandle != nullptr ? getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 commandEntry->reason = reason;
Siarhei Vishniakoue7c94b92019-07-29 09:17:54 -07004138 postCommandLocked(std::move(commandEntry));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139}
4140
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004141void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 mLock.unlock();
4143
4144 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4145
4146 mLock.lock();
4147}
4148
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004149void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150 sp<Connection> connection = commandEntry->connection;
4151
4152 if (connection->status != Connection::STATUS_ZOMBIE) {
4153 mLock.unlock();
4154
Robert Carr803535b2018-08-02 16:38:15 -07004155 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156
4157 mLock.lock();
4158 }
4159}
4160
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004161void InputDispatcher::doNotifyFocusChangedLockedInterruptible(CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004162 sp<IBinder> oldToken = commandEntry->oldToken;
4163 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004164 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004165 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004166 mLock.lock();
4167}
4168
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004169void InputDispatcher::doNotifyANRLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 mLock.unlock();
4171
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004172 nsecs_t newTimeout =
4173 mPolicy->notifyANR(commandEntry->inputApplicationHandle,
4174 commandEntry->inputChannel ? commandEntry->inputChannel->getToken()
4175 : nullptr,
4176 commandEntry->reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177
4178 mLock.lock();
4179
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004180 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181}
4182
4183void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4184 CommandEntry* commandEntry) {
4185 KeyEntry* entry = commandEntry->keyEntry;
4186
4187 KeyEvent event;
4188 initializeKeyEvent(&event, entry);
4189
4190 mLock.unlock();
4191
Michael Wright2b3c3302018-03-02 17:19:13 +00004192 android::base::Timer t;
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004193 sp<IBinder> token = commandEntry->inputChannel != nullptr
4194 ? commandEntry->inputChannel->getToken()
4195 : nullptr;
4196 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token, &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004197 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4198 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004199 std::to_string(t.duration().count()).c_str());
Michael Wright2b3c3302018-03-02 17:19:13 +00004200 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201
4202 mLock.lock();
4203
4204 if (delay < 0) {
4205 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4206 } else if (!delay) {
4207 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4208 } else {
4209 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4210 entry->interceptKeyWakeupTime = now() + delay;
4211 }
4212 entry->release();
4213}
4214
chaviwfd6d3512019-03-25 13:23:49 -07004215void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4216 mLock.unlock();
4217 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4218 mLock.lock();
4219}
4220
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004221void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 sp<Connection> connection = commandEntry->connection;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004223 const nsecs_t finishTime = commandEntry->eventTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224 uint32_t seq = commandEntry->seq;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004225 const bool handled = commandEntry->handled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226
4227 // Handle post-event policy actions.
Garfield Tane84e6f92019-08-29 17:28:41 -07004228 std::deque<DispatchEntry*>::iterator dispatchEntryIt = connection->findWaitQueueEntry(seq);
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004229 if (dispatchEntryIt == connection->waitQueue.end()) {
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004230 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 }
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004232 DispatchEntry* dispatchEntry = *dispatchEntryIt;
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004233
4234 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4235 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
4236 std::string msg =
4237 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
4238 connection->getWindowName().c_str(), eventDuration * 0.000001f);
4239 dispatchEntry->eventEntry->appendDescription(msg);
4240 ALOGI("%s", msg.c_str());
4241 }
4242
4243 bool restartEvent;
4244 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4245 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4246 restartEvent =
4247 afterKeyEventLockedInterruptible(connection, dispatchEntry, keyEntry, handled);
4248 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4249 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4250 restartEvent = afterMotionEventLockedInterruptible(connection, dispatchEntry, motionEntry,
4251 handled);
4252 } else {
4253 restartEvent = false;
4254 }
4255
4256 // Dequeue the event and start the next cycle.
4257 // Note that because the lock might have been released, it is possible that the
4258 // contents of the wait queue to have been drained, so we need to double-check
4259 // a few things.
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004260 dispatchEntryIt = connection->findWaitQueueEntry(seq);
4261 if (dispatchEntryIt != connection->waitQueue.end()) {
4262 dispatchEntry = *dispatchEntryIt;
4263 connection->waitQueue.erase(dispatchEntryIt);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004264 traceWaitQueueLength(connection);
4265 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004266 connection->outboundQueue.push_front(dispatchEntry);
Siarhei Vishniakou4e68fbf2019-07-31 14:00:52 -07004267 traceOutboundQueueLength(connection);
4268 } else {
4269 releaseDispatchEntry(dispatchEntry);
4270 }
4271 }
4272
4273 // Start the next dispatch cycle for this connection.
4274 startDispatchCycleLocked(now(), connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275}
4276
4277bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004278 DispatchEntry* dispatchEntry,
4279 KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004280 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004281 if (!handled) {
4282 // Report the key as unhandled, since the fallback was not handled.
4283 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4284 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004285 return false;
4286 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004288 // Get the fallback key state.
4289 // Clear it out after dispatching the UP.
4290 int32_t originalKeyCode = keyEntry->keyCode;
4291 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4292 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4293 connection->inputState.removeFallbackKey(originalKeyCode);
4294 }
4295
4296 if (handled || !dispatchEntry->hasForegroundTarget()) {
4297 // If the application handles the original key for which we previously
4298 // generated a fallback or if the window is not a foreground window,
4299 // then cancel the associated fallback key, if any.
4300 if (fallbackKeyCode != -1) {
4301 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004303 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004304 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4305 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4306 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307#endif
4308 KeyEvent event;
4309 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004310 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311
4312 mLock.unlock();
4313
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004314 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), &event,
4315 keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316
4317 mLock.lock();
4318
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004319 // Cancel the fallback key.
4320 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004322 "application handled the original non-fallback key "
4323 "or is no longer a foreground target, "
4324 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 options.keyCode = fallbackKeyCode;
4326 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004328 connection->inputState.removeFallbackKey(originalKeyCode);
4329 }
4330 } else {
4331 // If the application did not handle a non-fallback key, first check
4332 // that we are in a good state to perform unhandled key event processing
4333 // Then ask the policy what to do with it.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004334 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN && keyEntry->repeatCount == 0;
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004335 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004337 ALOGD("Unhandled key event: Skipping unhandled key event processing "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004338 "since this is not an initial down. "
4339 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4340 originalKeyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004342 return false;
4343 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004345 // Dispatch the unhandled key to the policy.
4346#if DEBUG_OUTBOUND_EVENT_DETAILS
4347 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004348 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4349 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, keyEntry->policyFlags);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004350#endif
4351 KeyEvent event;
4352 initializeKeyEvent(&event, keyEntry);
4353
4354 mLock.unlock();
4355
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004356 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(), &event,
4357 keyEntry->policyFlags, &event);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004358
4359 mLock.lock();
4360
4361 if (connection->status != Connection::STATUS_NORMAL) {
4362 connection->inputState.removeFallbackKey(originalKeyCode);
4363 return false;
4364 }
4365
4366 // Latch the fallback keycode for this key on an initial down.
4367 // The fallback keycode cannot change at any other point in the lifecycle.
4368 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004370 fallbackKeyCode = event.getKeyCode();
4371 } else {
4372 fallbackKeyCode = AKEYCODE_UNKNOWN;
4373 }
4374 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4375 }
4376
4377 ALOG_ASSERT(fallbackKeyCode != -1);
4378
4379 // Cancel the fallback key if the policy decides not to send it anymore.
4380 // We will continue to dispatch the key to the policy but we will no
4381 // longer dispatch a fallback key to the application.
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004382 if (fallbackKeyCode != AKEYCODE_UNKNOWN &&
4383 (!fallback || fallbackKeyCode != event.getKeyCode())) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004384#if DEBUG_OUTBOUND_EVENT_DETAILS
4385 if (fallback) {
4386 ALOGD("Unhandled key event: Policy requested to send key %d"
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004387 "as a fallback for %d, but on the DOWN it had requested "
4388 "to send %d instead. Fallback canceled.",
4389 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004390 } else {
4391 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004392 "but on the DOWN it had requested to send %d. "
4393 "Fallback canceled.",
4394 originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004395 }
4396#endif
4397
4398 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4399 "canceling fallback, policy no longer desires it");
4400 options.keyCode = fallbackKeyCode;
4401 synthesizeCancelationEventsForConnectionLocked(connection, options);
4402
4403 fallback = false;
4404 fallbackKeyCode = AKEYCODE_UNKNOWN;
4405 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004406 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004407 }
4408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004409
4410#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004411 {
4412 std::string msg;
4413 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4414 connection->inputState.getFallbackKeys();
4415 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004416 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i), fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004417 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004418 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004419 fallbackKeys.size(), msg.c_str());
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004420 }
4421#endif
4422
4423 if (fallback) {
4424 // Restart the dispatch cycle using the fallback key.
4425 keyEntry->eventTime = event.getEventTime();
4426 keyEntry->deviceId = event.getDeviceId();
4427 keyEntry->source = event.getSource();
4428 keyEntry->displayId = event.getDisplayId();
4429 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4430 keyEntry->keyCode = fallbackKeyCode;
4431 keyEntry->scanCode = event.getScanCode();
4432 keyEntry->metaState = event.getMetaState();
4433 keyEntry->repeatCount = event.getRepeatCount();
4434 keyEntry->downTime = event.getDownTime();
4435 keyEntry->syntheticRepeat = false;
4436
4437#if DEBUG_OUTBOUND_EVENT_DETAILS
4438 ALOGD("Unhandled key event: Dispatching fallback key. "
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004439 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4440 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004441#endif
4442 return true; // restart the event
4443 } else {
4444#if DEBUG_OUTBOUND_EVENT_DETAILS
4445 ALOGD("Unhandled key event: No fallback key.");
4446#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004447
4448 // Report the key as unhandled, since there is no fallback key.
4449 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 }
4451 }
4452 return false;
4453}
4454
4455bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004456 DispatchEntry* dispatchEntry,
4457 MotionEntry* motionEntry, bool handled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004458 return false;
4459}
4460
4461void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4462 mLock.unlock();
4463
4464 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4465
4466 mLock.lock();
4467}
4468
4469void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004470 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004471 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4472 entry->downTime, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004473}
4474
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004475void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Garfield Tan0fc2fa72019-08-29 17:22:15 -07004476 int32_t injectionResult,
4477 nsecs_t timeSpentWaitingForApplication) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478 // TODO Write some statistics about how long we spend waiting.
4479}
4480
4481void InputDispatcher::traceInboundQueueLengthLocked() {
4482 if (ATRACE_ENABLED()) {
Siarhei Vishniakou44a2aed2019-07-29 08:59:52 -07004483 ATRACE_INT("iq", mInboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 }
4485}
4486
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004487void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004488 if (ATRACE_ENABLED()) {
4489 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004490 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004491 ATRACE_INT(counterName, connection->outboundQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492 }
4493}
4494
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004495void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004496 if (ATRACE_ENABLED()) {
4497 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004498 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Siarhei Vishniakou13bda6c2019-07-29 08:34:33 -07004499 ATRACE_INT(counterName, connection->waitQueue.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 }
4501}
4502
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004503void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004504 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004506 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507 dumpDispatchStateLocked(dump);
4508
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004509 if (!mLastANRState.empty()) {
4510 dump += "\nInput Dispatcher State at time of last ANR:\n";
4511 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 }
4513}
4514
4515void InputDispatcher::monitor() {
4516 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004517 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004518 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004519 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004520}
4521
Garfield Tane84e6f92019-08-29 17:28:41 -07004522} // namespace android::inputdispatcher