blob: 38104c4b98b287c3666539121dc5d18ec0b93c03 [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
20//#define LOG_NDEBUG 0
21
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
Michael Wrightd02c5b62014-02-10 15:10:22 -080048#include <errno.h>
49#include <limits.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080050#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070051#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070053#include <unistd.h>
54
Michael Wright2b3c3302018-03-02 17:19:13 +000055#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080056#include <android-base/stringprintf.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070057#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <utils/Trace.h>
59#include <powermanager/PowerManager.h>
60#include <ui/Region.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080061
62#define INDENT " "
63#define INDENT2 " "
64#define INDENT3 " "
65#define INDENT4 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
71// Default input dispatching timeout if there is no focused application or paused window
72// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000073constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080074
75// Amount of time to allow for all pending events to be processed when an app switch
76// key is on the way. This is used to preempt input dispatch and drop input events
77// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000078constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Amount of time to allow for an event to be dispatched (measured since its eventTime)
81// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000082constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080083
84// Amount of time to allow touch events to be streamed out to a connection before requiring
85// that the first event be finished. This value extends the ANR timeout by the specified
86// amount. For example, if streaming is allowed to get ahead by one second relative to the
87// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// 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 +000091constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
92
93// Log a warning when an interception call takes longer than this to process.
94constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
96// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +000097constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
98
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
100static inline nsecs_t now() {
101 return systemTime(SYSTEM_TIME_MONOTONIC);
102}
103
104static inline const char* toString(bool value) {
105 return value ? "true" : "false";
106}
107
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800108static std::string motionActionToString(int32_t action) {
109 // Convert MotionEvent action to string
110 switch(action & AMOTION_EVENT_ACTION_MASK) {
111 case AMOTION_EVENT_ACTION_DOWN:
112 return "DOWN";
113 case AMOTION_EVENT_ACTION_MOVE:
114 return "MOVE";
115 case AMOTION_EVENT_ACTION_UP:
116 return "UP";
117 case AMOTION_EVENT_ACTION_POINTER_DOWN:
118 return "POINTER_DOWN";
119 case AMOTION_EVENT_ACTION_POINTER_UP:
120 return "POINTER_UP";
121 }
122 return StringPrintf("%" PRId32, action);
123}
124
125static std::string keyActionToString(int32_t action) {
126 // Convert KeyEvent action to string
127 switch(action) {
128 case AKEY_EVENT_ACTION_DOWN:
129 return "DOWN";
130 case AKEY_EVENT_ACTION_UP:
131 return "UP";
132 case AKEY_EVENT_ACTION_MULTIPLE:
133 return "MULTIPLE";
134 }
135 return StringPrintf("%" PRId32, action);
136}
137
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
139 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
140 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
141}
142
143static bool isValidKeyAction(int32_t action) {
144 switch (action) {
145 case AKEY_EVENT_ACTION_DOWN:
146 case AKEY_EVENT_ACTION_UP:
147 return true;
148 default:
149 return false;
150 }
151}
152
153static bool validateKeyEvent(int32_t action) {
154 if (! isValidKeyAction(action)) {
155 ALOGE("Key event has invalid action code 0x%x", action);
156 return false;
157 }
158 return true;
159}
160
Michael Wright7b159c92015-05-14 14:48:03 +0100161static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800162 switch (action & AMOTION_EVENT_ACTION_MASK) {
163 case AMOTION_EVENT_ACTION_DOWN:
164 case AMOTION_EVENT_ACTION_UP:
165 case AMOTION_EVENT_ACTION_CANCEL:
166 case AMOTION_EVENT_ACTION_MOVE:
167 case AMOTION_EVENT_ACTION_OUTSIDE:
168 case AMOTION_EVENT_ACTION_HOVER_ENTER:
169 case AMOTION_EVENT_ACTION_HOVER_MOVE:
170 case AMOTION_EVENT_ACTION_HOVER_EXIT:
171 case AMOTION_EVENT_ACTION_SCROLL:
172 return true;
173 case AMOTION_EVENT_ACTION_POINTER_DOWN:
174 case AMOTION_EVENT_ACTION_POINTER_UP: {
175 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800176 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 }
Michael Wright7b159c92015-05-14 14:48:03 +0100178 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
179 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
180 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 default:
182 return false;
183 }
184}
185
Michael Wright7b159c92015-05-14 14:48:03 +0100186static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100188 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 ALOGE("Motion event has invalid action code 0x%x", action);
190 return false;
191 }
192 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000193 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 pointerCount, MAX_POINTERS);
195 return false;
196 }
197 BitSet32 pointerIdBits;
198 for (size_t i = 0; i < pointerCount; i++) {
199 int32_t id = pointerProperties[i].id;
200 if (id < 0 || id > MAX_POINTER_ID) {
201 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
202 id, MAX_POINTER_ID);
203 return false;
204 }
205 if (pointerIdBits.hasBit(id)) {
206 ALOGE("Motion event has duplicate pointer id %d", id);
207 return false;
208 }
209 pointerIdBits.markBit(id);
210 }
211 return true;
212}
213
214static bool isMainDisplay(int32_t displayId) {
215 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
216}
217
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800218static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800220 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 return;
222 }
223
224 bool first = true;
225 Region::const_iterator cur = region.begin();
226 Region::const_iterator const tail = region.end();
227 while (cur != tail) {
228 if (first) {
229 first = false;
230 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800231 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800233 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 cur++;
235 }
236}
237
Tiger Huang721e26f2018-07-24 22:26:19 +0800238template<typename T, typename U>
239static T getValueByKey(std::unordered_map<U, T>& map, U key) {
240 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
241 return it != map.end() ? it->second : T{};
242}
243
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244
245// --- InputDispatcher ---
246
247InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
248 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700249 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100250 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700251 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800253 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
255 mLooper = new Looper(false);
256
Yi Kong9b14ac62018-07-17 13:48:38 -0700257 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258
259 policy->getDispatcherConfiguration(&mConfig);
260}
261
262InputDispatcher::~InputDispatcher() {
263 { // acquire lock
264 AutoMutex _l(mLock);
265
266 resetKeyRepeatLocked();
267 releasePendingEventLocked();
268 drainInboundQueueLocked();
269 }
270
271 while (mConnectionsByFd.size() != 0) {
272 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
273 }
274}
275
276void InputDispatcher::dispatchOnce() {
277 nsecs_t nextWakeupTime = LONG_LONG_MAX;
278 { // acquire lock
279 AutoMutex _l(mLock);
280 mDispatcherIsAliveCondition.broadcast();
281
282 // Run a dispatch loop if there are no pending commands.
283 // The dispatch loop might enqueue commands to run afterwards.
284 if (!haveCommandsLocked()) {
285 dispatchOnceInnerLocked(&nextWakeupTime);
286 }
287
288 // Run all pending commands if there are any.
289 // If any commands were run then force the next poll to wake up immediately.
290 if (runCommandsLockedInterruptible()) {
291 nextWakeupTime = LONG_LONG_MIN;
292 }
293 } // release lock
294
295 // Wait for callback or timeout or wake. (make sure we round up, not down)
296 nsecs_t currentTime = now();
297 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
298 mLooper->pollOnce(timeoutMillis);
299}
300
301void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
302 nsecs_t currentTime = now();
303
Jeff Browndc5992e2014-04-11 01:27:26 -0700304 // Reset the key repeat timer whenever normal dispatch is suspended while the
305 // device is in a non-interactive state. This is to ensure that we abort a key
306 // repeat if the device is just coming out of sleep.
307 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800308 resetKeyRepeatLocked();
309 }
310
311 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
312 if (mDispatchFrozen) {
313#if DEBUG_FOCUS
314 ALOGD("Dispatch frozen. Waiting some more.");
315#endif
316 return;
317 }
318
319 // Optimize latency of app switches.
320 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
321 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
322 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
323 if (mAppSwitchDueTime < *nextWakeupTime) {
324 *nextWakeupTime = mAppSwitchDueTime;
325 }
326
327 // Ready to start a new event.
328 // If we don't already have a pending event, go grab one.
329 if (! mPendingEvent) {
330 if (mInboundQueue.isEmpty()) {
331 if (isAppSwitchDue) {
332 // The inbound queue is empty so the app switch key we were waiting
333 // for will never arrive. Stop waiting for it.
334 resetPendingAppSwitchLocked(false);
335 isAppSwitchDue = false;
336 }
337
338 // Synthesize a key repeat if appropriate.
339 if (mKeyRepeatState.lastKeyEntry) {
340 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
341 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
342 } else {
343 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
344 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
345 }
346 }
347 }
348
349 // Nothing to do if there is no pending event.
350 if (!mPendingEvent) {
351 return;
352 }
353 } else {
354 // Inbound queue has at least one entry.
355 mPendingEvent = mInboundQueue.dequeueAtHead();
356 traceInboundQueueLengthLocked();
357 }
358
359 // Poke user activity for this event.
360 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
361 pokeUserActivityLocked(mPendingEvent);
362 }
363
364 // Get ready to dispatch the event.
365 resetANRTimeoutsLocked();
366 }
367
368 // Now we have an event to dispatch.
369 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700370 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800371 bool done = false;
372 DropReason dropReason = DROP_REASON_NOT_DROPPED;
373 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
374 dropReason = DROP_REASON_POLICY;
375 } else if (!mDispatchEnabled) {
376 dropReason = DROP_REASON_DISABLED;
377 }
378
379 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700380 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800381 }
382
383 switch (mPendingEvent->type) {
384 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
385 ConfigurationChangedEntry* typedEntry =
386 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
387 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
388 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
389 break;
390 }
391
392 case EventEntry::TYPE_DEVICE_RESET: {
393 DeviceResetEntry* typedEntry =
394 static_cast<DeviceResetEntry*>(mPendingEvent);
395 done = dispatchDeviceResetLocked(currentTime, typedEntry);
396 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
397 break;
398 }
399
400 case EventEntry::TYPE_KEY: {
401 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
402 if (isAppSwitchDue) {
403 if (isAppSwitchKeyEventLocked(typedEntry)) {
404 resetPendingAppSwitchLocked(true);
405 isAppSwitchDue = false;
406 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
407 dropReason = DROP_REASON_APP_SWITCH;
408 }
409 }
410 if (dropReason == DROP_REASON_NOT_DROPPED
411 && isStaleEventLocked(currentTime, typedEntry)) {
412 dropReason = DROP_REASON_STALE;
413 }
414 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
415 dropReason = DROP_REASON_BLOCKED;
416 }
417 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
418 break;
419 }
420
421 case EventEntry::TYPE_MOTION: {
422 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
423 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
424 dropReason = DROP_REASON_APP_SWITCH;
425 }
426 if (dropReason == DROP_REASON_NOT_DROPPED
427 && isStaleEventLocked(currentTime, typedEntry)) {
428 dropReason = DROP_REASON_STALE;
429 }
430 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
431 dropReason = DROP_REASON_BLOCKED;
432 }
433 done = dispatchMotionLocked(currentTime, typedEntry,
434 &dropReason, nextWakeupTime);
435 break;
436 }
437
438 default:
439 ALOG_ASSERT(false);
440 break;
441 }
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();
450 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
451 }
452}
453
454bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
455 bool needWake = mInboundQueue.isEmpty();
456 mInboundQueue.enqueueAtTail(entry);
457 traceInboundQueueLengthLocked();
458
459 switch (entry->type) {
460 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 (isAppSwitchKeyEventLocked(keyEntry)) {
466 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
467 mAppSwitchSawKeyDown = true;
468 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
469 if (mAppSwitchSawKeyDown) {
470#if DEBUG_APP_SWITCH
471 ALOGD("App switch is pending!");
472#endif
473 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
Yi Kong9b14ac62018-07-17 13:48:38 -0700491 && mInputTargetWaitApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492 int32_t displayId = motionEntry->displayId;
493 int32_t x = int32_t(motionEntry->pointerCoords[0].
494 getAxisValue(AMOTION_EVENT_AXIS_X));
495 int32_t y = int32_t(motionEntry->pointerCoords[0].
496 getAxisValue(AMOTION_EVENT_AXIS_Y));
497 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700498 if (touchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499 && touchedWindowHandle->inputApplicationHandle
500 != mInputTargetWaitApplicationHandle) {
501 // User touched a different application than the one we are waiting on.
502 // Flag the event, and start pruning the input queue.
503 mNextUnblockedEvent = motionEntry;
504 needWake = true;
505 }
506 }
507 break;
508 }
509 }
510
511 return needWake;
512}
513
514void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
515 entry->refCount += 1;
516 mRecentQueue.enqueueAtTail(entry);
517 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
518 mRecentQueue.dequeueAtHead()->release();
519 }
520}
521
522sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
523 int32_t x, int32_t y) {
524 // Traverse windows from front to back to find touched window.
Arthur Hungb92218b2018-08-14 12:00:21 +0800525 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
526 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800528 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529 const InputWindowInfo* windowInfo = windowHandle->getInfo();
530 if (windowInfo->displayId == displayId) {
531 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532
533 if (windowInfo->visible) {
534 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
535 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
536 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
537 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
538 // Found window.
539 return windowHandle;
540 }
541 }
542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 }
544 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700545 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546}
547
548void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
549 const char* reason;
550 switch (dropReason) {
551 case DROP_REASON_POLICY:
552#if DEBUG_INBOUND_EVENT_DETAILS
553 ALOGD("Dropped event because policy consumed it.");
554#endif
555 reason = "inbound event was dropped because the policy consumed it";
556 break;
557 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100558 if (mLastDropReason != DROP_REASON_DISABLED) {
559 ALOGI("Dropped event because input dispatch is disabled.");
560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561 reason = "inbound event was dropped because input dispatch is disabled";
562 break;
563 case DROP_REASON_APP_SWITCH:
564 ALOGI("Dropped event because of pending overdue app switch.");
565 reason = "inbound event was dropped because of pending overdue app switch";
566 break;
567 case DROP_REASON_BLOCKED:
568 ALOGI("Dropped event because the current application is not responding and the user "
569 "has started interacting with a different application.");
570 reason = "inbound event was dropped because the current application is not responding "
571 "and the user has started interacting with a different application";
572 break;
573 case DROP_REASON_STALE:
574 ALOGI("Dropped event because it is stale.");
575 reason = "inbound event was dropped because it is stale";
576 break;
577 default:
578 ALOG_ASSERT(false);
579 return;
580 }
581
582 switch (entry->type) {
583 case EventEntry::TYPE_KEY: {
584 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
585 synthesizeCancelationEventsForAllConnectionsLocked(options);
586 break;
587 }
588 case EventEntry::TYPE_MOTION: {
589 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
590 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
591 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
592 synthesizeCancelationEventsForAllConnectionsLocked(options);
593 } else {
594 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
595 synthesizeCancelationEventsForAllConnectionsLocked(options);
596 }
597 break;
598 }
599 }
600}
601
602bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
603 return keyCode == AKEYCODE_HOME
604 || keyCode == AKEYCODE_ENDCALL
605 || keyCode == AKEYCODE_APP_SWITCH;
606}
607
608bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
609 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
610 && isAppSwitchKeyCode(keyEntry->keyCode)
611 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
612 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
613}
614
615bool InputDispatcher::isAppSwitchPendingLocked() {
616 return mAppSwitchDueTime != LONG_LONG_MAX;
617}
618
619void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
620 mAppSwitchDueTime = LONG_LONG_MAX;
621
622#if DEBUG_APP_SWITCH
623 if (handled) {
624 ALOGD("App switch has arrived.");
625 } else {
626 ALOGD("App switch was abandoned.");
627 }
628#endif
629}
630
631bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
632 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
633}
634
635bool InputDispatcher::haveCommandsLocked() const {
636 return !mCommandQueue.isEmpty();
637}
638
639bool InputDispatcher::runCommandsLockedInterruptible() {
640 if (mCommandQueue.isEmpty()) {
641 return false;
642 }
643
644 do {
645 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
646
647 Command command = commandEntry->command;
648 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
649
650 commandEntry->connection.clear();
651 delete commandEntry;
652 } while (! mCommandQueue.isEmpty());
653 return true;
654}
655
656InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
657 CommandEntry* commandEntry = new CommandEntry(command);
658 mCommandQueue.enqueueAtTail(commandEntry);
659 return commandEntry;
660}
661
662void InputDispatcher::drainInboundQueueLocked() {
663 while (! mInboundQueue.isEmpty()) {
664 EventEntry* entry = mInboundQueue.dequeueAtHead();
665 releaseInboundEventLocked(entry);
666 }
667 traceInboundQueueLengthLocked();
668}
669
670void InputDispatcher::releasePendingEventLocked() {
671 if (mPendingEvent) {
672 resetANRTimeoutsLocked();
673 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700674 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 }
676}
677
678void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
679 InjectionState* injectionState = entry->injectionState;
680 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
681#if DEBUG_DISPATCH_CYCLE
682 ALOGD("Injected inbound event was dropped.");
683#endif
684 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
685 }
686 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700687 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 }
689 addRecentEventLocked(entry);
690 entry->release();
691}
692
693void InputDispatcher::resetKeyRepeatLocked() {
694 if (mKeyRepeatState.lastKeyEntry) {
695 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700696 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 }
698}
699
700InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
701 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
702
703 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700704 uint32_t policyFlags = entry->policyFlags &
705 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706 if (entry->refCount == 1) {
707 entry->recycle();
708 entry->eventTime = currentTime;
709 entry->policyFlags = policyFlags;
710 entry->repeatCount += 1;
711 } else {
712 KeyEntry* newEntry = new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100713 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 entry->action, entry->flags, entry->keyCode, entry->scanCode,
715 entry->metaState, entry->repeatCount + 1, entry->downTime);
716
717 mKeyRepeatState.lastKeyEntry = newEntry;
718 entry->release();
719
720 entry = newEntry;
721 }
722 entry->syntheticRepeat = true;
723
724 // Increment reference count since we keep a reference to the event in
725 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
726 entry->refCount += 1;
727
728 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
729 return entry;
730}
731
732bool InputDispatcher::dispatchConfigurationChangedLocked(
733 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
734#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700735 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736#endif
737
738 // Reset key repeating in case a keyboard device was added or removed or something.
739 resetKeyRepeatLocked();
740
741 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
742 CommandEntry* commandEntry = postCommandLocked(
743 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
744 commandEntry->eventTime = entry->eventTime;
745 return true;
746}
747
748bool InputDispatcher::dispatchDeviceResetLocked(
749 nsecs_t currentTime, DeviceResetEntry* entry) {
750#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700751 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
752 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753#endif
754
755 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
756 "device was reset");
757 options.deviceId = entry->deviceId;
758 synthesizeCancelationEventsForAllConnectionsLocked(options);
759 return true;
760}
761
762bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
763 DropReason* dropReason, nsecs_t* nextWakeupTime) {
764 // Preprocessing.
765 if (! entry->dispatchInProgress) {
766 if (entry->repeatCount == 0
767 && entry->action == AKEY_EVENT_ACTION_DOWN
768 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
769 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
770 if (mKeyRepeatState.lastKeyEntry
771 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
772 // We have seen two identical key downs in a row which indicates that the device
773 // driver is automatically generating key repeats itself. We take note of the
774 // repeat here, but we disable our own next key repeat timer since it is clear that
775 // we will not need to synthesize key repeats ourselves.
776 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
777 resetKeyRepeatLocked();
778 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
779 } else {
780 // Not a repeat. Save key down state in case we do see a repeat later.
781 resetKeyRepeatLocked();
782 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
783 }
784 mKeyRepeatState.lastKeyEntry = entry;
785 entry->refCount += 1;
786 } else if (! entry->syntheticRepeat) {
787 resetKeyRepeatLocked();
788 }
789
790 if (entry->repeatCount == 1) {
791 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
792 } else {
793 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
794 }
795
796 entry->dispatchInProgress = true;
797
798 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
799 }
800
801 // Handle case where the policy asked us to try again later last time.
802 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
803 if (currentTime < entry->interceptKeyWakeupTime) {
804 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
805 *nextWakeupTime = entry->interceptKeyWakeupTime;
806 }
807 return false; // wait until next wakeup
808 }
809 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
810 entry->interceptKeyWakeupTime = 0;
811 }
812
813 // Give the policy a chance to intercept the key.
814 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
815 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
816 CommandEntry* commandEntry = postCommandLocked(
817 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800818 sp<InputWindowHandle> focusedWindowHandle =
819 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
820 if (focusedWindowHandle != nullptr) {
821 commandEntry->inputWindowHandle = focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 }
823 commandEntry->keyEntry = entry;
824 entry->refCount += 1;
825 return false; // wait for the command to run
826 } else {
827 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
828 }
829 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
830 if (*dropReason == DROP_REASON_NOT_DROPPED) {
831 *dropReason = DROP_REASON_POLICY;
832 }
833 }
834
835 // Clean up if dropping the event.
836 if (*dropReason != DROP_REASON_NOT_DROPPED) {
837 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
838 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
839 return true;
840 }
841
842 // Identify targets.
843 Vector<InputTarget> inputTargets;
844 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
845 entry, inputTargets, nextWakeupTime);
846 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
847 return false;
848 }
849
850 setInjectionResultLocked(entry, injectionResult);
851 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
852 return true;
853 }
854
855 addMonitoringTargetsLocked(inputTargets);
856
857 // Dispatch the key.
858 dispatchEventLocked(currentTime, entry, inputTargets);
859 return true;
860}
861
862void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
863#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100864 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
865 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
866 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100868 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
870 entry->repeatCount, entry->downTime);
871#endif
872}
873
874bool InputDispatcher::dispatchMotionLocked(
875 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
876 // Preprocessing.
877 if (! entry->dispatchInProgress) {
878 entry->dispatchInProgress = true;
879
880 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
881 }
882
883 // Clean up if dropping the event.
884 if (*dropReason != DROP_REASON_NOT_DROPPED) {
885 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
886 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
887 return true;
888 }
889
890 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
891
892 // Identify targets.
893 Vector<InputTarget> inputTargets;
894
895 bool conflictingPointerActions = false;
896 int32_t injectionResult;
897 if (isPointerEvent) {
898 // Pointer event. (eg. touchscreen)
899 injectionResult = findTouchedWindowTargetsLocked(currentTime,
900 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
901 } else {
902 // Non touch event. (eg. trackball)
903 injectionResult = findFocusedWindowTargetsLocked(currentTime,
904 entry, inputTargets, nextWakeupTime);
905 }
906 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
907 return false;
908 }
909
910 setInjectionResultLocked(entry, injectionResult);
911 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100912 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
913 CancelationOptions::Mode mode(isPointerEvent ?
914 CancelationOptions::CANCEL_POINTER_EVENTS :
915 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
916 CancelationOptions options(mode, "input event injection failed");
917 synthesizeCancelationEventsForMonitorsLocked(options);
918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919 return true;
920 }
921
Tarandeep Singh48aeb512017-07-17 11:22:52 -0700922 addMonitoringTargetsLocked(inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923
924 // Dispatch the motion.
925 if (conflictingPointerActions) {
926 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
927 "conflicting pointer actions");
928 synthesizeCancelationEventsForAllConnectionsLocked(options);
929 }
930 dispatchEventLocked(currentTime, entry, inputTargets);
931 return true;
932}
933
934
935void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
936#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800937 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
938 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100939 "action=0x%x, actionButton=0x%x, flags=0x%x, "
940 "metaState=0x%x, buttonState=0x%x,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700941 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800943 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100944 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 entry->metaState, entry->buttonState,
946 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
947 entry->downTime);
948
949 for (uint32_t i = 0; i < entry->pointerCount; i++) {
950 ALOGD(" Pointer %d: id=%d, toolType=%d, "
951 "x=%f, y=%f, pressure=%f, size=%f, "
952 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800953 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 i, entry->pointerProperties[i].id,
955 entry->pointerProperties[i].toolType,
956 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
957 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
958 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
959 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
960 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
961 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
962 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
963 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800964 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 }
966#endif
967}
968
969void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
970 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
971#if DEBUG_DISPATCH_CYCLE
972 ALOGD("dispatchEventToCurrentInputTargets");
973#endif
974
975 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
976
977 pokeUserActivityLocked(eventEntry);
978
979 for (size_t i = 0; i < inputTargets.size(); i++) {
980 const InputTarget& inputTarget = inputTargets.itemAt(i);
981
982 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
983 if (connectionIndex >= 0) {
984 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
985 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
986 } else {
987#if DEBUG_FOCUS
988 ALOGD("Dropping event delivery to target with channel '%s' because it "
989 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800990 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991#endif
992 }
993 }
994}
995
996int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
997 const EventEntry* entry,
998 const sp<InputApplicationHandle>& applicationHandle,
999 const sp<InputWindowHandle>& windowHandle,
1000 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001001 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001002 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1003#if DEBUG_FOCUS
1004 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1005#endif
1006 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1007 mInputTargetWaitStartTime = currentTime;
1008 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1009 mInputTargetWaitTimeoutExpired = false;
1010 mInputTargetWaitApplicationHandle.clear();
1011 }
1012 } else {
1013 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1014#if DEBUG_FOCUS
1015 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001016 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 reason);
1018#endif
1019 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001020 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001022 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 timeout = applicationHandle->getDispatchingTimeout(
1024 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1025 } else {
1026 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1027 }
1028
1029 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1030 mInputTargetWaitStartTime = currentTime;
1031 mInputTargetWaitTimeoutTime = currentTime + timeout;
1032 mInputTargetWaitTimeoutExpired = false;
1033 mInputTargetWaitApplicationHandle.clear();
1034
Yi Kong9b14ac62018-07-17 13:48:38 -07001035 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
1037 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001038 if (mInputTargetWaitApplicationHandle == nullptr && applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 mInputTargetWaitApplicationHandle = applicationHandle;
1040 }
1041 }
1042 }
1043
1044 if (mInputTargetWaitTimeoutExpired) {
1045 return INPUT_EVENT_INJECTION_TIMED_OUT;
1046 }
1047
1048 if (currentTime >= mInputTargetWaitTimeoutTime) {
1049 onANRLocked(currentTime, applicationHandle, windowHandle,
1050 entry->eventTime, mInputTargetWaitStartTime, reason);
1051
1052 // Force poll loop to wake up immediately on next iteration once we get the
1053 // ANR response back from the policy.
1054 *nextWakeupTime = LONG_LONG_MIN;
1055 return INPUT_EVENT_INJECTION_PENDING;
1056 } else {
1057 // Force poll loop to wake up when timeout is due.
1058 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1059 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1060 }
1061 return INPUT_EVENT_INJECTION_PENDING;
1062 }
1063}
1064
1065void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1066 const sp<InputChannel>& inputChannel) {
1067 if (newTimeout > 0) {
1068 // Extend the timeout.
1069 mInputTargetWaitTimeoutTime = now() + newTimeout;
1070 } else {
1071 // Give up.
1072 mInputTargetWaitTimeoutExpired = true;
1073
1074 // Input state will not be realistic. Mark it out of sync.
1075 if (inputChannel.get()) {
1076 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1077 if (connectionIndex >= 0) {
1078 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1079 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1080
Yi Kong9b14ac62018-07-17 13:48:38 -07001081 if (windowHandle != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001082 const InputWindowInfo* info = windowHandle->getInfo();
1083 if (info) {
1084 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId);
1085 if (stateIndex >= 0) {
1086 mTouchStatesByDisplay.editValueAt(stateIndex).removeWindow(
1087 windowHandle);
1088 }
1089 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 }
1091
1092 if (connection->status == Connection::STATUS_NORMAL) {
1093 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1094 "application not responding");
1095 synthesizeCancelationEventsForConnectionLocked(connection, options);
1096 }
1097 }
1098 }
1099 }
1100}
1101
1102nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1103 nsecs_t currentTime) {
1104 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1105 return currentTime - mInputTargetWaitStartTime;
1106 }
1107 return 0;
1108}
1109
1110void InputDispatcher::resetANRTimeoutsLocked() {
1111#if DEBUG_FOCUS
1112 ALOGD("Resetting ANR timeouts.");
1113#endif
1114
1115 // Reset input target wait timeout.
1116 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1117 mInputTargetWaitApplicationHandle.clear();
1118}
1119
Tiger Huang721e26f2018-07-24 22:26:19 +08001120/**
1121 * Get the display id that the given event should go to. If this event specifies a valid display id,
1122 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1123 * Focused display is the display that the user most recently interacted with.
1124 */
1125int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1126 int32_t displayId;
1127 switch (entry->type) {
1128 case EventEntry::TYPE_KEY: {
1129 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1130 displayId = typedEntry->displayId;
1131 break;
1132 }
1133 case EventEntry::TYPE_MOTION: {
1134 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1135 displayId = typedEntry->displayId;
1136 break;
1137 }
1138 default: {
1139 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1140 return ADISPLAY_ID_NONE;
1141 }
1142 }
1143 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1144}
1145
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1147 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1148 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001149 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150
Tiger Huang721e26f2018-07-24 22:26:19 +08001151 int32_t displayId = getTargetDisplayId(entry);
1152 sp<InputWindowHandle> focusedWindowHandle =
1153 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1154 sp<InputApplicationHandle> focusedApplicationHandle =
1155 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1156
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157 // If there is no currently focused window and no focused application
1158 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001159 if (focusedWindowHandle == nullptr) {
1160 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001162 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 "Waiting because no window has focus but there is a "
1164 "focused application that may eventually add a window "
1165 "when it finishes starting up.");
1166 goto Unresponsive;
1167 }
1168
1169 ALOGI("Dropping event because there is no focused window or focused application.");
1170 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1171 goto Failed;
1172 }
1173
1174 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001175 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1177 goto Failed;
1178 }
1179
Jeff Brownffb49772014-10-10 19:01:34 -07001180 // Check whether the window is ready for more input.
1181 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001182 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001183 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001185 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 goto Unresponsive;
1187 }
1188
1189 // Success! Output targets.
1190 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001191 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1193 inputTargets);
1194
1195 // Done.
1196Failed:
1197Unresponsive:
1198 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1199 updateDispatchStatisticsLocked(currentTime, entry,
1200 injectionResult, timeSpentWaitingForApplication);
1201#if DEBUG_FOCUS
1202 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1203 "timeSpentWaitingForApplication=%0.1fms",
1204 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1205#endif
1206 return injectionResult;
1207}
1208
1209int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1210 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1211 bool* outConflictingPointerActions) {
1212 enum InjectionPermission {
1213 INJECTION_PERMISSION_UNKNOWN,
1214 INJECTION_PERMISSION_GRANTED,
1215 INJECTION_PERMISSION_DENIED
1216 };
1217
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 // For security reasons, we defer updating the touch state until we are sure that
1219 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 int32_t displayId = entry->displayId;
1221 int32_t action = entry->action;
1222 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1223
1224 // Update the touch state as needed based on the properties of the touch event.
1225 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1226 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1227 sp<InputWindowHandle> newHoverWindowHandle;
1228
Jeff Brownf086ddb2014-02-11 14:28:48 -08001229 // Copy current touch state into mTempTouchState.
1230 // This state is always reset at the end of this function, so if we don't find state
1231 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001232 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001233 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1234 if (oldStateIndex >= 0) {
1235 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1236 mTempTouchState.copyFrom(*oldState);
1237 }
1238
1239 bool isSplit = mTempTouchState.split;
1240 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1241 && (mTempTouchState.deviceId != entry->deviceId
1242 || mTempTouchState.source != entry->source
1243 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1245 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1246 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1247 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1248 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1249 || isHoverAction);
1250 bool wrongDevice = false;
1251 if (newGesture) {
1252 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001253 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254#if DEBUG_FOCUS
1255 ALOGD("Dropping event because a pointer for a different device is already down.");
1256#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001257 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1259 switchedDevice = false;
1260 wrongDevice = true;
1261 goto Failed;
1262 }
1263 mTempTouchState.reset();
1264 mTempTouchState.down = down;
1265 mTempTouchState.deviceId = entry->deviceId;
1266 mTempTouchState.source = entry->source;
1267 mTempTouchState.displayId = displayId;
1268 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001269 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1270#if DEBUG_FOCUS
1271 ALOGI("Dropping move event because a pointer for a different device is already active.");
1272#endif
1273 // TODO: test multiple simultaneous input streams.
1274 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1275 switchedDevice = false;
1276 wrongDevice = true;
1277 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 }
1279
1280 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1281 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1282
1283 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1284 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1285 getAxisValue(AMOTION_EVENT_AXIS_X));
1286 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1287 getAxisValue(AMOTION_EVENT_AXIS_Y));
1288 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289 bool isTouchModal = false;
1290
1291 // Traverse windows from front to back to find touched window and outside targets.
Arthur Hungb92218b2018-08-14 12:00:21 +08001292 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1293 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001295 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1297 if (windowInfo->displayId != displayId) {
1298 continue; // wrong display
1299 }
1300
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 int32_t flags = windowInfo->layoutParamsFlags;
1302 if (windowInfo->visible) {
1303 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1304 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1305 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1306 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001307 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 break; // found touched window, exit window loop
1309 }
1310 }
1311
1312 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1313 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001315 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001316 }
1317 }
1318 }
1319
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001321 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1323 // New window supports splitting.
1324 isSplit = true;
1325 } else if (isSplit) {
1326 // New window does not support splitting but we have already split events.
1327 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001328 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 }
1330
1331 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001332 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333 // Try to assign the pointer to the first foreground window we find, if there is one.
1334 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001335 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001336 ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y);
1337 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1338 goto Failed;
1339 }
1340 }
1341
1342 // Set target flags.
1343 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1344 if (isSplit) {
1345 targetFlags |= InputTarget::FLAG_SPLIT;
1346 }
1347 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1348 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001349 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1350 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001351 }
1352
1353 // Update hover state.
1354 if (isHoverAction) {
1355 newHoverWindowHandle = newTouchedWindowHandle;
1356 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1357 newHoverWindowHandle = mLastHoverWindowHandle;
1358 }
1359
1360 // Update the temporary touch state.
1361 BitSet32 pointerIds;
1362 if (isSplit) {
1363 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1364 pointerIds.markBit(pointerId);
1365 }
1366 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1367 } else {
1368 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1369
1370 // If the pointer is not currently down, then ignore the event.
1371 if (! mTempTouchState.down) {
1372#if DEBUG_FOCUS
1373 ALOGD("Dropping event because the pointer is not down or we previously "
1374 "dropped the pointer down event.");
1375#endif
1376 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1377 goto Failed;
1378 }
1379
1380 // Check whether touches should slip outside of the current foreground window.
1381 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1382 && entry->pointerCount == 1
1383 && mTempTouchState.isSlippery()) {
1384 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1385 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1386
1387 sp<InputWindowHandle> oldTouchedWindowHandle =
1388 mTempTouchState.getFirstForegroundWindowHandle();
1389 sp<InputWindowHandle> newTouchedWindowHandle =
1390 findTouchedWindowAtLocked(displayId, x, y);
1391 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001392 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393#if DEBUG_FOCUS
1394 ALOGD("Touch is slipping out of window %s into window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001395 oldTouchedWindowHandle->getName().c_str(),
1396 newTouchedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397#endif
1398 // Make a slippery exit from the old window.
1399 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1400 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1401
1402 // Make a slippery entrance into the new window.
1403 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1404 isSplit = true;
1405 }
1406
1407 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1408 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1409 if (isSplit) {
1410 targetFlags |= InputTarget::FLAG_SPLIT;
1411 }
1412 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1413 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1414 }
1415
1416 BitSet32 pointerIds;
1417 if (isSplit) {
1418 pointerIds.markBit(entry->pointerProperties[0].id);
1419 }
1420 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1421 }
1422 }
1423 }
1424
1425 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1426 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001427 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428#if DEBUG_HOVER
1429 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001430 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431#endif
1432 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1433 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1434 }
1435
1436 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001437 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438#if DEBUG_HOVER
1439 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001440 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441#endif
1442 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1443 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1444 }
1445 }
1446
1447 // Check permission to inject into all touched foreground windows and ensure there
1448 // is at least one touched foreground window.
1449 {
1450 bool haveForegroundWindow = false;
1451 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1452 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1453 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1454 haveForegroundWindow = true;
1455 if (! checkInjectionPermission(touchedWindow.windowHandle,
1456 entry->injectionState)) {
1457 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1458 injectionPermission = INJECTION_PERMISSION_DENIED;
1459 goto Failed;
1460 }
1461 }
1462 }
1463 if (! haveForegroundWindow) {
1464#if DEBUG_FOCUS
1465 ALOGD("Dropping event because there is no touched foreground window to receive it.");
1466#endif
1467 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1468 goto Failed;
1469 }
1470
1471 // Permission granted to injection into all touched foreground windows.
1472 injectionPermission = INJECTION_PERMISSION_GRANTED;
1473 }
1474
1475 // Check whether windows listening for outside touches are owned by the same UID. If it is
1476 // set the policy flag that we will not reveal coordinate information to this window.
1477 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1478 sp<InputWindowHandle> foregroundWindowHandle =
1479 mTempTouchState.getFirstForegroundWindowHandle();
1480 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1481 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1482 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1483 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1484 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1485 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1486 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1487 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1488 }
1489 }
1490 }
1491 }
1492
1493 // Ensure all touched foreground windows are ready for new input.
1494 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1495 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1496 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001497 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001498 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001499 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001500 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001501 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001502 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 goto Unresponsive;
1504 }
1505 }
1506 }
1507
1508 // If this is the first pointer going down and the touched window has a wallpaper
1509 // then also add the touched wallpaper windows so they are locked in for the duration
1510 // of the touch gesture.
1511 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1512 // engine only supports touch events. We would need to add a mechanism similar
1513 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1514 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1515 sp<InputWindowHandle> foregroundWindowHandle =
1516 mTempTouchState.getFirstForegroundWindowHandle();
1517 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001518 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1519 size_t numWindows = windowHandles.size();
1520 for (size_t i = 0; i < numWindows; i++) {
1521 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001522 const InputWindowInfo* info = windowHandle->getInfo();
1523 if (info->displayId == displayId
1524 && windowHandle->getInfo()->layoutParamsType
1525 == InputWindowInfo::TYPE_WALLPAPER) {
1526 mTempTouchState.addOrUpdateWindow(windowHandle,
1527 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001528 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529 | InputTarget::FLAG_DISPATCH_AS_IS,
1530 BitSet32(0));
1531 }
1532 }
1533 }
1534 }
1535
1536 // Success! Output targets.
1537 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1538
1539 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1540 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1541 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1542 touchedWindow.pointerIds, inputTargets);
1543 }
1544
1545 // Drop the outside or hover touch windows since we will not care about them
1546 // in the next iteration.
1547 mTempTouchState.filterNonAsIsTouchWindows();
1548
1549Failed:
1550 // Check injection permission once and for all.
1551 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001552 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 injectionPermission = INJECTION_PERMISSION_GRANTED;
1554 } else {
1555 injectionPermission = INJECTION_PERMISSION_DENIED;
1556 }
1557 }
1558
1559 // Update final pieces of touch state if the injector had permission.
1560 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1561 if (!wrongDevice) {
1562 if (switchedDevice) {
1563#if DEBUG_FOCUS
1564 ALOGD("Conflicting pointer actions: Switched to a different device.");
1565#endif
1566 *outConflictingPointerActions = true;
1567 }
1568
1569 if (isHoverAction) {
1570 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001571 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572#if DEBUG_FOCUS
1573 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1574#endif
1575 *outConflictingPointerActions = true;
1576 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001577 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1579 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001580 mTempTouchState.deviceId = entry->deviceId;
1581 mTempTouchState.source = entry->source;
1582 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 }
1584 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1585 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1586 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001587 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1589 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001590 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591#if DEBUG_FOCUS
1592 ALOGD("Conflicting pointer actions: Down received while already down.");
1593#endif
1594 *outConflictingPointerActions = true;
1595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1597 // One pointer went up.
1598 if (isSplit) {
1599 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1600 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1601
1602 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1603 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1604 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1605 touchedWindow.pointerIds.clearBit(pointerId);
1606 if (touchedWindow.pointerIds.isEmpty()) {
1607 mTempTouchState.windows.removeAt(i);
1608 continue;
1609 }
1610 }
1611 i += 1;
1612 }
1613 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001614 }
1615
1616 // Save changes unless the action was scroll in which case the temporary touch
1617 // state was only valid for this one action.
1618 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1619 if (mTempTouchState.displayId >= 0) {
1620 if (oldStateIndex >= 0) {
1621 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1622 } else {
1623 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1624 }
1625 } else if (oldStateIndex >= 0) {
1626 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001628 }
1629
1630 // Update hover state.
1631 mLastHoverWindowHandle = newHoverWindowHandle;
1632 }
1633 } else {
1634#if DEBUG_FOCUS
1635 ALOGD("Not updating touch focus because injection was denied.");
1636#endif
1637 }
1638
1639Unresponsive:
1640 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1641 mTempTouchState.reset();
1642
1643 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1644 updateDispatchStatisticsLocked(currentTime, entry,
1645 injectionResult, timeSpentWaitingForApplication);
1646#if DEBUG_FOCUS
1647 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1648 "timeSpentWaitingForApplication=%0.1fms",
1649 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1650#endif
1651 return injectionResult;
1652}
1653
1654void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1655 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1656 inputTargets.push();
1657
1658 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1659 InputTarget& target = inputTargets.editTop();
1660 target.inputChannel = windowInfo->inputChannel;
1661 target.flags = targetFlags;
1662 target.xOffset = - windowInfo->frameLeft;
1663 target.yOffset = - windowInfo->frameTop;
1664 target.scaleFactor = windowInfo->scaleFactor;
1665 target.pointerIds = pointerIds;
1666}
1667
1668void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
1669 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1670 inputTargets.push();
1671
1672 InputTarget& target = inputTargets.editTop();
1673 target.inputChannel = mMonitoringChannels[i];
1674 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1675 target.xOffset = 0;
1676 target.yOffset = 0;
1677 target.pointerIds.clear();
1678 target.scaleFactor = 1.0f;
1679 }
1680}
1681
1682bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1683 const InjectionState* injectionState) {
1684 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001685 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1687 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001688 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1690 "owned by uid %d",
1691 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001692 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 windowHandle->getInfo()->ownerUid);
1694 } else {
1695 ALOGW("Permission denied: injecting event from pid %d uid %d",
1696 injectionState->injectorPid, injectionState->injectorUid);
1697 }
1698 return false;
1699 }
1700 return true;
1701}
1702
1703bool InputDispatcher::isWindowObscuredAtPointLocked(
1704 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1705 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001706 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1707 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001709 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710 if (otherHandle == windowHandle) {
1711 break;
1712 }
1713
1714 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1715 if (otherInfo->displayId == displayId
1716 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1717 && otherInfo->frameContainsPoint(x, y)) {
1718 return true;
1719 }
1720 }
1721 return false;
1722}
1723
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001724
1725bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1726 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001727 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001728 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hungb92218b2018-08-14 12:00:21 +08001729 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001730 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001731 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001732 if (otherHandle == windowHandle) {
1733 break;
1734 }
1735
1736 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1737 if (otherInfo->displayId == displayId
1738 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1739 && otherInfo->overlaps(windowInfo)) {
1740 return true;
1741 }
1742 }
1743 return false;
1744}
1745
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001746std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001747 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1748 const char* targetType) {
1749 // If the window is paused then keep waiting.
1750 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001751 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001752 }
1753
1754 // If the window's connection is not registered then keep waiting.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brownffb49772014-10-10 19:01:34 -07001756 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001757 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001758 "registered with the input dispatcher. The window may be in the process "
1759 "of being removed.", targetType);
1760 }
1761
1762 // If the connection is dead then keep waiting.
1763 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1764 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001765 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001766 "The window may be in the process of being removed.", targetType,
1767 connection->getStatusLabel());
1768 }
1769
1770 // If the connection is backed up then keep waiting.
1771 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001772 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001773 "Outbound queue length: %d. Wait queue length: %d.",
1774 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1775 }
1776
1777 // Ensure that the dispatch queues aren't too far backed up for this event.
1778 if (eventEntry->type == EventEntry::TYPE_KEY) {
1779 // If the event is a key event, then we must wait for all previous events to
1780 // complete before delivering it because previous events may have the
1781 // side-effect of transferring focus to a different window and we want to
1782 // ensure that the following keys are sent to the new window.
1783 //
1784 // Suppose the user touches a button in a window then immediately presses "A".
1785 // If the button causes a pop-up window to appear then we want to ensure that
1786 // the "A" key is delivered to the new pop-up window. This is because users
1787 // often anticipate pending UI changes when typing on a keyboard.
1788 // To obtain this behavior, we must serialize key events with respect to all
1789 // prior input events.
1790 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001791 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001792 "finished processing all of the input events that were previously "
1793 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1794 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 }
Jeff Brownffb49772014-10-10 19:01:34 -07001796 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 // Touch events can always be sent to a window immediately because the user intended
1798 // to touch whatever was visible at the time. Even if focus changes or a new
1799 // window appears moments later, the touch event was meant to be delivered to
1800 // whatever window happened to be on screen at the time.
1801 //
1802 // Generic motion events, such as trackball or joystick events are a little trickier.
1803 // Like key events, generic motion events are delivered to the focused window.
1804 // Unlike key events, generic motion events don't tend to transfer focus to other
1805 // windows and it is not important for them to be serialized. So we prefer to deliver
1806 // generic motion events as soon as possible to improve efficiency and reduce lag
1807 // through batching.
1808 //
1809 // The one case where we pause input event delivery is when the wait queue is piling
1810 // up with lots of events because the application is not responding.
1811 // This condition ensures that ANRs are detected reliably.
1812 if (!connection->waitQueue.isEmpty()
1813 && currentTime >= connection->waitQueue.head->deliveryTime
1814 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001815 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001816 "finished processing certain input events that were delivered to it over "
1817 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1818 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1819 connection->waitQueue.count(),
1820 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 }
1822 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001823 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824}
1825
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001826std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 const sp<InputApplicationHandle>& applicationHandle,
1828 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001829 if (applicationHandle != nullptr) {
1830 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001831 std::string label(applicationHandle->getName());
1832 label += " - ";
1833 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 return label;
1835 } else {
1836 return applicationHandle->getName();
1837 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001838 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 return windowHandle->getName();
1840 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001841 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 }
1843}
1844
1845void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001846 int32_t displayId = getTargetDisplayId(eventEntry);
1847 sp<InputWindowHandle> focusedWindowHandle =
1848 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1849 if (focusedWindowHandle != nullptr) {
1850 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1852#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001853 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854#endif
1855 return;
1856 }
1857 }
1858
1859 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1860 switch (eventEntry->type) {
1861 case EventEntry::TYPE_MOTION: {
1862 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1863 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1864 return;
1865 }
1866
1867 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1868 eventType = USER_ACTIVITY_EVENT_TOUCH;
1869 }
1870 break;
1871 }
1872 case EventEntry::TYPE_KEY: {
1873 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1874 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1875 return;
1876 }
1877 eventType = USER_ACTIVITY_EVENT_BUTTON;
1878 break;
1879 }
1880 }
1881
1882 CommandEntry* commandEntry = postCommandLocked(
1883 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1884 commandEntry->eventTime = eventEntry->eventTime;
1885 commandEntry->userActivityEventType = eventType;
1886}
1887
1888void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1889 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1890#if DEBUG_DISPATCH_CYCLE
1891 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1892 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1893 "pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001894 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 inputTarget->xOffset, inputTarget->yOffset,
1896 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1897#endif
1898
1899 // Skip this event if the connection status is not normal.
1900 // We don't want to enqueue additional outbound events if the connection is broken.
1901 if (connection->status != Connection::STATUS_NORMAL) {
1902#if DEBUG_DISPATCH_CYCLE
1903 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001904 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905#endif
1906 return;
1907 }
1908
1909 // Split a motion event if needed.
1910 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1911 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1912
1913 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1914 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1915 MotionEntry* splitMotionEntry = splitMotionEvent(
1916 originalMotionEntry, inputTarget->pointerIds);
1917 if (!splitMotionEntry) {
1918 return; // split event was dropped
1919 }
1920#if DEBUG_FOCUS
1921 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001922 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1924#endif
1925 enqueueDispatchEntriesLocked(currentTime, connection,
1926 splitMotionEntry, inputTarget);
1927 splitMotionEntry->release();
1928 return;
1929 }
1930 }
1931
1932 // Not splitting. Enqueue dispatch entries for the event as is.
1933 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1934}
1935
1936void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1937 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1938 bool wasEmpty = connection->outboundQueue.isEmpty();
1939
1940 // Enqueue dispatch entries for the requested modes.
1941 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1942 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1943 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1944 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1945 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1946 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1947 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1948 InputTarget::FLAG_DISPATCH_AS_IS);
1949 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1950 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1951 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1952 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1953
1954 // If the outbound queue was previously empty, start the dispatch cycle going.
1955 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1956 startDispatchCycleLocked(currentTime, connection);
1957 }
1958}
1959
1960void InputDispatcher::enqueueDispatchEntryLocked(
1961 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1962 int32_t dispatchMode) {
1963 int32_t inputTargetFlags = inputTarget->flags;
1964 if (!(inputTargetFlags & dispatchMode)) {
1965 return;
1966 }
1967 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1968
1969 // This is a new event.
1970 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1971 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1972 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1973 inputTarget->scaleFactor);
1974
1975 // Apply target flags and update the connection's input state.
1976 switch (eventEntry->type) {
1977 case EventEntry::TYPE_KEY: {
1978 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1979 dispatchEntry->resolvedAction = keyEntry->action;
1980 dispatchEntry->resolvedFlags = keyEntry->flags;
1981
1982 if (!connection->inputState.trackKey(keyEntry,
1983 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1984#if DEBUG_DISPATCH_CYCLE
1985 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001986 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987#endif
1988 delete dispatchEntry;
1989 return; // skip the inconsistent event
1990 }
1991 break;
1992 }
1993
1994 case EventEntry::TYPE_MOTION: {
1995 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1996 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1997 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1998 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1999 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2000 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2001 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2002 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2003 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2004 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2005 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2006 } else {
2007 dispatchEntry->resolvedAction = motionEntry->action;
2008 }
2009 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2010 && !connection->inputState.isHovering(
2011 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2012#if DEBUG_DISPATCH_CYCLE
2013 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002014 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015#endif
2016 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2017 }
2018
2019 dispatchEntry->resolvedFlags = motionEntry->flags;
2020 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2021 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2022 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002023 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2024 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2025 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026
2027 if (!connection->inputState.trackMotion(motionEntry,
2028 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2029#if DEBUG_DISPATCH_CYCLE
2030 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002031 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032#endif
2033 delete dispatchEntry;
2034 return; // skip the inconsistent event
2035 }
2036 break;
2037 }
2038 }
2039
2040 // Remember that we are waiting for this dispatch to complete.
2041 if (dispatchEntry->hasForegroundTarget()) {
2042 incrementPendingForegroundDispatchesLocked(eventEntry);
2043 }
2044
2045 // Enqueue the dispatch entry.
2046 connection->outboundQueue.enqueueAtTail(dispatchEntry);
2047 traceOutboundQueueLengthLocked(connection);
2048}
2049
2050void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2051 const sp<Connection>& connection) {
2052#if DEBUG_DISPATCH_CYCLE
2053 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002054 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055#endif
2056
2057 while (connection->status == Connection::STATUS_NORMAL
2058 && !connection->outboundQueue.isEmpty()) {
2059 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2060 dispatchEntry->deliveryTime = currentTime;
2061
2062 // Publish the event.
2063 status_t status;
2064 EventEntry* eventEntry = dispatchEntry->eventEntry;
2065 switch (eventEntry->type) {
2066 case EventEntry::TYPE_KEY: {
2067 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2068
2069 // Publish the key event.
2070 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002071 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2073 keyEntry->keyCode, keyEntry->scanCode,
2074 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2075 keyEntry->eventTime);
2076 break;
2077 }
2078
2079 case EventEntry::TYPE_MOTION: {
2080 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2081
2082 PointerCoords scaledCoords[MAX_POINTERS];
2083 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2084
2085 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002086 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2088 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002089 float scaleFactor = dispatchEntry->scaleFactor;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 xOffset = dispatchEntry->xOffset * scaleFactor;
2091 yOffset = dispatchEntry->yOffset * scaleFactor;
2092 if (scaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002093 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 scaledCoords[i] = motionEntry->pointerCoords[i];
2095 scaledCoords[i].scale(scaleFactor);
2096 }
2097 usingCoords = scaledCoords;
2098 }
2099 } else {
2100 xOffset = 0.0f;
2101 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102
2103 // We don't want the dispatch target to know.
2104 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002105 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 scaledCoords[i].clear();
2107 }
2108 usingCoords = scaledCoords;
2109 }
2110 }
2111
2112 // Publish the motion event.
2113 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002114 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002115 dispatchEntry->resolvedAction, motionEntry->actionButton,
2116 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2117 motionEntry->metaState, motionEntry->buttonState,
2118 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119 motionEntry->downTime, motionEntry->eventTime,
2120 motionEntry->pointerCount, motionEntry->pointerProperties,
2121 usingCoords);
2122 break;
2123 }
2124
2125 default:
2126 ALOG_ASSERT(false);
2127 return;
2128 }
2129
2130 // Check the result.
2131 if (status) {
2132 if (status == WOULD_BLOCK) {
2133 if (connection->waitQueue.isEmpty()) {
2134 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2135 "This is unexpected because the wait queue is empty, so the pipe "
2136 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002137 "event to it, status=%d", connection->getInputChannelName().c_str(),
2138 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2140 } else {
2141 // Pipe is full and we are waiting for the app to finish process some events
2142 // before sending more events to it.
2143#if DEBUG_DISPATCH_CYCLE
2144 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2145 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002146 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147#endif
2148 connection->inputPublisherBlocked = true;
2149 }
2150 } else {
2151 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002152 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2154 }
2155 return;
2156 }
2157
2158 // Re-enqueue the event on the wait queue.
2159 connection->outboundQueue.dequeue(dispatchEntry);
2160 traceOutboundQueueLengthLocked(connection);
2161 connection->waitQueue.enqueueAtTail(dispatchEntry);
2162 traceWaitQueueLengthLocked(connection);
2163 }
2164}
2165
2166void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2167 const sp<Connection>& connection, uint32_t seq, bool handled) {
2168#if DEBUG_DISPATCH_CYCLE
2169 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002170 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171#endif
2172
2173 connection->inputPublisherBlocked = false;
2174
2175 if (connection->status == Connection::STATUS_BROKEN
2176 || connection->status == Connection::STATUS_ZOMBIE) {
2177 return;
2178 }
2179
2180 // Notify other system components and prepare to start the next dispatch cycle.
2181 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2182}
2183
2184void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2185 const sp<Connection>& connection, bool notify) {
2186#if DEBUG_DISPATCH_CYCLE
2187 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002188 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189#endif
2190
2191 // Clear the dispatch queues.
2192 drainDispatchQueueLocked(&connection->outboundQueue);
2193 traceOutboundQueueLengthLocked(connection);
2194 drainDispatchQueueLocked(&connection->waitQueue);
2195 traceWaitQueueLengthLocked(connection);
2196
2197 // The connection appears to be unrecoverably broken.
2198 // Ignore already broken or zombie connections.
2199 if (connection->status == Connection::STATUS_NORMAL) {
2200 connection->status = Connection::STATUS_BROKEN;
2201
2202 if (notify) {
2203 // Notify other system components.
2204 onDispatchCycleBrokenLocked(currentTime, connection);
2205 }
2206 }
2207}
2208
2209void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2210 while (!queue->isEmpty()) {
2211 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2212 releaseDispatchEntryLocked(dispatchEntry);
2213 }
2214}
2215
2216void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2217 if (dispatchEntry->hasForegroundTarget()) {
2218 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2219 }
2220 delete dispatchEntry;
2221}
2222
2223int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2224 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2225
2226 { // acquire lock
2227 AutoMutex _l(d->mLock);
2228
2229 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2230 if (connectionIndex < 0) {
2231 ALOGE("Received spurious receive callback for unknown input channel. "
2232 "fd=%d, events=0x%x", fd, events);
2233 return 0; // remove the callback
2234 }
2235
2236 bool notify;
2237 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2238 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2239 if (!(events & ALOOPER_EVENT_INPUT)) {
2240 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002241 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 return 1;
2243 }
2244
2245 nsecs_t currentTime = now();
2246 bool gotOne = false;
2247 status_t status;
2248 for (;;) {
2249 uint32_t seq;
2250 bool handled;
2251 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2252 if (status) {
2253 break;
2254 }
2255 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2256 gotOne = true;
2257 }
2258 if (gotOne) {
2259 d->runCommandsLockedInterruptible();
2260 if (status == WOULD_BLOCK) {
2261 return 1;
2262 }
2263 }
2264
2265 notify = status != DEAD_OBJECT || !connection->monitor;
2266 if (notify) {
2267 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002268 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 }
2270 } else {
2271 // Monitor channels are never explicitly unregistered.
2272 // We do it automatically when the remote endpoint is closed so don't warn
2273 // about them.
2274 notify = !connection->monitor;
2275 if (notify) {
2276 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002277 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 }
2279 }
2280
2281 // Unregister the channel.
2282 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2283 return 0; // remove the callback
2284 } // release lock
2285}
2286
2287void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2288 const CancelationOptions& options) {
2289 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2290 synthesizeCancelationEventsForConnectionLocked(
2291 mConnectionsByFd.valueAt(i), options);
2292 }
2293}
2294
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002295void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2296 const CancelationOptions& options) {
2297 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2298 synthesizeCancelationEventsForInputChannelLocked(mMonitoringChannels[i], options);
2299 }
2300}
2301
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2303 const sp<InputChannel>& channel, const CancelationOptions& options) {
2304 ssize_t index = getConnectionIndexLocked(channel);
2305 if (index >= 0) {
2306 synthesizeCancelationEventsForConnectionLocked(
2307 mConnectionsByFd.valueAt(index), options);
2308 }
2309}
2310
2311void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2312 const sp<Connection>& connection, const CancelationOptions& options) {
2313 if (connection->status == Connection::STATUS_BROKEN) {
2314 return;
2315 }
2316
2317 nsecs_t currentTime = now();
2318
2319 Vector<EventEntry*> cancelationEvents;
2320 connection->inputState.synthesizeCancelationEvents(currentTime,
2321 cancelationEvents, options);
2322
2323 if (!cancelationEvents.isEmpty()) {
2324#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002325 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002327 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 options.reason, options.mode);
2329#endif
2330 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2331 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2332 switch (cancelationEventEntry->type) {
2333 case EventEntry::TYPE_KEY:
2334 logOutboundKeyDetailsLocked("cancel - ",
2335 static_cast<KeyEntry*>(cancelationEventEntry));
2336 break;
2337 case EventEntry::TYPE_MOTION:
2338 logOutboundMotionDetailsLocked("cancel - ",
2339 static_cast<MotionEntry*>(cancelationEventEntry));
2340 break;
2341 }
2342
2343 InputTarget target;
2344 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07002345 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002346 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2347 target.xOffset = -windowInfo->frameLeft;
2348 target.yOffset = -windowInfo->frameTop;
2349 target.scaleFactor = windowInfo->scaleFactor;
2350 } else {
2351 target.xOffset = 0;
2352 target.yOffset = 0;
2353 target.scaleFactor = 1.0f;
2354 }
2355 target.inputChannel = connection->inputChannel;
2356 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2357
2358 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2359 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2360
2361 cancelationEventEntry->release();
2362 }
2363
2364 startDispatchCycleLocked(currentTime, connection);
2365 }
2366}
2367
2368InputDispatcher::MotionEntry*
2369InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2370 ALOG_ASSERT(pointerIds.value != 0);
2371
2372 uint32_t splitPointerIndexMap[MAX_POINTERS];
2373 PointerProperties splitPointerProperties[MAX_POINTERS];
2374 PointerCoords splitPointerCoords[MAX_POINTERS];
2375
2376 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2377 uint32_t splitPointerCount = 0;
2378
2379 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2380 originalPointerIndex++) {
2381 const PointerProperties& pointerProperties =
2382 originalMotionEntry->pointerProperties[originalPointerIndex];
2383 uint32_t pointerId = uint32_t(pointerProperties.id);
2384 if (pointerIds.hasBit(pointerId)) {
2385 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2386 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2387 splitPointerCoords[splitPointerCount].copyFrom(
2388 originalMotionEntry->pointerCoords[originalPointerIndex]);
2389 splitPointerCount += 1;
2390 }
2391 }
2392
2393 if (splitPointerCount != pointerIds.count()) {
2394 // This is bad. We are missing some of the pointers that we expected to deliver.
2395 // Most likely this indicates that we received an ACTION_MOVE events that has
2396 // different pointer ids than we expected based on the previous ACTION_DOWN
2397 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2398 // in this way.
2399 ALOGW("Dropping split motion event because the pointer count is %d but "
2400 "we expected there to be %d pointers. This probably means we received "
2401 "a broken sequence of pointer ids from the input device.",
2402 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002403 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 }
2405
2406 int32_t action = originalMotionEntry->action;
2407 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2408 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2409 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2410 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2411 const PointerProperties& pointerProperties =
2412 originalMotionEntry->pointerProperties[originalPointerIndex];
2413 uint32_t pointerId = uint32_t(pointerProperties.id);
2414 if (pointerIds.hasBit(pointerId)) {
2415 if (pointerIds.count() == 1) {
2416 // The first/last pointer went down/up.
2417 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2418 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2419 } else {
2420 // A secondary pointer went down/up.
2421 uint32_t splitPointerIndex = 0;
2422 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2423 splitPointerIndex += 1;
2424 }
2425 action = maskedAction | (splitPointerIndex
2426 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2427 }
2428 } else {
2429 // An unrelated pointer changed.
2430 action = AMOTION_EVENT_ACTION_MOVE;
2431 }
2432 }
2433
2434 MotionEntry* splitMotionEntry = new MotionEntry(
2435 originalMotionEntry->eventTime,
2436 originalMotionEntry->deviceId,
2437 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002438 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 originalMotionEntry->policyFlags,
2440 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002441 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 originalMotionEntry->flags,
2443 originalMotionEntry->metaState,
2444 originalMotionEntry->buttonState,
2445 originalMotionEntry->edgeFlags,
2446 originalMotionEntry->xPrecision,
2447 originalMotionEntry->yPrecision,
2448 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002449 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450
2451 if (originalMotionEntry->injectionState) {
2452 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2453 splitMotionEntry->injectionState->refCount += 1;
2454 }
2455
2456 return splitMotionEntry;
2457}
2458
2459void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2460#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002461 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462#endif
2463
2464 bool needWake;
2465 { // acquire lock
2466 AutoMutex _l(mLock);
2467
2468 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2469 needWake = enqueueInboundEventLocked(newEntry);
2470 } // release lock
2471
2472 if (needWake) {
2473 mLooper->wake();
2474 }
2475}
2476
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002477/**
2478 * If one of the meta shortcuts is detected, process them here:
2479 * Meta + Backspace -> generate BACK
2480 * Meta + Enter -> generate HOME
2481 * This will potentially overwrite keyCode and metaState.
2482 */
2483void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2484 int32_t& keyCode, int32_t& metaState) {
2485 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2486 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2487 if (keyCode == AKEYCODE_DEL) {
2488 newKeyCode = AKEYCODE_BACK;
2489 } else if (keyCode == AKEYCODE_ENTER) {
2490 newKeyCode = AKEYCODE_HOME;
2491 }
2492 if (newKeyCode != AKEYCODE_UNKNOWN) {
2493 AutoMutex _l(mLock);
2494 struct KeyReplacement replacement = {keyCode, deviceId};
2495 mReplacedKeys.add(replacement, newKeyCode);
2496 keyCode = newKeyCode;
2497 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2498 }
2499 } else if (action == AKEY_EVENT_ACTION_UP) {
2500 // In order to maintain a consistent stream of up and down events, check to see if the key
2501 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2502 // even if the modifier was released between the down and the up events.
2503 AutoMutex _l(mLock);
2504 struct KeyReplacement replacement = {keyCode, deviceId};
2505 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2506 if (index >= 0) {
2507 keyCode = mReplacedKeys.valueAt(index);
2508 mReplacedKeys.removeItemsAt(index);
2509 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2510 }
2511 }
2512}
2513
Michael Wrightd02c5b62014-02-10 15:10:22 -08002514void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2515#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002516 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002517 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002518 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002519 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520 args->action, args->flags, args->keyCode, args->scanCode,
2521 args->metaState, args->downTime);
2522#endif
2523 if (!validateKeyEvent(args->action)) {
2524 return;
2525 }
2526
2527 uint32_t policyFlags = args->policyFlags;
2528 int32_t flags = args->flags;
2529 int32_t metaState = args->metaState;
2530 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2531 policyFlags |= POLICY_FLAG_VIRTUAL;
2532 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 if (policyFlags & POLICY_FLAG_FUNCTION) {
2535 metaState |= AMETA_FUNCTION_ON;
2536 }
2537
2538 policyFlags |= POLICY_FLAG_TRUSTED;
2539
Michael Wright78f24442014-08-06 15:55:28 -07002540 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002541 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002542
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002544 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Michael Wright78f24442014-08-06 15:55:28 -07002545 flags, keyCode, args->scanCode, metaState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 args->downTime, args->eventTime);
2547
Michael Wright2b3c3302018-03-02 17:19:13 +00002548 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002550 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2551 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2552 std::to_string(t.duration().count()).c_str());
2553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555 bool needWake;
2556 { // acquire lock
2557 mLock.lock();
2558
2559 if (shouldSendKeyToInputFilterLocked(args)) {
2560 mLock.unlock();
2561
2562 policyFlags |= POLICY_FLAG_FILTERED;
2563 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2564 return; // event was consumed by the filter
2565 }
2566
2567 mLock.lock();
2568 }
2569
2570 int32_t repeatCount = 0;
2571 KeyEntry* newEntry = new KeyEntry(args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002572 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002573 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574 metaState, repeatCount, args->downTime);
2575
2576 needWake = enqueueInboundEventLocked(newEntry);
2577 mLock.unlock();
2578 } // release lock
2579
2580 if (needWake) {
2581 mLooper->wake();
2582 }
2583}
2584
2585bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2586 return mInputFilterEnabled;
2587}
2588
2589void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2590#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002591 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2592 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002593 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002594 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002595 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002596 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2598 for (uint32_t i = 0; i < args->pointerCount; i++) {
2599 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2600 "x=%f, y=%f, pressure=%f, size=%f, "
2601 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2602 "orientation=%f",
2603 i, args->pointerProperties[i].id,
2604 args->pointerProperties[i].toolType,
2605 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2606 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2607 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2608 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2609 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2610 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2611 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2612 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2613 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2614 }
2615#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002616 if (!validateMotionEvent(args->action, args->actionButton,
2617 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 return;
2619 }
2620
2621 uint32_t policyFlags = args->policyFlags;
2622 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002623
2624 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002626 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2627 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2628 std::to_string(t.duration().count()).c_str());
2629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002630
2631 bool needWake;
2632 { // acquire lock
2633 mLock.lock();
2634
2635 if (shouldSendMotionToInputFilterLocked(args)) {
2636 mLock.unlock();
2637
2638 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002639 event.initialize(args->deviceId, args->source, args->displayId,
2640 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002641 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2642 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 args->downTime, args->eventTime,
2644 args->pointerCount, args->pointerProperties, args->pointerCoords);
2645
2646 policyFlags |= POLICY_FLAG_FILTERED;
2647 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2648 return; // event was consumed by the filter
2649 }
2650
2651 mLock.lock();
2652 }
2653
2654 // Just enqueue a new motion event.
2655 MotionEntry* newEntry = new MotionEntry(args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002656 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002657 args->action, args->actionButton, args->flags,
2658 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002660 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661
2662 needWake = enqueueInboundEventLocked(newEntry);
2663 mLock.unlock();
2664 } // release lock
2665
2666 if (needWake) {
2667 mLooper->wake();
2668 }
2669}
2670
2671bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2672 // TODO: support sending secondary display events to input filter
2673 return mInputFilterEnabled && isMainDisplay(args->displayId);
2674}
2675
2676void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2677#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002678 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2679 "switchMask=0x%08x",
2680 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681#endif
2682
2683 uint32_t policyFlags = args->policyFlags;
2684 policyFlags |= POLICY_FLAG_TRUSTED;
2685 mPolicy->notifySwitch(args->eventTime,
2686 args->switchValues, args->switchMask, policyFlags);
2687}
2688
2689void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2690#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002691 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 args->eventTime, args->deviceId);
2693#endif
2694
2695 bool needWake;
2696 { // acquire lock
2697 AutoMutex _l(mLock);
2698
2699 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2700 needWake = enqueueInboundEventLocked(newEntry);
2701 } // release lock
2702
2703 if (needWake) {
2704 mLooper->wake();
2705 }
2706}
2707
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002708int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2710 uint32_t policyFlags) {
2711#if DEBUG_INBOUND_EVENT_DETAILS
2712 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002713 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2714 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715#endif
2716
2717 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2718
2719 policyFlags |= POLICY_FLAG_INJECTED;
2720 if (hasInjectionPermission(injectorPid, injectorUid)) {
2721 policyFlags |= POLICY_FLAG_TRUSTED;
2722 }
2723
2724 EventEntry* firstInjectedEntry;
2725 EventEntry* lastInjectedEntry;
2726 switch (event->getType()) {
2727 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002728 KeyEvent keyEvent;
2729 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2730 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731 if (! validateKeyEvent(action)) {
2732 return INPUT_EVENT_INJECTION_FAILED;
2733 }
2734
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002735 int32_t flags = keyEvent.getFlags();
2736 int32_t keyCode = keyEvent.getKeyCode();
2737 int32_t metaState = keyEvent.getMetaState();
2738 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2739 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002740 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
2741 action, flags, keyCode, keyEvent.getScanCode(), metaState, 0,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002742 keyEvent.getDownTime(), keyEvent.getEventTime());
2743
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2745 policyFlags |= POLICY_FLAG_VIRTUAL;
2746 }
2747
2748 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002749 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002750 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002751 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2752 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2753 std::to_string(t.duration().count()).c_str());
2754 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755 }
2756
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 mLock.lock();
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002758 firstInjectedEntry = new KeyEntry(keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002759 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002761 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2762 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763 lastInjectedEntry = firstInjectedEntry;
2764 break;
2765 }
2766
2767 case AINPUT_EVENT_TYPE_MOTION: {
2768 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 int32_t action = motionEvent->getAction();
2770 size_t pointerCount = motionEvent->getPointerCount();
2771 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002772 int32_t actionButton = motionEvent->getActionButton();
2773 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 return INPUT_EVENT_INJECTION_FAILED;
2775 }
2776
2777 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2778 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002779 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002781 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2782 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2783 std::to_string(t.duration().count()).c_str());
2784 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 }
2786
2787 mLock.lock();
2788 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2789 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2790 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002791 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2792 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002793 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002794 motionEvent->getMetaState(), motionEvent->getButtonState(),
2795 motionEvent->getEdgeFlags(),
2796 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002797 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002798 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2799 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800 lastInjectedEntry = firstInjectedEntry;
2801 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2802 sampleEventTimes += 1;
2803 samplePointerCoords += pointerCount;
2804 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002805 motionEvent->getDeviceId(), motionEvent->getSource(),
2806 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002807 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 motionEvent->getMetaState(), motionEvent->getButtonState(),
2809 motionEvent->getEdgeFlags(),
2810 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002811 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002812 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2813 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814 lastInjectedEntry->next = nextInjectedEntry;
2815 lastInjectedEntry = nextInjectedEntry;
2816 }
2817 break;
2818 }
2819
2820 default:
2821 ALOGW("Cannot inject event of type %d", event->getType());
2822 return INPUT_EVENT_INJECTION_FAILED;
2823 }
2824
2825 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2826 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2827 injectionState->injectionIsAsync = true;
2828 }
2829
2830 injectionState->refCount += 1;
2831 lastInjectedEntry->injectionState = injectionState;
2832
2833 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002834 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835 EventEntry* nextEntry = entry->next;
2836 needWake |= enqueueInboundEventLocked(entry);
2837 entry = nextEntry;
2838 }
2839
2840 mLock.unlock();
2841
2842 if (needWake) {
2843 mLooper->wake();
2844 }
2845
2846 int32_t injectionResult;
2847 { // acquire lock
2848 AutoMutex _l(mLock);
2849
2850 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2851 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2852 } else {
2853 for (;;) {
2854 injectionResult = injectionState->injectionResult;
2855 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2856 break;
2857 }
2858
2859 nsecs_t remainingTimeout = endTime - now();
2860 if (remainingTimeout <= 0) {
2861#if DEBUG_INJECTION
2862 ALOGD("injectInputEvent - Timed out waiting for injection result "
2863 "to become available.");
2864#endif
2865 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2866 break;
2867 }
2868
2869 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2870 }
2871
2872 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2873 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2874 while (injectionState->pendingForegroundDispatches != 0) {
2875#if DEBUG_INJECTION
2876 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2877 injectionState->pendingForegroundDispatches);
2878#endif
2879 nsecs_t remainingTimeout = endTime - now();
2880 if (remainingTimeout <= 0) {
2881#if DEBUG_INJECTION
2882 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2883 "dispatches to finish.");
2884#endif
2885 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2886 break;
2887 }
2888
2889 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2890 }
2891 }
2892 }
2893
2894 injectionState->release();
2895 } // release lock
2896
2897#if DEBUG_INJECTION
2898 ALOGD("injectInputEvent - Finished with result %d. "
2899 "injectorPid=%d, injectorUid=%d",
2900 injectionResult, injectorPid, injectorUid);
2901#endif
2902
2903 return injectionResult;
2904}
2905
2906bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2907 return injectorUid == 0
2908 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2909}
2910
2911void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2912 InjectionState* injectionState = entry->injectionState;
2913 if (injectionState) {
2914#if DEBUG_INJECTION
2915 ALOGD("Setting input event injection result to %d. "
2916 "injectorPid=%d, injectorUid=%d",
2917 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2918#endif
2919
2920 if (injectionState->injectionIsAsync
2921 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2922 // Log the outcome since the injector did not wait for the injection result.
2923 switch (injectionResult) {
2924 case INPUT_EVENT_INJECTION_SUCCEEDED:
2925 ALOGV("Asynchronous input event injection succeeded.");
2926 break;
2927 case INPUT_EVENT_INJECTION_FAILED:
2928 ALOGW("Asynchronous input event injection failed.");
2929 break;
2930 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2931 ALOGW("Asynchronous input event injection permission denied.");
2932 break;
2933 case INPUT_EVENT_INJECTION_TIMED_OUT:
2934 ALOGW("Asynchronous input event injection timed out.");
2935 break;
2936 }
2937 }
2938
2939 injectionState->injectionResult = injectionResult;
2940 mInjectionResultAvailableCondition.broadcast();
2941 }
2942}
2943
2944void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2945 InjectionState* injectionState = entry->injectionState;
2946 if (injectionState) {
2947 injectionState->pendingForegroundDispatches += 1;
2948 }
2949}
2950
2951void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2952 InjectionState* injectionState = entry->injectionState;
2953 if (injectionState) {
2954 injectionState->pendingForegroundDispatches -= 1;
2955
2956 if (injectionState->pendingForegroundDispatches == 0) {
2957 mInjectionSyncFinishedCondition.broadcast();
2958 }
2959 }
2960}
2961
Arthur Hungb92218b2018-08-14 12:00:21 +08002962Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
2963 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
2964 mWindowHandlesByDisplay.find(displayId);
2965 if(it != mWindowHandlesByDisplay.end()) {
2966 return it->second;
2967 }
2968
2969 // Return an empty one if nothing found.
2970 return Vector<sp<InputWindowHandle>>();
2971}
2972
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2974 const sp<InputChannel>& inputChannel) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08002975 for (auto& it : mWindowHandlesByDisplay) {
2976 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
2977 size_t numWindows = windowHandles.size();
2978 for (size_t i = 0; i < numWindows; i++) {
2979 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
2980 if (windowHandle->getInputChannel() == inputChannel) {
2981 return windowHandle;
2982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002983 }
2984 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002985 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002986}
2987
2988bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00002989 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08002990 for (auto& it : mWindowHandlesByDisplay) {
2991 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
2992 size_t numWindows = windowHandles.size();
2993 for (size_t i = 0; i < numWindows; i++) {
2994 if (windowHandles.itemAt(i) == windowHandle) {
2995 if (windowHandle->getInfo()->displayId != it.first) {
2996 ALOGE("Found window %s in display %d, but it should belong to display %d",
2997 windowHandle->getName().c_str(), it.first,
2998 windowHandle->getInfo()->displayId);
2999 }
3000 return true;
3001 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002 }
3003 }
3004 return false;
3005}
3006
Arthur Hungb92218b2018-08-14 12:00:21 +08003007/**
3008 * Called from InputManagerService, update window handle list by displayId that can receive input.
3009 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3010 * If set an empty list, remove all handles from the specific display.
3011 * For focused handle, check if need to change and send a cancel event to previous one.
3012 * For removed handle, check if need to send a cancel event if already in touch.
3013 */
3014void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3015 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016#if DEBUG_FOCUS
3017 ALOGD("setInputWindows");
3018#endif
3019 { // acquire lock
3020 AutoMutex _l(mLock);
3021
Arthur Hungb92218b2018-08-14 12:00:21 +08003022 // Copy old handles for release if they are no longer present.
3023 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024
Tiger Huang721e26f2018-07-24 22:26:19 +08003025 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003027
3028 if (inputWindowHandles.isEmpty()) {
3029 // Remove all handles on a display if there are no windows left.
3030 mWindowHandlesByDisplay.erase(displayId);
3031 } else {
3032 size_t numWindows = inputWindowHandles.size();
3033 for (size_t i = 0; i < numWindows; i++) {
3034 const sp<InputWindowHandle>& windowHandle = inputWindowHandles.itemAt(i);
3035 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == nullptr) {
3036 continue;
3037 }
3038
3039 if (windowHandle->getInfo()->displayId != displayId) {
3040 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3041 windowHandle->getName().c_str(), displayId,
3042 windowHandle->getInfo()->displayId);
3043 continue;
3044 }
3045
3046 if (windowHandle->getInfo()->hasFocus) {
3047 newFocusedWindowHandle = windowHandle;
3048 }
3049 if (windowHandle == mLastHoverWindowHandle) {
3050 foundHoveredWindow = true;
3051 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003052 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003053
3054 // Insert or replace
3055 mWindowHandlesByDisplay[displayId] = inputWindowHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 }
3057
3058 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003059 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003060 }
3061
Tiger Huang721e26f2018-07-24 22:26:19 +08003062 sp<InputWindowHandle> oldFocusedWindowHandle =
3063 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3064
3065 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3066 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067#if DEBUG_FOCUS
3068 ALOGD("Focus left window: %s",
Tiger Huang721e26f2018-07-24 22:26:19 +08003069 oldFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003071 sp<InputChannel> focusedInputChannel = oldFocusedWindowHandle->getInputChannel();
Yi Kong9b14ac62018-07-17 13:48:38 -07003072 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3074 "focus left window");
3075 synthesizeCancelationEventsForInputChannelLocked(
3076 focusedInputChannel, options);
3077 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003078 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003080 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081#if DEBUG_FOCUS
3082 ALOGD("Focus entered window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003083 newFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003085 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087 }
3088
Arthur Hungb92218b2018-08-14 12:00:21 +08003089 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3090 if (stateIndex >= 0) {
3091 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003092 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003093 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003094 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095#if DEBUG_FOCUS
Jeff Brownf086ddb2014-02-11 14:28:48 -08003096 ALOGD("Touched window was removed: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003097 touchedWindow.windowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003099 sp<InputChannel> touchedInputChannel =
3100 touchedWindow.windowHandle->getInputChannel();
Yi Kong9b14ac62018-07-17 13:48:38 -07003101 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003102 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3103 "touched window was removed");
3104 synthesizeCancelationEventsForInputChannelLocked(
3105 touchedInputChannel, options);
3106 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003107 state.windows.removeAt(i);
3108 } else {
3109 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111 }
3112 }
3113
3114 // Release information for windows that are no longer present.
3115 // This ensures that unused input channels are released promptly.
3116 // Otherwise, they might stick around until the window handle is destroyed
3117 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003118 size_t numWindows = oldWindowHandles.size();
3119 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003121 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003123 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124#endif
3125 oldWindowHandle->releaseInfo();
3126 }
3127 }
3128 } // release lock
3129
3130 // Wake up poll loop since it may need to make new input dispatching choices.
3131 mLooper->wake();
3132}
3133
3134void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003135 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136#if DEBUG_FOCUS
3137 ALOGD("setFocusedApplication");
3138#endif
3139 { // acquire lock
3140 AutoMutex _l(mLock);
3141
Tiger Huang721e26f2018-07-24 22:26:19 +08003142 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3143 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003144 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003145 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3146 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003148 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003150 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003152 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003154 oldFocusedApplicationHandle->releaseInfo();
3155 oldFocusedApplicationHandle.clear();
3156 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
3158
3159#if DEBUG_FOCUS
3160 //logDispatchStateLocked();
3161#endif
3162 } // release lock
3163
3164 // Wake up poll loop since it may need to make new input dispatching choices.
3165 mLooper->wake();
3166}
3167
Tiger Huang721e26f2018-07-24 22:26:19 +08003168/**
3169 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3170 * the display not specified.
3171 *
3172 * We track any unreleased events for each window. If a window loses the ability to receive the
3173 * released event, we will send a cancel event to it. So when the focused display is changed, we
3174 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3175 * display. The display-specified events won't be affected.
3176 */
3177void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3178#if DEBUG_FOCUS
3179 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3180#endif
3181 { // acquire lock
3182 AutoMutex _l(mLock);
3183
3184 if (mFocusedDisplayId != displayId) {
3185 sp<InputWindowHandle> oldFocusedWindowHandle =
3186 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3187 if (oldFocusedWindowHandle != nullptr) {
3188 sp<InputChannel> inputChannel = oldFocusedWindowHandle->getInputChannel();
3189 if (inputChannel != nullptr) {
3190 CancelationOptions options(
3191 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3192 "The display which contains this window no longer has focus.");
3193 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3194 }
3195 }
3196 mFocusedDisplayId = displayId;
3197
3198 // Sanity check
3199 sp<InputWindowHandle> newFocusedWindowHandle =
3200 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3201 if (newFocusedWindowHandle == nullptr) {
3202 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3203 if (!mFocusedWindowHandlesByDisplay.empty()) {
3204 ALOGE("But another display has a focused window:");
3205 for (auto& it : mFocusedWindowHandlesByDisplay) {
3206 const int32_t displayId = it.first;
3207 const sp<InputWindowHandle>& windowHandle = it.second;
3208 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3209 displayId, windowHandle->getName().c_str());
3210 }
3211 }
3212 }
3213 }
3214
3215#if DEBUG_FOCUS
3216 logDispatchStateLocked();
3217#endif
3218 } // release lock
3219
3220 // Wake up poll loop since it may need to make new input dispatching choices.
3221 mLooper->wake();
3222}
3223
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3225#if DEBUG_FOCUS
3226 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3227#endif
3228
3229 bool changed;
3230 { // acquire lock
3231 AutoMutex _l(mLock);
3232
3233 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3234 if (mDispatchFrozen && !frozen) {
3235 resetANRTimeoutsLocked();
3236 }
3237
3238 if (mDispatchEnabled && !enabled) {
3239 resetAndDropEverythingLocked("dispatcher is being disabled");
3240 }
3241
3242 mDispatchEnabled = enabled;
3243 mDispatchFrozen = frozen;
3244 changed = true;
3245 } else {
3246 changed = false;
3247 }
3248
3249#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003250 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251#endif
3252 } // release lock
3253
3254 if (changed) {
3255 // Wake up poll loop since it may need to make new input dispatching choices.
3256 mLooper->wake();
3257 }
3258}
3259
3260void InputDispatcher::setInputFilterEnabled(bool enabled) {
3261#if DEBUG_FOCUS
3262 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3263#endif
3264
3265 { // acquire lock
3266 AutoMutex _l(mLock);
3267
3268 if (mInputFilterEnabled == enabled) {
3269 return;
3270 }
3271
3272 mInputFilterEnabled = enabled;
3273 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3274 } // release lock
3275
3276 // Wake up poll loop since there might be work to do to drop everything.
3277 mLooper->wake();
3278}
3279
3280bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3281 const sp<InputChannel>& toChannel) {
3282#if DEBUG_FOCUS
3283 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003284 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285#endif
3286 { // acquire lock
3287 AutoMutex _l(mLock);
3288
3289 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3290 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07003291 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292#if DEBUG_FOCUS
3293 ALOGD("Cannot transfer focus because from or to window not found.");
3294#endif
3295 return false;
3296 }
3297 if (fromWindowHandle == toWindowHandle) {
3298#if DEBUG_FOCUS
3299 ALOGD("Trivial transfer to same window.");
3300#endif
3301 return true;
3302 }
3303 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3304#if DEBUG_FOCUS
3305 ALOGD("Cannot transfer focus because windows are on different displays.");
3306#endif
3307 return false;
3308 }
3309
3310 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003311 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3312 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3313 for (size_t i = 0; i < state.windows.size(); i++) {
3314 const TouchedWindow& touchedWindow = state.windows[i];
3315 if (touchedWindow.windowHandle == fromWindowHandle) {
3316 int32_t oldTargetFlags = touchedWindow.targetFlags;
3317 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318
Jeff Brownf086ddb2014-02-11 14:28:48 -08003319 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320
Jeff Brownf086ddb2014-02-11 14:28:48 -08003321 int32_t newTargetFlags = oldTargetFlags
3322 & (InputTarget::FLAG_FOREGROUND
3323 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3324 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325
Jeff Brownf086ddb2014-02-11 14:28:48 -08003326 found = true;
3327 goto Found;
3328 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329 }
3330 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003331Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332
3333 if (! found) {
3334#if DEBUG_FOCUS
3335 ALOGD("Focus transfer failed because from window did not have focus.");
3336#endif
3337 return false;
3338 }
3339
3340 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3341 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3342 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3343 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3344 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3345
3346 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3347 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3348 "transferring touch focus from this window to another window");
3349 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3350 }
3351
3352#if DEBUG_FOCUS
3353 logDispatchStateLocked();
3354#endif
3355 } // release lock
3356
3357 // Wake up poll loop since it may need to make new input dispatching choices.
3358 mLooper->wake();
3359 return true;
3360}
3361
3362void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3363#if DEBUG_FOCUS
3364 ALOGD("Resetting and dropping all events (%s).", reason);
3365#endif
3366
3367 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3368 synthesizeCancelationEventsForAllConnectionsLocked(options);
3369
3370 resetKeyRepeatLocked();
3371 releasePendingEventLocked();
3372 drainInboundQueueLocked();
3373 resetANRTimeoutsLocked();
3374
Jeff Brownf086ddb2014-02-11 14:28:48 -08003375 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003377 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378}
3379
3380void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003381 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 dumpDispatchStateLocked(dump);
3383
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003384 std::istringstream stream(dump);
3385 std::string line;
3386
3387 while (std::getline(stream, line, '\n')) {
3388 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 }
3390}
3391
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003392void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3393 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3394 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003395 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396
Tiger Huang721e26f2018-07-24 22:26:19 +08003397 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3398 dump += StringPrintf(INDENT "FocusedApplications:\n");
3399 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3400 const int32_t displayId = it.first;
3401 const sp<InputApplicationHandle>& applicationHandle = it.second;
3402 dump += StringPrintf(
3403 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3404 displayId,
3405 applicationHandle->getName().c_str(),
3406 applicationHandle->getDispatchingTimeout(
3407 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003410 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003412
3413 if (!mFocusedWindowHandlesByDisplay.empty()) {
3414 dump += StringPrintf(INDENT "FocusedWindows:\n");
3415 for (auto& it : mFocusedWindowHandlesByDisplay) {
3416 const int32_t displayId = it.first;
3417 const sp<InputWindowHandle>& windowHandle = it.second;
3418 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3419 displayId, windowHandle->getName().c_str());
3420 }
3421 } else {
3422 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3423 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424
Jeff Brownf086ddb2014-02-11 14:28:48 -08003425 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003426 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003427 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3428 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003429 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003430 state.displayId, toString(state.down), toString(state.split),
3431 state.deviceId, state.source);
3432 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003433 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003434 for (size_t i = 0; i < state.windows.size(); i++) {
3435 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003436 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3437 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003438 touchedWindow.pointerIds.value,
3439 touchedWindow.targetFlags);
3440 }
3441 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003442 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444 }
3445 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003446 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447 }
3448
Arthur Hungb92218b2018-08-14 12:00:21 +08003449 if (!mWindowHandlesByDisplay.empty()) {
3450 for (auto& it : mWindowHandlesByDisplay) {
3451 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3452 dump += StringPrintf(INDENT "Display: %d\n", it.first);
3453 if (!windowHandles.isEmpty()) {
3454 dump += INDENT2 "Windows:\n";
3455 for (size_t i = 0; i < windowHandles.size(); i++) {
3456 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3457 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458
Arthur Hungb92218b2018-08-14 12:00:21 +08003459 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3460 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3461 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3462 "frame=[%d,%d][%d,%d], scale=%f, "
3463 "touchableRegion=",
3464 i, windowInfo->name.c_str(), windowInfo->displayId,
3465 toString(windowInfo->paused),
3466 toString(windowInfo->hasFocus),
3467 toString(windowInfo->hasWallpaper),
3468 toString(windowInfo->visible),
3469 toString(windowInfo->canReceiveKeys),
3470 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3471 windowInfo->layer,
3472 windowInfo->frameLeft, windowInfo->frameTop,
3473 windowInfo->frameRight, windowInfo->frameBottom,
3474 windowInfo->scaleFactor);
3475 dumpRegion(dump, windowInfo->touchableRegion);
3476 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3477 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3478 windowInfo->ownerPid, windowInfo->ownerUid,
3479 windowInfo->dispatchingTimeout / 1000000.0);
3480 }
3481 } else {
3482 dump += INDENT2 "Windows: <none>\n";
3483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484 }
3485 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003486 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487 }
3488
3489 if (!mMonitoringChannels.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003490 dump += INDENT "MonitoringChannels:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3492 const sp<InputChannel>& channel = mMonitoringChannels[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003493 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494 }
3495 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003496 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497 }
3498
3499 nsecs_t currentTime = now();
3500
3501 // Dump recently dispatched or dropped events from oldest to newest.
3502 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003503 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003505 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003507 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 (currentTime - entry->eventTime) * 0.000001f);
3509 }
3510 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003511 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
3513
3514 // Dump event currently being dispatched.
3515 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003516 dump += INDENT "PendingEvent:\n";
3517 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003519 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3521 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003522 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523 }
3524
3525 // Dump inbound events from oldest to newest.
3526 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003527 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003529 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003531 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 (currentTime - entry->eventTime) * 0.000001f);
3533 }
3534 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003535 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 }
3537
Michael Wright78f24442014-08-06 15:55:28 -07003538 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003539 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003540 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3541 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3542 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003543 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003544 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3545 }
3546 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003547 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003548 }
3549
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003551 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3553 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003554 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003556 i, connection->getInputChannelName().c_str(),
3557 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 connection->getStatusLabel(), toString(connection->monitor),
3559 toString(connection->inputPublisherBlocked));
3560
3561 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003562 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563 connection->outboundQueue.count());
3564 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3565 entry = entry->next) {
3566 dump.append(INDENT4);
3567 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003568 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569 entry->targetFlags, entry->resolvedAction,
3570 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3571 }
3572 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003573 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 }
3575
3576 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003577 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578 connection->waitQueue.count());
3579 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3580 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003581 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003583 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 "age=%0.1fms, wait=%0.1fms\n",
3585 entry->targetFlags, entry->resolvedAction,
3586 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3587 (currentTime - entry->deliveryTime) * 0.000001f);
3588 }
3589 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003590 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003591 }
3592 }
3593 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003594 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 }
3596
3597 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003598 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 (mAppSwitchDueTime - now()) / 1000000.0);
3600 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003601 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 }
3603
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003604 dump += INDENT "Configuration:\n";
3605 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003607 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 mConfig.keyRepeatTimeout * 0.000001f);
3609}
3610
3611status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3612 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
3613#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003614 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 toString(monitor));
3616#endif
3617
3618 { // acquire lock
3619 AutoMutex _l(mLock);
3620
3621 if (getConnectionIndexLocked(inputChannel) >= 0) {
3622 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003623 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 return BAD_VALUE;
3625 }
3626
3627 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3628
3629 int fd = inputChannel->getFd();
3630 mConnectionsByFd.add(fd, connection);
3631
3632 if (monitor) {
3633 mMonitoringChannels.push(inputChannel);
3634 }
3635
3636 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3637 } // release lock
3638
3639 // Wake the looper because some connections have changed.
3640 mLooper->wake();
3641 return OK;
3642}
3643
3644status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3645#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003646 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647#endif
3648
3649 { // acquire lock
3650 AutoMutex _l(mLock);
3651
3652 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3653 if (status) {
3654 return status;
3655 }
3656 } // release lock
3657
3658 // Wake the poll loop because removing the connection may have changed the current
3659 // synchronization state.
3660 mLooper->wake();
3661 return OK;
3662}
3663
3664status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3665 bool notify) {
3666 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3667 if (connectionIndex < 0) {
3668 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003669 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 return BAD_VALUE;
3671 }
3672
3673 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3674 mConnectionsByFd.removeItemsAt(connectionIndex);
3675
3676 if (connection->monitor) {
3677 removeMonitorChannelLocked(inputChannel);
3678 }
3679
3680 mLooper->removeFd(inputChannel->getFd());
3681
3682 nsecs_t currentTime = now();
3683 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3684
3685 connection->status = Connection::STATUS_ZOMBIE;
3686 return OK;
3687}
3688
3689void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3690 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3691 if (mMonitoringChannels[i] == inputChannel) {
3692 mMonitoringChannels.removeAt(i);
3693 break;
3694 }
3695 }
3696}
3697
3698ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
3699 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3700 if (connectionIndex >= 0) {
3701 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3702 if (connection->inputChannel.get() == inputChannel.get()) {
3703 return connectionIndex;
3704 }
3705 }
3706
3707 return -1;
3708}
3709
3710void InputDispatcher::onDispatchCycleFinishedLocked(
3711 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3712 CommandEntry* commandEntry = postCommandLocked(
3713 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3714 commandEntry->connection = connection;
3715 commandEntry->eventTime = currentTime;
3716 commandEntry->seq = seq;
3717 commandEntry->handled = handled;
3718}
3719
3720void InputDispatcher::onDispatchCycleBrokenLocked(
3721 nsecs_t currentTime, const sp<Connection>& connection) {
3722 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003723 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724
3725 CommandEntry* commandEntry = postCommandLocked(
3726 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3727 commandEntry->connection = connection;
3728}
3729
3730void InputDispatcher::onANRLocked(
3731 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3732 const sp<InputWindowHandle>& windowHandle,
3733 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3734 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3735 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3736 ALOGI("Application is not responding: %s. "
3737 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003738 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 dispatchLatency, waitDuration, reason);
3740
3741 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003742 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 struct tm tm;
3744 localtime_r(&t, &tm);
3745 char timestr[64];
3746 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3747 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003748 mLastANRState += INDENT "ANR:\n";
3749 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3750 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3751 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3752 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3753 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3754 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 dumpDispatchStateLocked(mLastANRState);
3756
3757 CommandEntry* commandEntry = postCommandLocked(
3758 & InputDispatcher::doNotifyANRLockedInterruptible);
3759 commandEntry->inputApplicationHandle = applicationHandle;
3760 commandEntry->inputWindowHandle = windowHandle;
3761 commandEntry->reason = reason;
3762}
3763
3764void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3765 CommandEntry* commandEntry) {
3766 mLock.unlock();
3767
3768 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3769
3770 mLock.lock();
3771}
3772
3773void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3774 CommandEntry* commandEntry) {
3775 sp<Connection> connection = commandEntry->connection;
3776
3777 if (connection->status != Connection::STATUS_ZOMBIE) {
3778 mLock.unlock();
3779
3780 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3781
3782 mLock.lock();
3783 }
3784}
3785
3786void InputDispatcher::doNotifyANRLockedInterruptible(
3787 CommandEntry* commandEntry) {
3788 mLock.unlock();
3789
3790 nsecs_t newTimeout = mPolicy->notifyANR(
3791 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3792 commandEntry->reason);
3793
3794 mLock.lock();
3795
3796 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Yi Kong9b14ac62018-07-17 13:48:38 -07003797 commandEntry->inputWindowHandle != nullptr
3798 ? commandEntry->inputWindowHandle->getInputChannel() : nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799}
3800
3801void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3802 CommandEntry* commandEntry) {
3803 KeyEntry* entry = commandEntry->keyEntry;
3804
3805 KeyEvent event;
3806 initializeKeyEvent(&event, entry);
3807
3808 mLock.unlock();
3809
Michael Wright2b3c3302018-03-02 17:19:13 +00003810 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3812 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003813 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3814 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3815 std::to_string(t.duration().count()).c_str());
3816 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817
3818 mLock.lock();
3819
3820 if (delay < 0) {
3821 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3822 } else if (!delay) {
3823 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3824 } else {
3825 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3826 entry->interceptKeyWakeupTime = now() + delay;
3827 }
3828 entry->release();
3829}
3830
3831void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3832 CommandEntry* commandEntry) {
3833 sp<Connection> connection = commandEntry->connection;
3834 nsecs_t finishTime = commandEntry->eventTime;
3835 uint32_t seq = commandEntry->seq;
3836 bool handled = commandEntry->handled;
3837
3838 // Handle post-event policy actions.
3839 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3840 if (dispatchEntry) {
3841 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3842 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003843 std::string msg =
3844 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003845 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003847 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 }
3849
3850 bool restartEvent;
3851 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3852 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3853 restartEvent = afterKeyEventLockedInterruptible(connection,
3854 dispatchEntry, keyEntry, handled);
3855 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3856 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3857 restartEvent = afterMotionEventLockedInterruptible(connection,
3858 dispatchEntry, motionEntry, handled);
3859 } else {
3860 restartEvent = false;
3861 }
3862
3863 // Dequeue the event and start the next cycle.
3864 // Note that because the lock might have been released, it is possible that the
3865 // contents of the wait queue to have been drained, so we need to double-check
3866 // a few things.
3867 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3868 connection->waitQueue.dequeue(dispatchEntry);
3869 traceWaitQueueLengthLocked(connection);
3870 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3871 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3872 traceOutboundQueueLengthLocked(connection);
3873 } else {
3874 releaseDispatchEntryLocked(dispatchEntry);
3875 }
3876 }
3877
3878 // Start the next dispatch cycle for this connection.
3879 startDispatchCycleLocked(now(), connection);
3880 }
3881}
3882
3883bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3884 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3885 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3886 // Get the fallback key state.
3887 // Clear it out after dispatching the UP.
3888 int32_t originalKeyCode = keyEntry->keyCode;
3889 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3890 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3891 connection->inputState.removeFallbackKey(originalKeyCode);
3892 }
3893
3894 if (handled || !dispatchEntry->hasForegroundTarget()) {
3895 // If the application handles the original key for which we previously
3896 // generated a fallback or if the window is not a foreground window,
3897 // then cancel the associated fallback key, if any.
3898 if (fallbackKeyCode != -1) {
3899 // Dispatch the unhandled key to the policy with the cancel flag.
3900#if DEBUG_OUTBOUND_EVENT_DETAILS
3901 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3902 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3903 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3904 keyEntry->policyFlags);
3905#endif
3906 KeyEvent event;
3907 initializeKeyEvent(&event, keyEntry);
3908 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3909
3910 mLock.unlock();
3911
3912 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3913 &event, keyEntry->policyFlags, &event);
3914
3915 mLock.lock();
3916
3917 // Cancel the fallback key.
3918 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3919 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3920 "application handled the original non-fallback key "
3921 "or is no longer a foreground target, "
3922 "canceling previously dispatched fallback key");
3923 options.keyCode = fallbackKeyCode;
3924 synthesizeCancelationEventsForConnectionLocked(connection, options);
3925 }
3926 connection->inputState.removeFallbackKey(originalKeyCode);
3927 }
3928 } else {
3929 // If the application did not handle a non-fallback key, first check
3930 // that we are in a good state to perform unhandled key event processing
3931 // Then ask the policy what to do with it.
3932 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3933 && keyEntry->repeatCount == 0;
3934 if (fallbackKeyCode == -1 && !initialDown) {
3935#if DEBUG_OUTBOUND_EVENT_DETAILS
3936 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3937 "since this is not an initial down. "
3938 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3939 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3940 keyEntry->policyFlags);
3941#endif
3942 return false;
3943 }
3944
3945 // Dispatch the unhandled key to the policy.
3946#if DEBUG_OUTBOUND_EVENT_DETAILS
3947 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
3948 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3949 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3950 keyEntry->policyFlags);
3951#endif
3952 KeyEvent event;
3953 initializeKeyEvent(&event, keyEntry);
3954
3955 mLock.unlock();
3956
3957 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3958 &event, keyEntry->policyFlags, &event);
3959
3960 mLock.lock();
3961
3962 if (connection->status != Connection::STATUS_NORMAL) {
3963 connection->inputState.removeFallbackKey(originalKeyCode);
3964 return false;
3965 }
3966
3967 // Latch the fallback keycode for this key on an initial down.
3968 // The fallback keycode cannot change at any other point in the lifecycle.
3969 if (initialDown) {
3970 if (fallback) {
3971 fallbackKeyCode = event.getKeyCode();
3972 } else {
3973 fallbackKeyCode = AKEYCODE_UNKNOWN;
3974 }
3975 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3976 }
3977
3978 ALOG_ASSERT(fallbackKeyCode != -1);
3979
3980 // Cancel the fallback key if the policy decides not to send it anymore.
3981 // We will continue to dispatch the key to the policy but we will no
3982 // longer dispatch a fallback key to the application.
3983 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3984 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3985#if DEBUG_OUTBOUND_EVENT_DETAILS
3986 if (fallback) {
3987 ALOGD("Unhandled key event: Policy requested to send key %d"
3988 "as a fallback for %d, but on the DOWN it had requested "
3989 "to send %d instead. Fallback canceled.",
3990 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3991 } else {
3992 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
3993 "but on the DOWN it had requested to send %d. "
3994 "Fallback canceled.",
3995 originalKeyCode, fallbackKeyCode);
3996 }
3997#endif
3998
3999 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4000 "canceling fallback, policy no longer desires it");
4001 options.keyCode = fallbackKeyCode;
4002 synthesizeCancelationEventsForConnectionLocked(connection, options);
4003
4004 fallback = false;
4005 fallbackKeyCode = AKEYCODE_UNKNOWN;
4006 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4007 connection->inputState.setFallbackKey(originalKeyCode,
4008 fallbackKeyCode);
4009 }
4010 }
4011
4012#if DEBUG_OUTBOUND_EVENT_DETAILS
4013 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004014 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4016 connection->inputState.getFallbackKeys();
4017 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004018 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019 fallbackKeys.valueAt(i));
4020 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07004021 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004022 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023 }
4024#endif
4025
4026 if (fallback) {
4027 // Restart the dispatch cycle using the fallback key.
4028 keyEntry->eventTime = event.getEventTime();
4029 keyEntry->deviceId = event.getDeviceId();
4030 keyEntry->source = event.getSource();
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004031 keyEntry->displayId = event.getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4033 keyEntry->keyCode = fallbackKeyCode;
4034 keyEntry->scanCode = event.getScanCode();
4035 keyEntry->metaState = event.getMetaState();
4036 keyEntry->repeatCount = event.getRepeatCount();
4037 keyEntry->downTime = event.getDownTime();
4038 keyEntry->syntheticRepeat = false;
4039
4040#if DEBUG_OUTBOUND_EVENT_DETAILS
4041 ALOGD("Unhandled key event: Dispatching fallback key. "
4042 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4043 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4044#endif
4045 return true; // restart the event
4046 } else {
4047#if DEBUG_OUTBOUND_EVENT_DETAILS
4048 ALOGD("Unhandled key event: No fallback key.");
4049#endif
4050 }
4051 }
4052 }
4053 return false;
4054}
4055
4056bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4057 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4058 return false;
4059}
4060
4061void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4062 mLock.unlock();
4063
4064 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4065
4066 mLock.lock();
4067}
4068
4069void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004070 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4072 entry->downTime, entry->eventTime);
4073}
4074
4075void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4076 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4077 // TODO Write some statistics about how long we spend waiting.
4078}
4079
4080void InputDispatcher::traceInboundQueueLengthLocked() {
4081 if (ATRACE_ENABLED()) {
4082 ATRACE_INT("iq", mInboundQueue.count());
4083 }
4084}
4085
4086void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4087 if (ATRACE_ENABLED()) {
4088 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004089 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 ATRACE_INT(counterName, connection->outboundQueue.count());
4091 }
4092}
4093
4094void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4095 if (ATRACE_ENABLED()) {
4096 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004097 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 ATRACE_INT(counterName, connection->waitQueue.count());
4099 }
4100}
4101
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004102void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 AutoMutex _l(mLock);
4104
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004105 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 dumpDispatchStateLocked(dump);
4107
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004108 if (!mLastANRState.empty()) {
4109 dump += "\nInput Dispatcher State at time of last ANR:\n";
4110 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 }
4112}
4113
4114void InputDispatcher::monitor() {
4115 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4116 mLock.lock();
4117 mLooper->wake();
4118 mDispatcherIsAliveCondition.wait(mLock);
4119 mLock.unlock();
4120}
4121
4122
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123// --- InputDispatcher::InjectionState ---
4124
4125InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4126 refCount(1),
4127 injectorPid(injectorPid), injectorUid(injectorUid),
4128 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4129 pendingForegroundDispatches(0) {
4130}
4131
4132InputDispatcher::InjectionState::~InjectionState() {
4133}
4134
4135void InputDispatcher::InjectionState::release() {
4136 refCount -= 1;
4137 if (refCount == 0) {
4138 delete this;
4139 } else {
4140 ALOG_ASSERT(refCount > 0);
4141 }
4142}
4143
4144
4145// --- InputDispatcher::EventEntry ---
4146
4147InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4148 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
Yi Kong9b14ac62018-07-17 13:48:38 -07004149 injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150}
4151
4152InputDispatcher::EventEntry::~EventEntry() {
4153 releaseInjectionState();
4154}
4155
4156void InputDispatcher::EventEntry::release() {
4157 refCount -= 1;
4158 if (refCount == 0) {
4159 delete this;
4160 } else {
4161 ALOG_ASSERT(refCount > 0);
4162 }
4163}
4164
4165void InputDispatcher::EventEntry::releaseInjectionState() {
4166 if (injectionState) {
4167 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004168 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 }
4170}
4171
4172
4173// --- InputDispatcher::ConfigurationChangedEntry ---
4174
4175InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4176 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4177}
4178
4179InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4180}
4181
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004182void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4183 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004184}
4185
4186
4187// --- InputDispatcher::DeviceResetEntry ---
4188
4189InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4190 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4191 deviceId(deviceId) {
4192}
4193
4194InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4195}
4196
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004197void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4198 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 deviceId, policyFlags);
4200}
4201
4202
4203// --- InputDispatcher::KeyEntry ---
4204
4205InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004206 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4208 int32_t repeatCount, nsecs_t downTime) :
4209 EventEntry(TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004210 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4212 repeatCount(repeatCount), downTime(downTime),
4213 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4214 interceptKeyWakeupTime(0) {
4215}
4216
4217InputDispatcher::KeyEntry::~KeyEntry() {
4218}
4219
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004220void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004221 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4223 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004224 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004225 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226}
4227
4228void InputDispatcher::KeyEntry::recycle() {
4229 releaseInjectionState();
4230
4231 dispatchInProgress = false;
4232 syntheticRepeat = false;
4233 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4234 interceptKeyWakeupTime = 0;
4235}
4236
4237
4238// --- InputDispatcher::MotionEntry ---
4239
Michael Wright7b159c92015-05-14 14:48:03 +01004240InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004241 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4242 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004243 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4244 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004245 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004246 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4247 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4249 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004250 deviceId(deviceId), source(source), displayId(displayId), action(action),
4251 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004252 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004253 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254 for (uint32_t i = 0; i < pointerCount; i++) {
4255 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4256 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004257 if (xOffset || yOffset) {
4258 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4259 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 }
4261}
4262
4263InputDispatcher::MotionEntry::~MotionEntry() {
4264}
4265
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004266void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004267 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004268 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004269 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004270 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4271 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4272
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 for (uint32_t i = 0; i < pointerCount; i++) {
4274 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004275 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004277 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 pointerCoords[i].getX(), pointerCoords[i].getY());
4279 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004280 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281}
4282
4283
4284// --- InputDispatcher::DispatchEntry ---
4285
4286volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4287
4288InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4289 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4290 seq(nextSeq()),
4291 eventEntry(eventEntry), targetFlags(targetFlags),
4292 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4293 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4294 eventEntry->refCount += 1;
4295}
4296
4297InputDispatcher::DispatchEntry::~DispatchEntry() {
4298 eventEntry->release();
4299}
4300
4301uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4302 // Sequence number 0 is reserved and will never be returned.
4303 uint32_t seq;
4304 do {
4305 seq = android_atomic_inc(&sNextSeqAtomic);
4306 } while (!seq);
4307 return seq;
4308}
4309
4310
4311// --- InputDispatcher::InputState ---
4312
4313InputDispatcher::InputState::InputState() {
4314}
4315
4316InputDispatcher::InputState::~InputState() {
4317}
4318
4319bool InputDispatcher::InputState::isNeutral() const {
4320 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4321}
4322
4323bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4324 int32_t displayId) const {
4325 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4326 const MotionMemento& memento = mMotionMementos.itemAt(i);
4327 if (memento.deviceId == deviceId
4328 && memento.source == source
4329 && memento.displayId == displayId
4330 && memento.hovering) {
4331 return true;
4332 }
4333 }
4334 return false;
4335}
4336
4337bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4338 int32_t action, int32_t flags) {
4339 switch (action) {
4340 case AKEY_EVENT_ACTION_UP: {
4341 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4342 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4343 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4344 mFallbackKeys.removeItemsAt(i);
4345 } else {
4346 i += 1;
4347 }
4348 }
4349 }
4350 ssize_t index = findKeyMemento(entry);
4351 if (index >= 0) {
4352 mKeyMementos.removeAt(index);
4353 return true;
4354 }
4355 /* FIXME: We can't just drop the key up event because that prevents creating
4356 * popup windows that are automatically shown when a key is held and then
4357 * dismissed when the key is released. The problem is that the popup will
4358 * not have received the original key down, so the key up will be considered
4359 * to be inconsistent with its observed state. We could perhaps handle this
4360 * by synthesizing a key down but that will cause other problems.
4361 *
4362 * So for now, allow inconsistent key up events to be dispatched.
4363 *
4364#if DEBUG_OUTBOUND_EVENT_DETAILS
4365 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4366 "keyCode=%d, scanCode=%d",
4367 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4368#endif
4369 return false;
4370 */
4371 return true;
4372 }
4373
4374 case AKEY_EVENT_ACTION_DOWN: {
4375 ssize_t index = findKeyMemento(entry);
4376 if (index >= 0) {
4377 mKeyMementos.removeAt(index);
4378 }
4379 addKeyMemento(entry, flags);
4380 return true;
4381 }
4382
4383 default:
4384 return true;
4385 }
4386}
4387
4388bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4389 int32_t action, int32_t flags) {
4390 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4391 switch (actionMasked) {
4392 case AMOTION_EVENT_ACTION_UP:
4393 case AMOTION_EVENT_ACTION_CANCEL: {
4394 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4395 if (index >= 0) {
4396 mMotionMementos.removeAt(index);
4397 return true;
4398 }
4399#if DEBUG_OUTBOUND_EVENT_DETAILS
4400 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004401 "displayId=%" PRId32 ", actionMasked=%d",
4402 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403#endif
4404 return false;
4405 }
4406
4407 case AMOTION_EVENT_ACTION_DOWN: {
4408 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4409 if (index >= 0) {
4410 mMotionMementos.removeAt(index);
4411 }
4412 addMotionMemento(entry, flags, false /*hovering*/);
4413 return true;
4414 }
4415
4416 case AMOTION_EVENT_ACTION_POINTER_UP:
4417 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4418 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004419 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4420 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4421 // generate cancellation events for these since they're based in relative rather than
4422 // absolute units.
4423 return true;
4424 }
4425
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004427
4428 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4429 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4430 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4431 // other value and we need to track the motion so we can send cancellation events for
4432 // anything generating fallback events (e.g. DPad keys for joystick movements).
4433 if (index >= 0) {
4434 if (entry->pointerCoords[0].isEmpty()) {
4435 mMotionMementos.removeAt(index);
4436 } else {
4437 MotionMemento& memento = mMotionMementos.editItemAt(index);
4438 memento.setPointers(entry);
4439 }
4440 } else if (!entry->pointerCoords[0].isEmpty()) {
4441 addMotionMemento(entry, flags, false /*hovering*/);
4442 }
4443
4444 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4445 return true;
4446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447 if (index >= 0) {
4448 MotionMemento& memento = mMotionMementos.editItemAt(index);
4449 memento.setPointers(entry);
4450 return true;
4451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452#if DEBUG_OUTBOUND_EVENT_DETAILS
4453 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004454 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4455 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456#endif
4457 return false;
4458 }
4459
4460 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4461 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4462 if (index >= 0) {
4463 mMotionMementos.removeAt(index);
4464 return true;
4465 }
4466#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004467 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4468 "displayId=%" PRId32,
4469 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470#endif
4471 return false;
4472 }
4473
4474 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4475 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4476 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4477 if (index >= 0) {
4478 mMotionMementos.removeAt(index);
4479 }
4480 addMotionMemento(entry, flags, true /*hovering*/);
4481 return true;
4482 }
4483
4484 default:
4485 return true;
4486 }
4487}
4488
4489ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4490 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4491 const KeyMemento& memento = mKeyMementos.itemAt(i);
4492 if (memento.deviceId == entry->deviceId
4493 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004494 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495 && memento.keyCode == entry->keyCode
4496 && memento.scanCode == entry->scanCode) {
4497 return i;
4498 }
4499 }
4500 return -1;
4501}
4502
4503ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4504 bool hovering) const {
4505 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4506 const MotionMemento& memento = mMotionMementos.itemAt(i);
4507 if (memento.deviceId == entry->deviceId
4508 && memento.source == entry->source
4509 && memento.displayId == entry->displayId
4510 && memento.hovering == hovering) {
4511 return i;
4512 }
4513 }
4514 return -1;
4515}
4516
4517void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4518 mKeyMementos.push();
4519 KeyMemento& memento = mKeyMementos.editTop();
4520 memento.deviceId = entry->deviceId;
4521 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004522 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 memento.keyCode = entry->keyCode;
4524 memento.scanCode = entry->scanCode;
4525 memento.metaState = entry->metaState;
4526 memento.flags = flags;
4527 memento.downTime = entry->downTime;
4528 memento.policyFlags = entry->policyFlags;
4529}
4530
4531void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4532 int32_t flags, bool hovering) {
4533 mMotionMementos.push();
4534 MotionMemento& memento = mMotionMementos.editTop();
4535 memento.deviceId = entry->deviceId;
4536 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004537 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 memento.flags = flags;
4539 memento.xPrecision = entry->xPrecision;
4540 memento.yPrecision = entry->yPrecision;
4541 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542 memento.setPointers(entry);
4543 memento.hovering = hovering;
4544 memento.policyFlags = entry->policyFlags;
4545}
4546
4547void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4548 pointerCount = entry->pointerCount;
4549 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4550 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4551 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4552 }
4553}
4554
4555void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4556 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4557 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4558 const KeyMemento& memento = mKeyMementos.itemAt(i);
4559 if (shouldCancelKey(memento, options)) {
4560 outEvents.push(new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004561 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4563 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4564 }
4565 }
4566
4567 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4568 const MotionMemento& memento = mMotionMementos.itemAt(i);
4569 if (shouldCancelMotion(memento, options)) {
4570 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004571 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 memento.hovering
4573 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4574 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004575 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004576 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004577 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4578 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579 }
4580 }
4581}
4582
4583void InputDispatcher::InputState::clear() {
4584 mKeyMementos.clear();
4585 mMotionMementos.clear();
4586 mFallbackKeys.clear();
4587}
4588
4589void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4590 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4591 const MotionMemento& memento = mMotionMementos.itemAt(i);
4592 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4593 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4594 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4595 if (memento.deviceId == otherMemento.deviceId
4596 && memento.source == otherMemento.source
4597 && memento.displayId == otherMemento.displayId) {
4598 other.mMotionMementos.removeAt(j);
4599 } else {
4600 j += 1;
4601 }
4602 }
4603 other.mMotionMementos.push(memento);
4604 }
4605 }
4606}
4607
4608int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4609 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4610 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4611}
4612
4613void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4614 int32_t fallbackKeyCode) {
4615 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4616 if (index >= 0) {
4617 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4618 } else {
4619 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4620 }
4621}
4622
4623void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4624 mFallbackKeys.removeItem(originalKeyCode);
4625}
4626
4627bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4628 const CancelationOptions& options) {
4629 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4630 return false;
4631 }
4632
4633 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4634 return false;
4635 }
4636
4637 switch (options.mode) {
4638 case CancelationOptions::CANCEL_ALL_EVENTS:
4639 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4640 return true;
4641 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4642 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004643 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4644 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 default:
4646 return false;
4647 }
4648}
4649
4650bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4651 const CancelationOptions& options) {
4652 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4653 return false;
4654 }
4655
4656 switch (options.mode) {
4657 case CancelationOptions::CANCEL_ALL_EVENTS:
4658 return true;
4659 case CancelationOptions::CANCEL_POINTER_EVENTS:
4660 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4661 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4662 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004663 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4664 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665 default:
4666 return false;
4667 }
4668}
4669
4670
4671// --- InputDispatcher::Connection ---
4672
4673InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4674 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4675 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4676 monitor(monitor),
4677 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4678}
4679
4680InputDispatcher::Connection::~Connection() {
4681}
4682
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004683const std::string InputDispatcher::Connection::getWindowName() const {
Yi Kong9b14ac62018-07-17 13:48:38 -07004684 if (inputWindowHandle != nullptr) {
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004685 return inputWindowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686 }
4687 if (monitor) {
4688 return "monitor";
4689 }
4690 return "?";
4691}
4692
4693const char* InputDispatcher::Connection::getStatusLabel() const {
4694 switch (status) {
4695 case STATUS_NORMAL:
4696 return "NORMAL";
4697
4698 case STATUS_BROKEN:
4699 return "BROKEN";
4700
4701 case STATUS_ZOMBIE:
4702 return "ZOMBIE";
4703
4704 default:
4705 return "UNKNOWN";
4706 }
4707}
4708
4709InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004710 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 if (entry->seq == seq) {
4712 return entry;
4713 }
4714 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004715 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716}
4717
4718
4719// --- InputDispatcher::CommandEntry ---
4720
4721InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004722 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 seq(0), handled(false) {
4724}
4725
4726InputDispatcher::CommandEntry::~CommandEntry() {
4727}
4728
4729
4730// --- InputDispatcher::TouchState ---
4731
4732InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004733 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734}
4735
4736InputDispatcher::TouchState::~TouchState() {
4737}
4738
4739void InputDispatcher::TouchState::reset() {
4740 down = false;
4741 split = false;
4742 deviceId = -1;
4743 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004744 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004745 windows.clear();
4746}
4747
4748void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4749 down = other.down;
4750 split = other.split;
4751 deviceId = other.deviceId;
4752 source = other.source;
4753 displayId = other.displayId;
4754 windows = other.windows;
4755}
4756
4757void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4758 int32_t targetFlags, BitSet32 pointerIds) {
4759 if (targetFlags & InputTarget::FLAG_SPLIT) {
4760 split = true;
4761 }
4762
4763 for (size_t i = 0; i < windows.size(); i++) {
4764 TouchedWindow& touchedWindow = windows.editItemAt(i);
4765 if (touchedWindow.windowHandle == windowHandle) {
4766 touchedWindow.targetFlags |= targetFlags;
4767 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4768 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4769 }
4770 touchedWindow.pointerIds.value |= pointerIds.value;
4771 return;
4772 }
4773 }
4774
4775 windows.push();
4776
4777 TouchedWindow& touchedWindow = windows.editTop();
4778 touchedWindow.windowHandle = windowHandle;
4779 touchedWindow.targetFlags = targetFlags;
4780 touchedWindow.pointerIds = pointerIds;
4781}
4782
4783void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4784 for (size_t i = 0; i < windows.size(); i++) {
4785 if (windows.itemAt(i).windowHandle == windowHandle) {
4786 windows.removeAt(i);
4787 return;
4788 }
4789 }
4790}
4791
4792void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4793 for (size_t i = 0 ; i < windows.size(); ) {
4794 TouchedWindow& window = windows.editItemAt(i);
4795 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4796 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4797 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4798 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4799 i += 1;
4800 } else {
4801 windows.removeAt(i);
4802 }
4803 }
4804}
4805
4806sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4807 for (size_t i = 0; i < windows.size(); i++) {
4808 const TouchedWindow& window = windows.itemAt(i);
4809 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4810 return window.windowHandle;
4811 }
4812 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004813 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814}
4815
4816bool InputDispatcher::TouchState::isSlippery() const {
4817 // Must have exactly one foreground window.
4818 bool haveSlipperyForegroundWindow = false;
4819 for (size_t i = 0; i < windows.size(); i++) {
4820 const TouchedWindow& window = windows.itemAt(i);
4821 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4822 if (haveSlipperyForegroundWindow
4823 || !(window.windowHandle->getInfo()->layoutParamsFlags
4824 & InputWindowInfo::FLAG_SLIPPERY)) {
4825 return false;
4826 }
4827 haveSlipperyForegroundWindow = true;
4828 }
4829 }
4830 return haveSlipperyForegroundWindow;
4831}
4832
4833
4834// --- InputDispatcherThread ---
4835
4836InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4837 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4838}
4839
4840InputDispatcherThread::~InputDispatcherThread() {
4841}
4842
4843bool InputDispatcherThread::threadLoop() {
4844 mDispatcher->dispatchOnce();
4845 return true;
4846}
4847
4848} // namespace android