blob: 4d32ea6eeaa16f6ae6b111f991a60669ac057aa4 [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
108static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
109 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
110 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
111}
112
113static bool isValidKeyAction(int32_t action) {
114 switch (action) {
115 case AKEY_EVENT_ACTION_DOWN:
116 case AKEY_EVENT_ACTION_UP:
117 return true;
118 default:
119 return false;
120 }
121}
122
123static bool validateKeyEvent(int32_t action) {
124 if (! isValidKeyAction(action)) {
125 ALOGE("Key event has invalid action code 0x%x", action);
126 return false;
127 }
128 return true;
129}
130
Michael Wright7b159c92015-05-14 14:48:03 +0100131static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 switch (action & AMOTION_EVENT_ACTION_MASK) {
133 case AMOTION_EVENT_ACTION_DOWN:
134 case AMOTION_EVENT_ACTION_UP:
135 case AMOTION_EVENT_ACTION_CANCEL:
136 case AMOTION_EVENT_ACTION_MOVE:
137 case AMOTION_EVENT_ACTION_OUTSIDE:
138 case AMOTION_EVENT_ACTION_HOVER_ENTER:
139 case AMOTION_EVENT_ACTION_HOVER_MOVE:
140 case AMOTION_EVENT_ACTION_HOVER_EXIT:
141 case AMOTION_EVENT_ACTION_SCROLL:
142 return true;
143 case AMOTION_EVENT_ACTION_POINTER_DOWN:
144 case AMOTION_EVENT_ACTION_POINTER_UP: {
145 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800146 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 }
Michael Wright7b159c92015-05-14 14:48:03 +0100148 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
149 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
150 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800151 default:
152 return false;
153 }
154}
155
Michael Wright7b159c92015-05-14 14:48:03 +0100156static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800157 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100158 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800159 ALOGE("Motion event has invalid action code 0x%x", action);
160 return false;
161 }
162 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000163 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800164 pointerCount, MAX_POINTERS);
165 return false;
166 }
167 BitSet32 pointerIdBits;
168 for (size_t i = 0; i < pointerCount; i++) {
169 int32_t id = pointerProperties[i].id;
170 if (id < 0 || id > MAX_POINTER_ID) {
171 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
172 id, MAX_POINTER_ID);
173 return false;
174 }
175 if (pointerIdBits.hasBit(id)) {
176 ALOGE("Motion event has duplicate pointer id %d", id);
177 return false;
178 }
179 pointerIdBits.markBit(id);
180 }
181 return true;
182}
183
184static bool isMainDisplay(int32_t displayId) {
185 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
186}
187
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800188static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800190 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 return;
192 }
193
194 bool first = true;
195 Region::const_iterator cur = region.begin();
196 Region::const_iterator const tail = region.end();
197 while (cur != tail) {
198 if (first) {
199 first = false;
200 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800201 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800203 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 cur++;
205 }
206}
207
208
209// --- InputDispatcher ---
210
211InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
212 mPolicy(policy),
Michael Wright3a981722015-06-10 15:26:13 +0100213 mPendingEvent(NULL), mLastDropReason(DROP_REASON_NOT_DROPPED),
214 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 mNextUnblockedEvent(NULL),
216 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
217 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
218 mLooper = new Looper(false);
219
220 mKeyRepeatState.lastKeyEntry = NULL;
221
222 policy->getDispatcherConfiguration(&mConfig);
223}
224
225InputDispatcher::~InputDispatcher() {
226 { // acquire lock
227 AutoMutex _l(mLock);
228
229 resetKeyRepeatLocked();
230 releasePendingEventLocked();
231 drainInboundQueueLocked();
232 }
233
234 while (mConnectionsByFd.size() != 0) {
235 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
236 }
237}
238
239void InputDispatcher::dispatchOnce() {
240 nsecs_t nextWakeupTime = LONG_LONG_MAX;
241 { // acquire lock
242 AutoMutex _l(mLock);
243 mDispatcherIsAliveCondition.broadcast();
244
245 // Run a dispatch loop if there are no pending commands.
246 // The dispatch loop might enqueue commands to run afterwards.
247 if (!haveCommandsLocked()) {
248 dispatchOnceInnerLocked(&nextWakeupTime);
249 }
250
251 // Run all pending commands if there are any.
252 // If any commands were run then force the next poll to wake up immediately.
253 if (runCommandsLockedInterruptible()) {
254 nextWakeupTime = LONG_LONG_MIN;
255 }
256 } // release lock
257
258 // Wait for callback or timeout or wake. (make sure we round up, not down)
259 nsecs_t currentTime = now();
260 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
261 mLooper->pollOnce(timeoutMillis);
262}
263
264void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
265 nsecs_t currentTime = now();
266
Jeff Browndc5992e2014-04-11 01:27:26 -0700267 // Reset the key repeat timer whenever normal dispatch is suspended while the
268 // device is in a non-interactive state. This is to ensure that we abort a key
269 // repeat if the device is just coming out of sleep.
270 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800271 resetKeyRepeatLocked();
272 }
273
274 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
275 if (mDispatchFrozen) {
276#if DEBUG_FOCUS
277 ALOGD("Dispatch frozen. Waiting some more.");
278#endif
279 return;
280 }
281
282 // Optimize latency of app switches.
283 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
284 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
285 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
286 if (mAppSwitchDueTime < *nextWakeupTime) {
287 *nextWakeupTime = mAppSwitchDueTime;
288 }
289
290 // Ready to start a new event.
291 // If we don't already have a pending event, go grab one.
292 if (! mPendingEvent) {
293 if (mInboundQueue.isEmpty()) {
294 if (isAppSwitchDue) {
295 // The inbound queue is empty so the app switch key we were waiting
296 // for will never arrive. Stop waiting for it.
297 resetPendingAppSwitchLocked(false);
298 isAppSwitchDue = false;
299 }
300
301 // Synthesize a key repeat if appropriate.
302 if (mKeyRepeatState.lastKeyEntry) {
303 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
304 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
305 } else {
306 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
307 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
308 }
309 }
310 }
311
312 // Nothing to do if there is no pending event.
313 if (!mPendingEvent) {
314 return;
315 }
316 } else {
317 // Inbound queue has at least one entry.
318 mPendingEvent = mInboundQueue.dequeueAtHead();
319 traceInboundQueueLengthLocked();
320 }
321
322 // Poke user activity for this event.
323 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
324 pokeUserActivityLocked(mPendingEvent);
325 }
326
327 // Get ready to dispatch the event.
328 resetANRTimeoutsLocked();
329 }
330
331 // Now we have an event to dispatch.
332 // All events are eventually dequeued and processed this way, even if we intend to drop them.
333 ALOG_ASSERT(mPendingEvent != NULL);
334 bool done = false;
335 DropReason dropReason = DROP_REASON_NOT_DROPPED;
336 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
337 dropReason = DROP_REASON_POLICY;
338 } else if (!mDispatchEnabled) {
339 dropReason = DROP_REASON_DISABLED;
340 }
341
342 if (mNextUnblockedEvent == mPendingEvent) {
343 mNextUnblockedEvent = NULL;
344 }
345
346 switch (mPendingEvent->type) {
347 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
348 ConfigurationChangedEntry* typedEntry =
349 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
350 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
351 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
352 break;
353 }
354
355 case EventEntry::TYPE_DEVICE_RESET: {
356 DeviceResetEntry* typedEntry =
357 static_cast<DeviceResetEntry*>(mPendingEvent);
358 done = dispatchDeviceResetLocked(currentTime, typedEntry);
359 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
360 break;
361 }
362
363 case EventEntry::TYPE_KEY: {
364 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
365 if (isAppSwitchDue) {
366 if (isAppSwitchKeyEventLocked(typedEntry)) {
367 resetPendingAppSwitchLocked(true);
368 isAppSwitchDue = false;
369 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
370 dropReason = DROP_REASON_APP_SWITCH;
371 }
372 }
373 if (dropReason == DROP_REASON_NOT_DROPPED
374 && isStaleEventLocked(currentTime, typedEntry)) {
375 dropReason = DROP_REASON_STALE;
376 }
377 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
378 dropReason = DROP_REASON_BLOCKED;
379 }
380 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
381 break;
382 }
383
384 case EventEntry::TYPE_MOTION: {
385 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
386 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
387 dropReason = DROP_REASON_APP_SWITCH;
388 }
389 if (dropReason == DROP_REASON_NOT_DROPPED
390 && isStaleEventLocked(currentTime, typedEntry)) {
391 dropReason = DROP_REASON_STALE;
392 }
393 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
394 dropReason = DROP_REASON_BLOCKED;
395 }
396 done = dispatchMotionLocked(currentTime, typedEntry,
397 &dropReason, nextWakeupTime);
398 break;
399 }
400
401 default:
402 ALOG_ASSERT(false);
403 break;
404 }
405
406 if (done) {
407 if (dropReason != DROP_REASON_NOT_DROPPED) {
408 dropInboundEventLocked(mPendingEvent, dropReason);
409 }
Michael Wright3a981722015-06-10 15:26:13 +0100410 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411
412 releasePendingEventLocked();
413 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
414 }
415}
416
417bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
418 bool needWake = mInboundQueue.isEmpty();
419 mInboundQueue.enqueueAtTail(entry);
420 traceInboundQueueLengthLocked();
421
422 switch (entry->type) {
423 case EventEntry::TYPE_KEY: {
424 // Optimize app switch latency.
425 // If the application takes too long to catch up then we drop all events preceding
426 // the app switch key.
427 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
428 if (isAppSwitchKeyEventLocked(keyEntry)) {
429 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
430 mAppSwitchSawKeyDown = true;
431 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
432 if (mAppSwitchSawKeyDown) {
433#if DEBUG_APP_SWITCH
434 ALOGD("App switch is pending!");
435#endif
436 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
437 mAppSwitchSawKeyDown = false;
438 needWake = true;
439 }
440 }
441 }
442 break;
443 }
444
445 case EventEntry::TYPE_MOTION: {
446 // Optimize case where the current application is unresponsive and the user
447 // decides to touch a window in a different application.
448 // If the application takes too long to catch up then we drop all events preceding
449 // the touch into the other window.
450 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
451 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
452 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
453 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
454 && mInputTargetWaitApplicationHandle != NULL) {
455 int32_t displayId = motionEntry->displayId;
456 int32_t x = int32_t(motionEntry->pointerCoords[0].
457 getAxisValue(AMOTION_EVENT_AXIS_X));
458 int32_t y = int32_t(motionEntry->pointerCoords[0].
459 getAxisValue(AMOTION_EVENT_AXIS_Y));
460 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
461 if (touchedWindowHandle != NULL
462 && touchedWindowHandle->inputApplicationHandle
463 != mInputTargetWaitApplicationHandle) {
464 // User touched a different application than the one we are waiting on.
465 // Flag the event, and start pruning the input queue.
466 mNextUnblockedEvent = motionEntry;
467 needWake = true;
468 }
469 }
470 break;
471 }
472 }
473
474 return needWake;
475}
476
477void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
478 entry->refCount += 1;
479 mRecentQueue.enqueueAtTail(entry);
480 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
481 mRecentQueue.dequeueAtHead()->release();
482 }
483}
484
485sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
486 int32_t x, int32_t y) {
487 // Traverse windows from front to back to find touched window.
488 size_t numWindows = mWindowHandles.size();
489 for (size_t i = 0; i < numWindows; i++) {
490 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
491 const InputWindowInfo* windowInfo = windowHandle->getInfo();
492 if (windowInfo->displayId == displayId) {
493 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494
495 if (windowInfo->visible) {
496 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
497 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
498 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
499 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
500 // Found window.
501 return windowHandle;
502 }
503 }
504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 }
506 }
507 return NULL;
508}
509
510void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
511 const char* reason;
512 switch (dropReason) {
513 case DROP_REASON_POLICY:
514#if DEBUG_INBOUND_EVENT_DETAILS
515 ALOGD("Dropped event because policy consumed it.");
516#endif
517 reason = "inbound event was dropped because the policy consumed it";
518 break;
519 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100520 if (mLastDropReason != DROP_REASON_DISABLED) {
521 ALOGI("Dropped event because input dispatch is disabled.");
522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800523 reason = "inbound event was dropped because input dispatch is disabled";
524 break;
525 case DROP_REASON_APP_SWITCH:
526 ALOGI("Dropped event because of pending overdue app switch.");
527 reason = "inbound event was dropped because of pending overdue app switch";
528 break;
529 case DROP_REASON_BLOCKED:
530 ALOGI("Dropped event because the current application is not responding and the user "
531 "has started interacting with a different application.");
532 reason = "inbound event was dropped because the current application is not responding "
533 "and the user has started interacting with a different application";
534 break;
535 case DROP_REASON_STALE:
536 ALOGI("Dropped event because it is stale.");
537 reason = "inbound event was dropped because it is stale";
538 break;
539 default:
540 ALOG_ASSERT(false);
541 return;
542 }
543
544 switch (entry->type) {
545 case EventEntry::TYPE_KEY: {
546 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
547 synthesizeCancelationEventsForAllConnectionsLocked(options);
548 break;
549 }
550 case EventEntry::TYPE_MOTION: {
551 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
552 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
553 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
554 synthesizeCancelationEventsForAllConnectionsLocked(options);
555 } else {
556 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
557 synthesizeCancelationEventsForAllConnectionsLocked(options);
558 }
559 break;
560 }
561 }
562}
563
564bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
565 return keyCode == AKEYCODE_HOME
566 || keyCode == AKEYCODE_ENDCALL
567 || keyCode == AKEYCODE_APP_SWITCH;
568}
569
570bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
571 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
572 && isAppSwitchKeyCode(keyEntry->keyCode)
573 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
574 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
575}
576
577bool InputDispatcher::isAppSwitchPendingLocked() {
578 return mAppSwitchDueTime != LONG_LONG_MAX;
579}
580
581void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
582 mAppSwitchDueTime = LONG_LONG_MAX;
583
584#if DEBUG_APP_SWITCH
585 if (handled) {
586 ALOGD("App switch has arrived.");
587 } else {
588 ALOGD("App switch was abandoned.");
589 }
590#endif
591}
592
593bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
594 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
595}
596
597bool InputDispatcher::haveCommandsLocked() const {
598 return !mCommandQueue.isEmpty();
599}
600
601bool InputDispatcher::runCommandsLockedInterruptible() {
602 if (mCommandQueue.isEmpty()) {
603 return false;
604 }
605
606 do {
607 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
608
609 Command command = commandEntry->command;
610 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
611
612 commandEntry->connection.clear();
613 delete commandEntry;
614 } while (! mCommandQueue.isEmpty());
615 return true;
616}
617
618InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
619 CommandEntry* commandEntry = new CommandEntry(command);
620 mCommandQueue.enqueueAtTail(commandEntry);
621 return commandEntry;
622}
623
624void InputDispatcher::drainInboundQueueLocked() {
625 while (! mInboundQueue.isEmpty()) {
626 EventEntry* entry = mInboundQueue.dequeueAtHead();
627 releaseInboundEventLocked(entry);
628 }
629 traceInboundQueueLengthLocked();
630}
631
632void InputDispatcher::releasePendingEventLocked() {
633 if (mPendingEvent) {
634 resetANRTimeoutsLocked();
635 releaseInboundEventLocked(mPendingEvent);
636 mPendingEvent = NULL;
637 }
638}
639
640void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
641 InjectionState* injectionState = entry->injectionState;
642 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
643#if DEBUG_DISPATCH_CYCLE
644 ALOGD("Injected inbound event was dropped.");
645#endif
646 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
647 }
648 if (entry == mNextUnblockedEvent) {
649 mNextUnblockedEvent = NULL;
650 }
651 addRecentEventLocked(entry);
652 entry->release();
653}
654
655void InputDispatcher::resetKeyRepeatLocked() {
656 if (mKeyRepeatState.lastKeyEntry) {
657 mKeyRepeatState.lastKeyEntry->release();
658 mKeyRepeatState.lastKeyEntry = NULL;
659 }
660}
661
662InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
663 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
664
665 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700666 uint32_t policyFlags = entry->policyFlags &
667 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 if (entry->refCount == 1) {
669 entry->recycle();
670 entry->eventTime = currentTime;
671 entry->policyFlags = policyFlags;
672 entry->repeatCount += 1;
673 } else {
674 KeyEntry* newEntry = new KeyEntry(currentTime,
675 entry->deviceId, entry->source, policyFlags,
676 entry->action, entry->flags, entry->keyCode, entry->scanCode,
677 entry->metaState, entry->repeatCount + 1, entry->downTime);
678
679 mKeyRepeatState.lastKeyEntry = newEntry;
680 entry->release();
681
682 entry = newEntry;
683 }
684 entry->syntheticRepeat = true;
685
686 // Increment reference count since we keep a reference to the event in
687 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
688 entry->refCount += 1;
689
690 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
691 return entry;
692}
693
694bool InputDispatcher::dispatchConfigurationChangedLocked(
695 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
696#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700697 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698#endif
699
700 // Reset key repeating in case a keyboard device was added or removed or something.
701 resetKeyRepeatLocked();
702
703 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
704 CommandEntry* commandEntry = postCommandLocked(
705 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
706 commandEntry->eventTime = entry->eventTime;
707 return true;
708}
709
710bool InputDispatcher::dispatchDeviceResetLocked(
711 nsecs_t currentTime, DeviceResetEntry* entry) {
712#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700713 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
714 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715#endif
716
717 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
718 "device was reset");
719 options.deviceId = entry->deviceId;
720 synthesizeCancelationEventsForAllConnectionsLocked(options);
721 return true;
722}
723
724bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
725 DropReason* dropReason, nsecs_t* nextWakeupTime) {
726 // Preprocessing.
727 if (! entry->dispatchInProgress) {
728 if (entry->repeatCount == 0
729 && entry->action == AKEY_EVENT_ACTION_DOWN
730 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
731 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
732 if (mKeyRepeatState.lastKeyEntry
733 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
734 // We have seen two identical key downs in a row which indicates that the device
735 // driver is automatically generating key repeats itself. We take note of the
736 // repeat here, but we disable our own next key repeat timer since it is clear that
737 // we will not need to synthesize key repeats ourselves.
738 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
739 resetKeyRepeatLocked();
740 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
741 } else {
742 // Not a repeat. Save key down state in case we do see a repeat later.
743 resetKeyRepeatLocked();
744 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
745 }
746 mKeyRepeatState.lastKeyEntry = entry;
747 entry->refCount += 1;
748 } else if (! entry->syntheticRepeat) {
749 resetKeyRepeatLocked();
750 }
751
752 if (entry->repeatCount == 1) {
753 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
754 } else {
755 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
756 }
757
758 entry->dispatchInProgress = true;
759
760 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
761 }
762
763 // Handle case where the policy asked us to try again later last time.
764 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
765 if (currentTime < entry->interceptKeyWakeupTime) {
766 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
767 *nextWakeupTime = entry->interceptKeyWakeupTime;
768 }
769 return false; // wait until next wakeup
770 }
771 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
772 entry->interceptKeyWakeupTime = 0;
773 }
774
775 // Give the policy a chance to intercept the key.
776 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
777 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
778 CommandEntry* commandEntry = postCommandLocked(
779 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
780 if (mFocusedWindowHandle != NULL) {
781 commandEntry->inputWindowHandle = mFocusedWindowHandle;
782 }
783 commandEntry->keyEntry = entry;
784 entry->refCount += 1;
785 return false; // wait for the command to run
786 } else {
787 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
788 }
789 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
790 if (*dropReason == DROP_REASON_NOT_DROPPED) {
791 *dropReason = DROP_REASON_POLICY;
792 }
793 }
794
795 // Clean up if dropping the event.
796 if (*dropReason != DROP_REASON_NOT_DROPPED) {
797 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
798 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
799 return true;
800 }
801
802 // Identify targets.
803 Vector<InputTarget> inputTargets;
804 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
805 entry, inputTargets, nextWakeupTime);
806 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
807 return false;
808 }
809
810 setInjectionResultLocked(entry, injectionResult);
811 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
812 return true;
813 }
814
815 addMonitoringTargetsLocked(inputTargets);
816
817 // Dispatch the key.
818 dispatchEventLocked(currentTime, entry, inputTargets);
819 return true;
820}
821
822void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
823#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700824 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, policyFlags=0x%x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700826 "repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 prefix,
828 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
829 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
830 entry->repeatCount, entry->downTime);
831#endif
832}
833
834bool InputDispatcher::dispatchMotionLocked(
835 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
836 // Preprocessing.
837 if (! entry->dispatchInProgress) {
838 entry->dispatchInProgress = true;
839
840 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
841 }
842
843 // Clean up if dropping the event.
844 if (*dropReason != DROP_REASON_NOT_DROPPED) {
845 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
846 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
847 return true;
848 }
849
850 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
851
852 // Identify targets.
853 Vector<InputTarget> inputTargets;
854
855 bool conflictingPointerActions = false;
856 int32_t injectionResult;
857 if (isPointerEvent) {
858 // Pointer event. (eg. touchscreen)
859 injectionResult = findTouchedWindowTargetsLocked(currentTime,
860 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
861 } else {
862 // Non touch event. (eg. trackball)
863 injectionResult = findFocusedWindowTargetsLocked(currentTime,
864 entry, inputTargets, nextWakeupTime);
865 }
866 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
867 return false;
868 }
869
870 setInjectionResultLocked(entry, injectionResult);
871 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100872 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
873 CancelationOptions::Mode mode(isPointerEvent ?
874 CancelationOptions::CANCEL_POINTER_EVENTS :
875 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
876 CancelationOptions options(mode, "input event injection failed");
877 synthesizeCancelationEventsForMonitorsLocked(options);
878 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879 return true;
880 }
881
Tarandeep Singh48aeb512017-07-17 11:22:52 -0700882 addMonitoringTargetsLocked(inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883
884 // Dispatch the motion.
885 if (conflictingPointerActions) {
886 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
887 "conflicting pointer actions");
888 synthesizeCancelationEventsForAllConnectionsLocked(options);
889 }
890 dispatchEventLocked(currentTime, entry, inputTargets);
891 return true;
892}
893
894
895void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
896#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800897 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
898 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100899 "action=0x%x, actionButton=0x%x, flags=0x%x, "
900 "metaState=0x%x, buttonState=0x%x,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700901 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800903 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100904 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800905 entry->metaState, entry->buttonState,
906 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
907 entry->downTime);
908
909 for (uint32_t i = 0; i < entry->pointerCount; i++) {
910 ALOGD(" Pointer %d: id=%d, toolType=%d, "
911 "x=%f, y=%f, pressure=%f, size=%f, "
912 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800913 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 i, entry->pointerProperties[i].id,
915 entry->pointerProperties[i].toolType,
916 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
917 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
918 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
919 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
920 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
921 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
922 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
923 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800924 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 }
926#endif
927}
928
929void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
930 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
931#if DEBUG_DISPATCH_CYCLE
932 ALOGD("dispatchEventToCurrentInputTargets");
933#endif
934
935 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
936
937 pokeUserActivityLocked(eventEntry);
938
939 for (size_t i = 0; i < inputTargets.size(); i++) {
940 const InputTarget& inputTarget = inputTargets.itemAt(i);
941
942 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
943 if (connectionIndex >= 0) {
944 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
945 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
946 } else {
947#if DEBUG_FOCUS
948 ALOGD("Dropping event delivery to target with channel '%s' because it "
949 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800950 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951#endif
952 }
953 }
954}
955
956int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
957 const EventEntry* entry,
958 const sp<InputApplicationHandle>& applicationHandle,
959 const sp<InputWindowHandle>& windowHandle,
960 nsecs_t* nextWakeupTime, const char* reason) {
961 if (applicationHandle == NULL && windowHandle == NULL) {
962 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
963#if DEBUG_FOCUS
964 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
965#endif
966 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
967 mInputTargetWaitStartTime = currentTime;
968 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
969 mInputTargetWaitTimeoutExpired = false;
970 mInputTargetWaitApplicationHandle.clear();
971 }
972 } else {
973 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
974#if DEBUG_FOCUS
975 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800976 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 reason);
978#endif
979 nsecs_t timeout;
980 if (windowHandle != NULL) {
981 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
982 } else if (applicationHandle != NULL) {
983 timeout = applicationHandle->getDispatchingTimeout(
984 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
985 } else {
986 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
987 }
988
989 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
990 mInputTargetWaitStartTime = currentTime;
991 mInputTargetWaitTimeoutTime = currentTime + timeout;
992 mInputTargetWaitTimeoutExpired = false;
993 mInputTargetWaitApplicationHandle.clear();
994
995 if (windowHandle != NULL) {
996 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
997 }
998 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
999 mInputTargetWaitApplicationHandle = applicationHandle;
1000 }
1001 }
1002 }
1003
1004 if (mInputTargetWaitTimeoutExpired) {
1005 return INPUT_EVENT_INJECTION_TIMED_OUT;
1006 }
1007
1008 if (currentTime >= mInputTargetWaitTimeoutTime) {
1009 onANRLocked(currentTime, applicationHandle, windowHandle,
1010 entry->eventTime, mInputTargetWaitStartTime, reason);
1011
1012 // Force poll loop to wake up immediately on next iteration once we get the
1013 // ANR response back from the policy.
1014 *nextWakeupTime = LONG_LONG_MIN;
1015 return INPUT_EVENT_INJECTION_PENDING;
1016 } else {
1017 // Force poll loop to wake up when timeout is due.
1018 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1019 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1020 }
1021 return INPUT_EVENT_INJECTION_PENDING;
1022 }
1023}
1024
1025void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1026 const sp<InputChannel>& inputChannel) {
1027 if (newTimeout > 0) {
1028 // Extend the timeout.
1029 mInputTargetWaitTimeoutTime = now() + newTimeout;
1030 } else {
1031 // Give up.
1032 mInputTargetWaitTimeoutExpired = true;
1033
1034 // Input state will not be realistic. Mark it out of sync.
1035 if (inputChannel.get()) {
1036 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1037 if (connectionIndex >= 0) {
1038 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1039 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1040
1041 if (windowHandle != NULL) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001042 const InputWindowInfo* info = windowHandle->getInfo();
1043 if (info) {
1044 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId);
1045 if (stateIndex >= 0) {
1046 mTouchStatesByDisplay.editValueAt(stateIndex).removeWindow(
1047 windowHandle);
1048 }
1049 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 }
1051
1052 if (connection->status == Connection::STATUS_NORMAL) {
1053 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1054 "application not responding");
1055 synthesizeCancelationEventsForConnectionLocked(connection, options);
1056 }
1057 }
1058 }
1059 }
1060}
1061
1062nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1063 nsecs_t currentTime) {
1064 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1065 return currentTime - mInputTargetWaitStartTime;
1066 }
1067 return 0;
1068}
1069
1070void InputDispatcher::resetANRTimeoutsLocked() {
1071#if DEBUG_FOCUS
1072 ALOGD("Resetting ANR timeouts.");
1073#endif
1074
1075 // Reset input target wait timeout.
1076 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1077 mInputTargetWaitApplicationHandle.clear();
1078}
1079
1080int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1081 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1082 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001083 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001084
1085 // If there is no currently focused window and no focused application
1086 // then drop the event.
1087 if (mFocusedWindowHandle == NULL) {
1088 if (mFocusedApplicationHandle != NULL) {
1089 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1090 mFocusedApplicationHandle, NULL, nextWakeupTime,
1091 "Waiting because no window has focus but there is a "
1092 "focused application that may eventually add a window "
1093 "when it finishes starting up.");
1094 goto Unresponsive;
1095 }
1096
1097 ALOGI("Dropping event because there is no focused window or focused application.");
1098 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1099 goto Failed;
1100 }
1101
1102 // Check permissions.
1103 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
1104 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1105 goto Failed;
1106 }
1107
Jeff Brownffb49772014-10-10 19:01:34 -07001108 // Check whether the window is ready for more input.
1109 reason = checkWindowReadyForMoreInputLocked(currentTime,
1110 mFocusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001111 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001113 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114 goto Unresponsive;
1115 }
1116
1117 // Success! Output targets.
1118 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1119 addWindowTargetLocked(mFocusedWindowHandle,
1120 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1121 inputTargets);
1122
1123 // Done.
1124Failed:
1125Unresponsive:
1126 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1127 updateDispatchStatisticsLocked(currentTime, entry,
1128 injectionResult, timeSpentWaitingForApplication);
1129#if DEBUG_FOCUS
1130 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1131 "timeSpentWaitingForApplication=%0.1fms",
1132 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1133#endif
1134 return injectionResult;
1135}
1136
1137int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1138 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1139 bool* outConflictingPointerActions) {
1140 enum InjectionPermission {
1141 INJECTION_PERMISSION_UNKNOWN,
1142 INJECTION_PERMISSION_GRANTED,
1143 INJECTION_PERMISSION_DENIED
1144 };
1145
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 // For security reasons, we defer updating the touch state until we are sure that
1147 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 int32_t displayId = entry->displayId;
1149 int32_t action = entry->action;
1150 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1151
1152 // Update the touch state as needed based on the properties of the touch event.
1153 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1154 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1155 sp<InputWindowHandle> newHoverWindowHandle;
1156
Jeff Brownf086ddb2014-02-11 14:28:48 -08001157 // Copy current touch state into mTempTouchState.
1158 // This state is always reset at the end of this function, so if we don't find state
1159 // for the specified display then our initial state will be empty.
1160 const TouchState* oldState = NULL;
1161 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1162 if (oldStateIndex >= 0) {
1163 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1164 mTempTouchState.copyFrom(*oldState);
1165 }
1166
1167 bool isSplit = mTempTouchState.split;
1168 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1169 && (mTempTouchState.deviceId != entry->deviceId
1170 || mTempTouchState.source != entry->source
1171 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1173 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1174 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1175 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1176 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1177 || isHoverAction);
1178 bool wrongDevice = false;
1179 if (newGesture) {
1180 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001181 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182#if DEBUG_FOCUS
1183 ALOGD("Dropping event because a pointer for a different device is already down.");
1184#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001185 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1187 switchedDevice = false;
1188 wrongDevice = true;
1189 goto Failed;
1190 }
1191 mTempTouchState.reset();
1192 mTempTouchState.down = down;
1193 mTempTouchState.deviceId = entry->deviceId;
1194 mTempTouchState.source = entry->source;
1195 mTempTouchState.displayId = displayId;
1196 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001197 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1198#if DEBUG_FOCUS
1199 ALOGI("Dropping move event because a pointer for a different device is already active.");
1200#endif
1201 // TODO: test multiple simultaneous input streams.
1202 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1203 switchedDevice = false;
1204 wrongDevice = true;
1205 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
1207
1208 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1209 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1210
1211 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1212 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1213 getAxisValue(AMOTION_EVENT_AXIS_X));
1214 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1215 getAxisValue(AMOTION_EVENT_AXIS_Y));
1216 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 bool isTouchModal = false;
1218
1219 // Traverse windows from front to back to find touched window and outside targets.
1220 size_t numWindows = mWindowHandles.size();
1221 for (size_t i = 0; i < numWindows; i++) {
1222 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1223 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1224 if (windowInfo->displayId != displayId) {
1225 continue; // wrong display
1226 }
1227
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 int32_t flags = windowInfo->layoutParamsFlags;
1229 if (windowInfo->visible) {
1230 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1231 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1232 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1233 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001234 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 break; // found touched window, exit window loop
1236 }
1237 }
1238
1239 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1240 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001242 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 }
1244 }
1245 }
1246
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 // Figure out whether splitting will be allowed for this window.
1248 if (newTouchedWindowHandle != NULL
1249 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1250 // New window supports splitting.
1251 isSplit = true;
1252 } else if (isSplit) {
1253 // New window does not support splitting but we have already split events.
1254 // Ignore the new window.
1255 newTouchedWindowHandle = NULL;
1256 }
1257
1258 // Handle the case where we did not find a window.
1259 if (newTouchedWindowHandle == NULL) {
1260 // Try to assign the pointer to the first foreground window we find, if there is one.
1261 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1262 if (newTouchedWindowHandle == NULL) {
1263 ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y);
1264 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1265 goto Failed;
1266 }
1267 }
1268
1269 // Set target flags.
1270 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1271 if (isSplit) {
1272 targetFlags |= InputTarget::FLAG_SPLIT;
1273 }
1274 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1275 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001276 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1277 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 }
1279
1280 // Update hover state.
1281 if (isHoverAction) {
1282 newHoverWindowHandle = newTouchedWindowHandle;
1283 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1284 newHoverWindowHandle = mLastHoverWindowHandle;
1285 }
1286
1287 // Update the temporary touch state.
1288 BitSet32 pointerIds;
1289 if (isSplit) {
1290 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1291 pointerIds.markBit(pointerId);
1292 }
1293 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1294 } else {
1295 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1296
1297 // If the pointer is not currently down, then ignore the event.
1298 if (! mTempTouchState.down) {
1299#if DEBUG_FOCUS
1300 ALOGD("Dropping event because the pointer is not down or we previously "
1301 "dropped the pointer down event.");
1302#endif
1303 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1304 goto Failed;
1305 }
1306
1307 // Check whether touches should slip outside of the current foreground window.
1308 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1309 && entry->pointerCount == 1
1310 && mTempTouchState.isSlippery()) {
1311 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1312 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1313
1314 sp<InputWindowHandle> oldTouchedWindowHandle =
1315 mTempTouchState.getFirstForegroundWindowHandle();
1316 sp<InputWindowHandle> newTouchedWindowHandle =
1317 findTouchedWindowAtLocked(displayId, x, y);
1318 if (oldTouchedWindowHandle != newTouchedWindowHandle
1319 && newTouchedWindowHandle != NULL) {
1320#if DEBUG_FOCUS
1321 ALOGD("Touch is slipping out of window %s into window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001322 oldTouchedWindowHandle->getName().c_str(),
1323 newTouchedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324#endif
1325 // Make a slippery exit from the old window.
1326 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1327 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1328
1329 // Make a slippery entrance into the new window.
1330 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1331 isSplit = true;
1332 }
1333
1334 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1335 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1336 if (isSplit) {
1337 targetFlags |= InputTarget::FLAG_SPLIT;
1338 }
1339 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1340 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1341 }
1342
1343 BitSet32 pointerIds;
1344 if (isSplit) {
1345 pointerIds.markBit(entry->pointerProperties[0].id);
1346 }
1347 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1348 }
1349 }
1350 }
1351
1352 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1353 // Let the previous window know that the hover sequence is over.
1354 if (mLastHoverWindowHandle != NULL) {
1355#if DEBUG_HOVER
1356 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001357 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358#endif
1359 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1360 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1361 }
1362
1363 // Let the new window know that the hover sequence is starting.
1364 if (newHoverWindowHandle != NULL) {
1365#if DEBUG_HOVER
1366 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001367 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001368#endif
1369 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1370 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1371 }
1372 }
1373
1374 // Check permission to inject into all touched foreground windows and ensure there
1375 // is at least one touched foreground window.
1376 {
1377 bool haveForegroundWindow = false;
1378 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1379 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1380 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1381 haveForegroundWindow = true;
1382 if (! checkInjectionPermission(touchedWindow.windowHandle,
1383 entry->injectionState)) {
1384 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1385 injectionPermission = INJECTION_PERMISSION_DENIED;
1386 goto Failed;
1387 }
1388 }
1389 }
1390 if (! haveForegroundWindow) {
1391#if DEBUG_FOCUS
1392 ALOGD("Dropping event because there is no touched foreground window to receive it.");
1393#endif
1394 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1395 goto Failed;
1396 }
1397
1398 // Permission granted to injection into all touched foreground windows.
1399 injectionPermission = INJECTION_PERMISSION_GRANTED;
1400 }
1401
1402 // Check whether windows listening for outside touches are owned by the same UID. If it is
1403 // set the policy flag that we will not reveal coordinate information to this window.
1404 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1405 sp<InputWindowHandle> foregroundWindowHandle =
1406 mTempTouchState.getFirstForegroundWindowHandle();
1407 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1408 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1409 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1410 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1411 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1412 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1413 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1414 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1415 }
1416 }
1417 }
1418 }
1419
1420 // Ensure all touched foreground windows are ready for new input.
1421 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1422 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1423 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001424 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001425 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001426 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001427 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001429 NULL, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430 goto Unresponsive;
1431 }
1432 }
1433 }
1434
1435 // If this is the first pointer going down and the touched window has a wallpaper
1436 // then also add the touched wallpaper windows so they are locked in for the duration
1437 // of the touch gesture.
1438 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1439 // engine only supports touch events. We would need to add a mechanism similar
1440 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1441 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1442 sp<InputWindowHandle> foregroundWindowHandle =
1443 mTempTouchState.getFirstForegroundWindowHandle();
1444 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
1445 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1446 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1447 const InputWindowInfo* info = windowHandle->getInfo();
1448 if (info->displayId == displayId
1449 && windowHandle->getInfo()->layoutParamsType
1450 == InputWindowInfo::TYPE_WALLPAPER) {
1451 mTempTouchState.addOrUpdateWindow(windowHandle,
1452 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001453 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001454 | InputTarget::FLAG_DISPATCH_AS_IS,
1455 BitSet32(0));
1456 }
1457 }
1458 }
1459 }
1460
1461 // Success! Output targets.
1462 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1463
1464 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1465 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1466 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1467 touchedWindow.pointerIds, inputTargets);
1468 }
1469
1470 // Drop the outside or hover touch windows since we will not care about them
1471 // in the next iteration.
1472 mTempTouchState.filterNonAsIsTouchWindows();
1473
1474Failed:
1475 // Check injection permission once and for all.
1476 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
1477 if (checkInjectionPermission(NULL, entry->injectionState)) {
1478 injectionPermission = INJECTION_PERMISSION_GRANTED;
1479 } else {
1480 injectionPermission = INJECTION_PERMISSION_DENIED;
1481 }
1482 }
1483
1484 // Update final pieces of touch state if the injector had permission.
1485 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1486 if (!wrongDevice) {
1487 if (switchedDevice) {
1488#if DEBUG_FOCUS
1489 ALOGD("Conflicting pointer actions: Switched to a different device.");
1490#endif
1491 *outConflictingPointerActions = true;
1492 }
1493
1494 if (isHoverAction) {
1495 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001496 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497#if DEBUG_FOCUS
1498 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1499#endif
1500 *outConflictingPointerActions = true;
1501 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001502 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1504 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001505 mTempTouchState.deviceId = entry->deviceId;
1506 mTempTouchState.source = entry->source;
1507 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 }
1509 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1510 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1511 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001512 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1514 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001515 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516#if DEBUG_FOCUS
1517 ALOGD("Conflicting pointer actions: Down received while already down.");
1518#endif
1519 *outConflictingPointerActions = true;
1520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001521 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1522 // One pointer went up.
1523 if (isSplit) {
1524 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1525 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1526
1527 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1528 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1529 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1530 touchedWindow.pointerIds.clearBit(pointerId);
1531 if (touchedWindow.pointerIds.isEmpty()) {
1532 mTempTouchState.windows.removeAt(i);
1533 continue;
1534 }
1535 }
1536 i += 1;
1537 }
1538 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001539 }
1540
1541 // Save changes unless the action was scroll in which case the temporary touch
1542 // state was only valid for this one action.
1543 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1544 if (mTempTouchState.displayId >= 0) {
1545 if (oldStateIndex >= 0) {
1546 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1547 } else {
1548 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1549 }
1550 } else if (oldStateIndex >= 0) {
1551 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 }
1554
1555 // Update hover state.
1556 mLastHoverWindowHandle = newHoverWindowHandle;
1557 }
1558 } else {
1559#if DEBUG_FOCUS
1560 ALOGD("Not updating touch focus because injection was denied.");
1561#endif
1562 }
1563
1564Unresponsive:
1565 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1566 mTempTouchState.reset();
1567
1568 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1569 updateDispatchStatisticsLocked(currentTime, entry,
1570 injectionResult, timeSpentWaitingForApplication);
1571#if DEBUG_FOCUS
1572 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1573 "timeSpentWaitingForApplication=%0.1fms",
1574 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1575#endif
1576 return injectionResult;
1577}
1578
1579void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1580 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1581 inputTargets.push();
1582
1583 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1584 InputTarget& target = inputTargets.editTop();
1585 target.inputChannel = windowInfo->inputChannel;
1586 target.flags = targetFlags;
1587 target.xOffset = - windowInfo->frameLeft;
1588 target.yOffset = - windowInfo->frameTop;
1589 target.scaleFactor = windowInfo->scaleFactor;
1590 target.pointerIds = pointerIds;
1591}
1592
1593void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
1594 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1595 inputTargets.push();
1596
1597 InputTarget& target = inputTargets.editTop();
1598 target.inputChannel = mMonitoringChannels[i];
1599 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1600 target.xOffset = 0;
1601 target.yOffset = 0;
1602 target.pointerIds.clear();
1603 target.scaleFactor = 1.0f;
1604 }
1605}
1606
1607bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1608 const InjectionState* injectionState) {
1609 if (injectionState
1610 && (windowHandle == NULL
1611 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1612 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1613 if (windowHandle != NULL) {
1614 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1615 "owned by uid %d",
1616 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001617 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001618 windowHandle->getInfo()->ownerUid);
1619 } else {
1620 ALOGW("Permission denied: injecting event from pid %d uid %d",
1621 injectionState->injectorPid, injectionState->injectorUid);
1622 }
1623 return false;
1624 }
1625 return true;
1626}
1627
1628bool InputDispatcher::isWindowObscuredAtPointLocked(
1629 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1630 int32_t displayId = windowHandle->getInfo()->displayId;
1631 size_t numWindows = mWindowHandles.size();
1632 for (size_t i = 0; i < numWindows; i++) {
1633 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1634 if (otherHandle == windowHandle) {
1635 break;
1636 }
1637
1638 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1639 if (otherInfo->displayId == displayId
1640 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1641 && otherInfo->frameContainsPoint(x, y)) {
1642 return true;
1643 }
1644 }
1645 return false;
1646}
1647
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001648
1649bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1650 int32_t displayId = windowHandle->getInfo()->displayId;
1651 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1652 size_t numWindows = mWindowHandles.size();
1653 for (size_t i = 0; i < numWindows; i++) {
1654 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1655 if (otherHandle == windowHandle) {
1656 break;
1657 }
1658
1659 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1660 if (otherInfo->displayId == displayId
1661 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1662 && otherInfo->overlaps(windowInfo)) {
1663 return true;
1664 }
1665 }
1666 return false;
1667}
1668
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001669std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001670 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1671 const char* targetType) {
1672 // If the window is paused then keep waiting.
1673 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001674 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001675 }
1676
1677 // If the window's connection is not registered then keep waiting.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brownffb49772014-10-10 19:01:34 -07001679 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001680 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001681 "registered with the input dispatcher. The window may be in the process "
1682 "of being removed.", targetType);
1683 }
1684
1685 // If the connection is dead then keep waiting.
1686 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1687 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001688 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001689 "The window may be in the process of being removed.", targetType,
1690 connection->getStatusLabel());
1691 }
1692
1693 // If the connection is backed up then keep waiting.
1694 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001695 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001696 "Outbound queue length: %d. Wait queue length: %d.",
1697 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1698 }
1699
1700 // Ensure that the dispatch queues aren't too far backed up for this event.
1701 if (eventEntry->type == EventEntry::TYPE_KEY) {
1702 // If the event is a key event, then we must wait for all previous events to
1703 // complete before delivering it because previous events may have the
1704 // side-effect of transferring focus to a different window and we want to
1705 // ensure that the following keys are sent to the new window.
1706 //
1707 // Suppose the user touches a button in a window then immediately presses "A".
1708 // If the button causes a pop-up window to appear then we want to ensure that
1709 // the "A" key is delivered to the new pop-up window. This is because users
1710 // often anticipate pending UI changes when typing on a keyboard.
1711 // To obtain this behavior, we must serialize key events with respect to all
1712 // prior input events.
1713 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001714 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001715 "finished processing all of the input events that were previously "
1716 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1717 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001718 }
Jeff Brownffb49772014-10-10 19:01:34 -07001719 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720 // Touch events can always be sent to a window immediately because the user intended
1721 // to touch whatever was visible at the time. Even if focus changes or a new
1722 // window appears moments later, the touch event was meant to be delivered to
1723 // whatever window happened to be on screen at the time.
1724 //
1725 // Generic motion events, such as trackball or joystick events are a little trickier.
1726 // Like key events, generic motion events are delivered to the focused window.
1727 // Unlike key events, generic motion events don't tend to transfer focus to other
1728 // windows and it is not important for them to be serialized. So we prefer to deliver
1729 // generic motion events as soon as possible to improve efficiency and reduce lag
1730 // through batching.
1731 //
1732 // The one case where we pause input event delivery is when the wait queue is piling
1733 // up with lots of events because the application is not responding.
1734 // This condition ensures that ANRs are detected reliably.
1735 if (!connection->waitQueue.isEmpty()
1736 && currentTime >= connection->waitQueue.head->deliveryTime
1737 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001738 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001739 "finished processing certain input events that were delivered to it over "
1740 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1741 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1742 connection->waitQueue.count(),
1743 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 }
1745 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001746 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001747}
1748
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001749std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 const sp<InputApplicationHandle>& applicationHandle,
1751 const sp<InputWindowHandle>& windowHandle) {
1752 if (applicationHandle != NULL) {
1753 if (windowHandle != NULL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001754 std::string label(applicationHandle->getName());
1755 label += " - ";
1756 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757 return label;
1758 } else {
1759 return applicationHandle->getName();
1760 }
1761 } else if (windowHandle != NULL) {
1762 return windowHandle->getName();
1763 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001764 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 }
1766}
1767
1768void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
1769 if (mFocusedWindowHandle != NULL) {
1770 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1771 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1772#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001773 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774#endif
1775 return;
1776 }
1777 }
1778
1779 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1780 switch (eventEntry->type) {
1781 case EventEntry::TYPE_MOTION: {
1782 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1783 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1784 return;
1785 }
1786
1787 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1788 eventType = USER_ACTIVITY_EVENT_TOUCH;
1789 }
1790 break;
1791 }
1792 case EventEntry::TYPE_KEY: {
1793 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1794 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1795 return;
1796 }
1797 eventType = USER_ACTIVITY_EVENT_BUTTON;
1798 break;
1799 }
1800 }
1801
1802 CommandEntry* commandEntry = postCommandLocked(
1803 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1804 commandEntry->eventTime = eventEntry->eventTime;
1805 commandEntry->userActivityEventType = eventType;
1806}
1807
1808void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1809 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1810#if DEBUG_DISPATCH_CYCLE
1811 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1812 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1813 "pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001814 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815 inputTarget->xOffset, inputTarget->yOffset,
1816 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1817#endif
1818
1819 // Skip this event if the connection status is not normal.
1820 // We don't want to enqueue additional outbound events if the connection is broken.
1821 if (connection->status != Connection::STATUS_NORMAL) {
1822#if DEBUG_DISPATCH_CYCLE
1823 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001824 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001825#endif
1826 return;
1827 }
1828
1829 // Split a motion event if needed.
1830 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1831 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1832
1833 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1834 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1835 MotionEntry* splitMotionEntry = splitMotionEvent(
1836 originalMotionEntry, inputTarget->pointerIds);
1837 if (!splitMotionEntry) {
1838 return; // split event was dropped
1839 }
1840#if DEBUG_FOCUS
1841 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001842 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1844#endif
1845 enqueueDispatchEntriesLocked(currentTime, connection,
1846 splitMotionEntry, inputTarget);
1847 splitMotionEntry->release();
1848 return;
1849 }
1850 }
1851
1852 // Not splitting. Enqueue dispatch entries for the event as is.
1853 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1854}
1855
1856void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1857 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1858 bool wasEmpty = connection->outboundQueue.isEmpty();
1859
1860 // Enqueue dispatch entries for the requested modes.
1861 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1862 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1863 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1864 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1865 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1866 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1867 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1868 InputTarget::FLAG_DISPATCH_AS_IS);
1869 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1870 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1871 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1872 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1873
1874 // If the outbound queue was previously empty, start the dispatch cycle going.
1875 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1876 startDispatchCycleLocked(currentTime, connection);
1877 }
1878}
1879
1880void InputDispatcher::enqueueDispatchEntryLocked(
1881 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1882 int32_t dispatchMode) {
1883 int32_t inputTargetFlags = inputTarget->flags;
1884 if (!(inputTargetFlags & dispatchMode)) {
1885 return;
1886 }
1887 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1888
1889 // This is a new event.
1890 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1891 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1892 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1893 inputTarget->scaleFactor);
1894
1895 // Apply target flags and update the connection's input state.
1896 switch (eventEntry->type) {
1897 case EventEntry::TYPE_KEY: {
1898 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1899 dispatchEntry->resolvedAction = keyEntry->action;
1900 dispatchEntry->resolvedFlags = keyEntry->flags;
1901
1902 if (!connection->inputState.trackKey(keyEntry,
1903 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1904#if DEBUG_DISPATCH_CYCLE
1905 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001906 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001907#endif
1908 delete dispatchEntry;
1909 return; // skip the inconsistent event
1910 }
1911 break;
1912 }
1913
1914 case EventEntry::TYPE_MOTION: {
1915 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1916 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1917 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1918 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1919 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1920 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1921 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1922 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1923 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1924 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1925 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1926 } else {
1927 dispatchEntry->resolvedAction = motionEntry->action;
1928 }
1929 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1930 && !connection->inputState.isHovering(
1931 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
1932#if DEBUG_DISPATCH_CYCLE
1933 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001934 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935#endif
1936 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1937 }
1938
1939 dispatchEntry->resolvedFlags = motionEntry->flags;
1940 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1941 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1942 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001943 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
1944 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946
1947 if (!connection->inputState.trackMotion(motionEntry,
1948 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1949#if DEBUG_DISPATCH_CYCLE
1950 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001951 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952#endif
1953 delete dispatchEntry;
1954 return; // skip the inconsistent event
1955 }
1956 break;
1957 }
1958 }
1959
1960 // Remember that we are waiting for this dispatch to complete.
1961 if (dispatchEntry->hasForegroundTarget()) {
1962 incrementPendingForegroundDispatchesLocked(eventEntry);
1963 }
1964
1965 // Enqueue the dispatch entry.
1966 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1967 traceOutboundQueueLengthLocked(connection);
1968}
1969
1970void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
1971 const sp<Connection>& connection) {
1972#if DEBUG_DISPATCH_CYCLE
1973 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001974 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975#endif
1976
1977 while (connection->status == Connection::STATUS_NORMAL
1978 && !connection->outboundQueue.isEmpty()) {
1979 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
1980 dispatchEntry->deliveryTime = currentTime;
1981
1982 // Publish the event.
1983 status_t status;
1984 EventEntry* eventEntry = dispatchEntry->eventEntry;
1985 switch (eventEntry->type) {
1986 case EventEntry::TYPE_KEY: {
1987 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1988
1989 // Publish the key event.
1990 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
1991 keyEntry->deviceId, keyEntry->source,
1992 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1993 keyEntry->keyCode, keyEntry->scanCode,
1994 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1995 keyEntry->eventTime);
1996 break;
1997 }
1998
1999 case EventEntry::TYPE_MOTION: {
2000 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2001
2002 PointerCoords scaledCoords[MAX_POINTERS];
2003 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2004
2005 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002006 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2008 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002009 float scaleFactor = dispatchEntry->scaleFactor;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010 xOffset = dispatchEntry->xOffset * scaleFactor;
2011 yOffset = dispatchEntry->yOffset * scaleFactor;
2012 if (scaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002013 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014 scaledCoords[i] = motionEntry->pointerCoords[i];
2015 scaledCoords[i].scale(scaleFactor);
2016 }
2017 usingCoords = scaledCoords;
2018 }
2019 } else {
2020 xOffset = 0.0f;
2021 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022
2023 // We don't want the dispatch target to know.
2024 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002025 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002026 scaledCoords[i].clear();
2027 }
2028 usingCoords = scaledCoords;
2029 }
2030 }
2031
2032 // Publish the motion event.
2033 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002034 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002035 dispatchEntry->resolvedAction, motionEntry->actionButton,
2036 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2037 motionEntry->metaState, motionEntry->buttonState,
2038 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 motionEntry->downTime, motionEntry->eventTime,
2040 motionEntry->pointerCount, motionEntry->pointerProperties,
2041 usingCoords);
2042 break;
2043 }
2044
2045 default:
2046 ALOG_ASSERT(false);
2047 return;
2048 }
2049
2050 // Check the result.
2051 if (status) {
2052 if (status == WOULD_BLOCK) {
2053 if (connection->waitQueue.isEmpty()) {
2054 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2055 "This is unexpected because the wait queue is empty, so the pipe "
2056 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002057 "event to it, status=%d", connection->getInputChannelName().c_str(),
2058 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2060 } else {
2061 // Pipe is full and we are waiting for the app to finish process some events
2062 // before sending more events to it.
2063#if DEBUG_DISPATCH_CYCLE
2064 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2065 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002066 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067#endif
2068 connection->inputPublisherBlocked = true;
2069 }
2070 } else {
2071 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002072 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2074 }
2075 return;
2076 }
2077
2078 // Re-enqueue the event on the wait queue.
2079 connection->outboundQueue.dequeue(dispatchEntry);
2080 traceOutboundQueueLengthLocked(connection);
2081 connection->waitQueue.enqueueAtTail(dispatchEntry);
2082 traceWaitQueueLengthLocked(connection);
2083 }
2084}
2085
2086void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2087 const sp<Connection>& connection, uint32_t seq, bool handled) {
2088#if DEBUG_DISPATCH_CYCLE
2089 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002090 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091#endif
2092
2093 connection->inputPublisherBlocked = false;
2094
2095 if (connection->status == Connection::STATUS_BROKEN
2096 || connection->status == Connection::STATUS_ZOMBIE) {
2097 return;
2098 }
2099
2100 // Notify other system components and prepare to start the next dispatch cycle.
2101 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2102}
2103
2104void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2105 const sp<Connection>& connection, bool notify) {
2106#if DEBUG_DISPATCH_CYCLE
2107 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002108 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109#endif
2110
2111 // Clear the dispatch queues.
2112 drainDispatchQueueLocked(&connection->outboundQueue);
2113 traceOutboundQueueLengthLocked(connection);
2114 drainDispatchQueueLocked(&connection->waitQueue);
2115 traceWaitQueueLengthLocked(connection);
2116
2117 // The connection appears to be unrecoverably broken.
2118 // Ignore already broken or zombie connections.
2119 if (connection->status == Connection::STATUS_NORMAL) {
2120 connection->status = Connection::STATUS_BROKEN;
2121
2122 if (notify) {
2123 // Notify other system components.
2124 onDispatchCycleBrokenLocked(currentTime, connection);
2125 }
2126 }
2127}
2128
2129void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2130 while (!queue->isEmpty()) {
2131 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2132 releaseDispatchEntryLocked(dispatchEntry);
2133 }
2134}
2135
2136void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2137 if (dispatchEntry->hasForegroundTarget()) {
2138 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2139 }
2140 delete dispatchEntry;
2141}
2142
2143int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2144 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2145
2146 { // acquire lock
2147 AutoMutex _l(d->mLock);
2148
2149 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2150 if (connectionIndex < 0) {
2151 ALOGE("Received spurious receive callback for unknown input channel. "
2152 "fd=%d, events=0x%x", fd, events);
2153 return 0; // remove the callback
2154 }
2155
2156 bool notify;
2157 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2158 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2159 if (!(events & ALOOPER_EVENT_INPUT)) {
2160 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002161 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 return 1;
2163 }
2164
2165 nsecs_t currentTime = now();
2166 bool gotOne = false;
2167 status_t status;
2168 for (;;) {
2169 uint32_t seq;
2170 bool handled;
2171 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2172 if (status) {
2173 break;
2174 }
2175 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2176 gotOne = true;
2177 }
2178 if (gotOne) {
2179 d->runCommandsLockedInterruptible();
2180 if (status == WOULD_BLOCK) {
2181 return 1;
2182 }
2183 }
2184
2185 notify = status != DEAD_OBJECT || !connection->monitor;
2186 if (notify) {
2187 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002188 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189 }
2190 } else {
2191 // Monitor channels are never explicitly unregistered.
2192 // We do it automatically when the remote endpoint is closed so don't warn
2193 // about them.
2194 notify = !connection->monitor;
2195 if (notify) {
2196 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002197 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 }
2199 }
2200
2201 // Unregister the channel.
2202 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2203 return 0; // remove the callback
2204 } // release lock
2205}
2206
2207void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2208 const CancelationOptions& options) {
2209 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2210 synthesizeCancelationEventsForConnectionLocked(
2211 mConnectionsByFd.valueAt(i), options);
2212 }
2213}
2214
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002215void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2216 const CancelationOptions& options) {
2217 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2218 synthesizeCancelationEventsForInputChannelLocked(mMonitoringChannels[i], options);
2219 }
2220}
2221
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2223 const sp<InputChannel>& channel, const CancelationOptions& options) {
2224 ssize_t index = getConnectionIndexLocked(channel);
2225 if (index >= 0) {
2226 synthesizeCancelationEventsForConnectionLocked(
2227 mConnectionsByFd.valueAt(index), options);
2228 }
2229}
2230
2231void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2232 const sp<Connection>& connection, const CancelationOptions& options) {
2233 if (connection->status == Connection::STATUS_BROKEN) {
2234 return;
2235 }
2236
2237 nsecs_t currentTime = now();
2238
2239 Vector<EventEntry*> cancelationEvents;
2240 connection->inputState.synthesizeCancelationEvents(currentTime,
2241 cancelationEvents, options);
2242
2243 if (!cancelationEvents.isEmpty()) {
2244#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002245 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002247 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 options.reason, options.mode);
2249#endif
2250 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2251 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2252 switch (cancelationEventEntry->type) {
2253 case EventEntry::TYPE_KEY:
2254 logOutboundKeyDetailsLocked("cancel - ",
2255 static_cast<KeyEntry*>(cancelationEventEntry));
2256 break;
2257 case EventEntry::TYPE_MOTION:
2258 logOutboundMotionDetailsLocked("cancel - ",
2259 static_cast<MotionEntry*>(cancelationEventEntry));
2260 break;
2261 }
2262
2263 InputTarget target;
2264 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2265 if (windowHandle != NULL) {
2266 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2267 target.xOffset = -windowInfo->frameLeft;
2268 target.yOffset = -windowInfo->frameTop;
2269 target.scaleFactor = windowInfo->scaleFactor;
2270 } else {
2271 target.xOffset = 0;
2272 target.yOffset = 0;
2273 target.scaleFactor = 1.0f;
2274 }
2275 target.inputChannel = connection->inputChannel;
2276 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2277
2278 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2279 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2280
2281 cancelationEventEntry->release();
2282 }
2283
2284 startDispatchCycleLocked(currentTime, connection);
2285 }
2286}
2287
2288InputDispatcher::MotionEntry*
2289InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2290 ALOG_ASSERT(pointerIds.value != 0);
2291
2292 uint32_t splitPointerIndexMap[MAX_POINTERS];
2293 PointerProperties splitPointerProperties[MAX_POINTERS];
2294 PointerCoords splitPointerCoords[MAX_POINTERS];
2295
2296 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2297 uint32_t splitPointerCount = 0;
2298
2299 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2300 originalPointerIndex++) {
2301 const PointerProperties& pointerProperties =
2302 originalMotionEntry->pointerProperties[originalPointerIndex];
2303 uint32_t pointerId = uint32_t(pointerProperties.id);
2304 if (pointerIds.hasBit(pointerId)) {
2305 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2306 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2307 splitPointerCoords[splitPointerCount].copyFrom(
2308 originalMotionEntry->pointerCoords[originalPointerIndex]);
2309 splitPointerCount += 1;
2310 }
2311 }
2312
2313 if (splitPointerCount != pointerIds.count()) {
2314 // This is bad. We are missing some of the pointers that we expected to deliver.
2315 // Most likely this indicates that we received an ACTION_MOVE events that has
2316 // different pointer ids than we expected based on the previous ACTION_DOWN
2317 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2318 // in this way.
2319 ALOGW("Dropping split motion event because the pointer count is %d but "
2320 "we expected there to be %d pointers. This probably means we received "
2321 "a broken sequence of pointer ids from the input device.",
2322 splitPointerCount, pointerIds.count());
2323 return NULL;
2324 }
2325
2326 int32_t action = originalMotionEntry->action;
2327 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2328 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2329 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2330 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2331 const PointerProperties& pointerProperties =
2332 originalMotionEntry->pointerProperties[originalPointerIndex];
2333 uint32_t pointerId = uint32_t(pointerProperties.id);
2334 if (pointerIds.hasBit(pointerId)) {
2335 if (pointerIds.count() == 1) {
2336 // The first/last pointer went down/up.
2337 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2338 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2339 } else {
2340 // A secondary pointer went down/up.
2341 uint32_t splitPointerIndex = 0;
2342 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2343 splitPointerIndex += 1;
2344 }
2345 action = maskedAction | (splitPointerIndex
2346 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2347 }
2348 } else {
2349 // An unrelated pointer changed.
2350 action = AMOTION_EVENT_ACTION_MOVE;
2351 }
2352 }
2353
2354 MotionEntry* splitMotionEntry = new MotionEntry(
2355 originalMotionEntry->eventTime,
2356 originalMotionEntry->deviceId,
2357 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002358 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 originalMotionEntry->policyFlags,
2360 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002361 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 originalMotionEntry->flags,
2363 originalMotionEntry->metaState,
2364 originalMotionEntry->buttonState,
2365 originalMotionEntry->edgeFlags,
2366 originalMotionEntry->xPrecision,
2367 originalMotionEntry->yPrecision,
2368 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002369 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370
2371 if (originalMotionEntry->injectionState) {
2372 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2373 splitMotionEntry->injectionState->refCount += 1;
2374 }
2375
2376 return splitMotionEntry;
2377}
2378
2379void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2380#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002381 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382#endif
2383
2384 bool needWake;
2385 { // acquire lock
2386 AutoMutex _l(mLock);
2387
2388 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2389 needWake = enqueueInboundEventLocked(newEntry);
2390 } // release lock
2391
2392 if (needWake) {
2393 mLooper->wake();
2394 }
2395}
2396
2397void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2398#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002399 ALOGD("notifyKey - eventTime=%" PRId64
2400 ", deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
2401 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 args->eventTime, args->deviceId, args->source, args->policyFlags,
2403 args->action, args->flags, args->keyCode, args->scanCode,
2404 args->metaState, args->downTime);
2405#endif
2406 if (!validateKeyEvent(args->action)) {
2407 return;
2408 }
2409
2410 uint32_t policyFlags = args->policyFlags;
2411 int32_t flags = args->flags;
2412 int32_t metaState = args->metaState;
2413 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2414 policyFlags |= POLICY_FLAG_VIRTUAL;
2415 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 if (policyFlags & POLICY_FLAG_FUNCTION) {
2418 metaState |= AMETA_FUNCTION_ON;
2419 }
2420
2421 policyFlags |= POLICY_FLAG_TRUSTED;
2422
Michael Wright78f24442014-08-06 15:55:28 -07002423 int32_t keyCode = args->keyCode;
2424 if (metaState & AMETA_META_ON && args->action == AKEY_EVENT_ACTION_DOWN) {
2425 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2426 if (keyCode == AKEYCODE_DEL) {
2427 newKeyCode = AKEYCODE_BACK;
2428 } else if (keyCode == AKEYCODE_ENTER) {
2429 newKeyCode = AKEYCODE_HOME;
2430 }
2431 if (newKeyCode != AKEYCODE_UNKNOWN) {
2432 AutoMutex _l(mLock);
2433 struct KeyReplacement replacement = {keyCode, args->deviceId};
2434 mReplacedKeys.add(replacement, newKeyCode);
2435 keyCode = newKeyCode;
Evan Roskye71f0552017-03-21 18:12:36 -07002436 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
Michael Wright78f24442014-08-06 15:55:28 -07002437 }
2438 } else if (args->action == AKEY_EVENT_ACTION_UP) {
2439 // In order to maintain a consistent stream of up and down events, check to see if the key
2440 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2441 // even if the modifier was released between the down and the up events.
2442 AutoMutex _l(mLock);
2443 struct KeyReplacement replacement = {keyCode, args->deviceId};
2444 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2445 if (index >= 0) {
2446 keyCode = mReplacedKeys.valueAt(index);
2447 mReplacedKeys.removeItemsAt(index);
Evan Roskye71f0552017-03-21 18:12:36 -07002448 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
Michael Wright78f24442014-08-06 15:55:28 -07002449 }
2450 }
2451
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 KeyEvent event;
2453 event.initialize(args->deviceId, args->source, args->action,
Michael Wright78f24442014-08-06 15:55:28 -07002454 flags, keyCode, args->scanCode, metaState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002455 args->downTime, args->eventTime);
2456
Michael Wright2b3c3302018-03-02 17:19:13 +00002457 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002459 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2460 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2461 std::to_string(t.duration().count()).c_str());
2462 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 bool needWake;
2465 { // acquire lock
2466 mLock.lock();
2467
2468 if (shouldSendKeyToInputFilterLocked(args)) {
2469 mLock.unlock();
2470
2471 policyFlags |= POLICY_FLAG_FILTERED;
2472 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2473 return; // event was consumed by the filter
2474 }
2475
2476 mLock.lock();
2477 }
2478
2479 int32_t repeatCount = 0;
2480 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2481 args->deviceId, args->source, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002482 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 metaState, repeatCount, args->downTime);
2484
2485 needWake = enqueueInboundEventLocked(newEntry);
2486 mLock.unlock();
2487 } // release lock
2488
2489 if (needWake) {
2490 mLooper->wake();
2491 }
2492}
2493
2494bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2495 return mInputFilterEnabled;
2496}
2497
2498void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2499#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002500 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2501 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002502 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002503 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002504 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002505 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2507 for (uint32_t i = 0; i < args->pointerCount; i++) {
2508 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2509 "x=%f, y=%f, pressure=%f, size=%f, "
2510 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2511 "orientation=%f",
2512 i, args->pointerProperties[i].id,
2513 args->pointerProperties[i].toolType,
2514 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2515 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2516 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2517 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2518 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2519 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2520 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2521 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2522 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2523 }
2524#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002525 if (!validateMotionEvent(args->action, args->actionButton,
2526 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527 return;
2528 }
2529
2530 uint32_t policyFlags = args->policyFlags;
2531 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002532
2533 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002535 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2536 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2537 std::to_string(t.duration().count()).c_str());
2538 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539
2540 bool needWake;
2541 { // acquire lock
2542 mLock.lock();
2543
2544 if (shouldSendMotionToInputFilterLocked(args)) {
2545 mLock.unlock();
2546
2547 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002548 event.initialize(args->deviceId, args->source, args->displayId,
2549 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002550 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2551 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552 args->downTime, args->eventTime,
2553 args->pointerCount, args->pointerProperties, args->pointerCoords);
2554
2555 policyFlags |= POLICY_FLAG_FILTERED;
2556 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2557 return; // event was consumed by the filter
2558 }
2559
2560 mLock.lock();
2561 }
2562
2563 // Just enqueue a new motion event.
2564 MotionEntry* newEntry = new MotionEntry(args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002565 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002566 args->action, args->actionButton, args->flags,
2567 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002569 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570
2571 needWake = enqueueInboundEventLocked(newEntry);
2572 mLock.unlock();
2573 } // release lock
2574
2575 if (needWake) {
2576 mLooper->wake();
2577 }
2578}
2579
2580bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2581 // TODO: support sending secondary display events to input filter
2582 return mInputFilterEnabled && isMainDisplay(args->displayId);
2583}
2584
2585void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2586#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002587 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2588 "switchMask=0x%08x",
2589 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002590#endif
2591
2592 uint32_t policyFlags = args->policyFlags;
2593 policyFlags |= POLICY_FLAG_TRUSTED;
2594 mPolicy->notifySwitch(args->eventTime,
2595 args->switchValues, args->switchMask, policyFlags);
2596}
2597
2598void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2599#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002600 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 args->eventTime, args->deviceId);
2602#endif
2603
2604 bool needWake;
2605 { // acquire lock
2606 AutoMutex _l(mLock);
2607
2608 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2609 needWake = enqueueInboundEventLocked(newEntry);
2610 } // release lock
2611
2612 if (needWake) {
2613 mLooper->wake();
2614 }
2615}
2616
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002617int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2619 uint32_t policyFlags) {
2620#if DEBUG_INBOUND_EVENT_DETAILS
2621 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002622 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2623 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624#endif
2625
2626 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2627
2628 policyFlags |= POLICY_FLAG_INJECTED;
2629 if (hasInjectionPermission(injectorPid, injectorUid)) {
2630 policyFlags |= POLICY_FLAG_TRUSTED;
2631 }
2632
2633 EventEntry* firstInjectedEntry;
2634 EventEntry* lastInjectedEntry;
2635 switch (event->getType()) {
2636 case AINPUT_EVENT_TYPE_KEY: {
2637 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2638 int32_t action = keyEvent->getAction();
2639 if (! validateKeyEvent(action)) {
2640 return INPUT_EVENT_INJECTION_FAILED;
2641 }
2642
2643 int32_t flags = keyEvent->getFlags();
2644 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2645 policyFlags |= POLICY_FLAG_VIRTUAL;
2646 }
2647
2648 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002649 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002651 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2652 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2653 std::to_string(t.duration().count()).c_str());
2654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 }
2656
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 mLock.lock();
2658 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
2659 keyEvent->getDeviceId(), keyEvent->getSource(),
2660 policyFlags, action, flags,
2661 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
2662 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2663 lastInjectedEntry = firstInjectedEntry;
2664 break;
2665 }
2666
2667 case AINPUT_EVENT_TYPE_MOTION: {
2668 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 int32_t action = motionEvent->getAction();
2670 size_t pointerCount = motionEvent->getPointerCount();
2671 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002672 int32_t actionButton = motionEvent->getActionButton();
2673 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674 return INPUT_EVENT_INJECTION_FAILED;
2675 }
2676
2677 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2678 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002679 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002681 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2682 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2683 std::to_string(t.duration().count()).c_str());
2684 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 }
2686
2687 mLock.lock();
2688 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2689 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2690 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002691 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2692 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002693 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 motionEvent->getMetaState(), motionEvent->getButtonState(),
2695 motionEvent->getEdgeFlags(),
2696 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002697 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002698 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2699 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 lastInjectedEntry = firstInjectedEntry;
2701 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2702 sampleEventTimes += 1;
2703 samplePointerCoords += pointerCount;
2704 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002705 motionEvent->getDeviceId(), motionEvent->getSource(),
2706 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002707 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 motionEvent->getMetaState(), motionEvent->getButtonState(),
2709 motionEvent->getEdgeFlags(),
2710 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002711 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002712 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2713 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 lastInjectedEntry->next = nextInjectedEntry;
2715 lastInjectedEntry = nextInjectedEntry;
2716 }
2717 break;
2718 }
2719
2720 default:
2721 ALOGW("Cannot inject event of type %d", event->getType());
2722 return INPUT_EVENT_INJECTION_FAILED;
2723 }
2724
2725 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2726 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2727 injectionState->injectionIsAsync = true;
2728 }
2729
2730 injectionState->refCount += 1;
2731 lastInjectedEntry->injectionState = injectionState;
2732
2733 bool needWake = false;
2734 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2735 EventEntry* nextEntry = entry->next;
2736 needWake |= enqueueInboundEventLocked(entry);
2737 entry = nextEntry;
2738 }
2739
2740 mLock.unlock();
2741
2742 if (needWake) {
2743 mLooper->wake();
2744 }
2745
2746 int32_t injectionResult;
2747 { // acquire lock
2748 AutoMutex _l(mLock);
2749
2750 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2751 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2752 } else {
2753 for (;;) {
2754 injectionResult = injectionState->injectionResult;
2755 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2756 break;
2757 }
2758
2759 nsecs_t remainingTimeout = endTime - now();
2760 if (remainingTimeout <= 0) {
2761#if DEBUG_INJECTION
2762 ALOGD("injectInputEvent - Timed out waiting for injection result "
2763 "to become available.");
2764#endif
2765 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2766 break;
2767 }
2768
2769 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2770 }
2771
2772 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2773 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2774 while (injectionState->pendingForegroundDispatches != 0) {
2775#if DEBUG_INJECTION
2776 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2777 injectionState->pendingForegroundDispatches);
2778#endif
2779 nsecs_t remainingTimeout = endTime - now();
2780 if (remainingTimeout <= 0) {
2781#if DEBUG_INJECTION
2782 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2783 "dispatches to finish.");
2784#endif
2785 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2786 break;
2787 }
2788
2789 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2790 }
2791 }
2792 }
2793
2794 injectionState->release();
2795 } // release lock
2796
2797#if DEBUG_INJECTION
2798 ALOGD("injectInputEvent - Finished with result %d. "
2799 "injectorPid=%d, injectorUid=%d",
2800 injectionResult, injectorPid, injectorUid);
2801#endif
2802
2803 return injectionResult;
2804}
2805
2806bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2807 return injectorUid == 0
2808 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2809}
2810
2811void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2812 InjectionState* injectionState = entry->injectionState;
2813 if (injectionState) {
2814#if DEBUG_INJECTION
2815 ALOGD("Setting input event injection result to %d. "
2816 "injectorPid=%d, injectorUid=%d",
2817 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2818#endif
2819
2820 if (injectionState->injectionIsAsync
2821 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2822 // Log the outcome since the injector did not wait for the injection result.
2823 switch (injectionResult) {
2824 case INPUT_EVENT_INJECTION_SUCCEEDED:
2825 ALOGV("Asynchronous input event injection succeeded.");
2826 break;
2827 case INPUT_EVENT_INJECTION_FAILED:
2828 ALOGW("Asynchronous input event injection failed.");
2829 break;
2830 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2831 ALOGW("Asynchronous input event injection permission denied.");
2832 break;
2833 case INPUT_EVENT_INJECTION_TIMED_OUT:
2834 ALOGW("Asynchronous input event injection timed out.");
2835 break;
2836 }
2837 }
2838
2839 injectionState->injectionResult = injectionResult;
2840 mInjectionResultAvailableCondition.broadcast();
2841 }
2842}
2843
2844void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2845 InjectionState* injectionState = entry->injectionState;
2846 if (injectionState) {
2847 injectionState->pendingForegroundDispatches += 1;
2848 }
2849}
2850
2851void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2852 InjectionState* injectionState = entry->injectionState;
2853 if (injectionState) {
2854 injectionState->pendingForegroundDispatches -= 1;
2855
2856 if (injectionState->pendingForegroundDispatches == 0) {
2857 mInjectionSyncFinishedCondition.broadcast();
2858 }
2859 }
2860}
2861
2862sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2863 const sp<InputChannel>& inputChannel) const {
2864 size_t numWindows = mWindowHandles.size();
2865 for (size_t i = 0; i < numWindows; i++) {
2866 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2867 if (windowHandle->getInputChannel() == inputChannel) {
2868 return windowHandle;
2869 }
2870 }
2871 return NULL;
2872}
2873
2874bool InputDispatcher::hasWindowHandleLocked(
2875 const sp<InputWindowHandle>& windowHandle) const {
2876 size_t numWindows = mWindowHandles.size();
2877 for (size_t i = 0; i < numWindows; i++) {
2878 if (mWindowHandles.itemAt(i) == windowHandle) {
2879 return true;
2880 }
2881 }
2882 return false;
2883}
2884
2885void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
2886#if DEBUG_FOCUS
2887 ALOGD("setInputWindows");
2888#endif
2889 { // acquire lock
2890 AutoMutex _l(mLock);
2891
2892 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
2893 mWindowHandles = inputWindowHandles;
2894
2895 sp<InputWindowHandle> newFocusedWindowHandle;
2896 bool foundHoveredWindow = false;
2897 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2898 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2899 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
2900 mWindowHandles.removeAt(i--);
2901 continue;
2902 }
2903 if (windowHandle->getInfo()->hasFocus) {
2904 newFocusedWindowHandle = windowHandle;
2905 }
2906 if (windowHandle == mLastHoverWindowHandle) {
2907 foundHoveredWindow = true;
2908 }
2909 }
2910
2911 if (!foundHoveredWindow) {
2912 mLastHoverWindowHandle = NULL;
2913 }
2914
2915 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2916 if (mFocusedWindowHandle != NULL) {
2917#if DEBUG_FOCUS
2918 ALOGD("Focus left window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002919 mFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920#endif
2921 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2922 if (focusedInputChannel != NULL) {
2923 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2924 "focus left window");
2925 synthesizeCancelationEventsForInputChannelLocked(
2926 focusedInputChannel, options);
2927 }
2928 }
2929 if (newFocusedWindowHandle != NULL) {
2930#if DEBUG_FOCUS
2931 ALOGD("Focus entered window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002932 newFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933#endif
2934 }
2935 mFocusedWindowHandle = newFocusedWindowHandle;
2936 }
2937
Jeff Brownf086ddb2014-02-11 14:28:48 -08002938 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
2939 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
Ivan Lozano96f12992017-11-09 14:45:38 -08002940 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08002941 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
2942 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943#if DEBUG_FOCUS
Jeff Brownf086ddb2014-02-11 14:28:48 -08002944 ALOGD("Touched window was removed: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002945 touchedWindow.windowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08002947 sp<InputChannel> touchedInputChannel =
2948 touchedWindow.windowHandle->getInputChannel();
2949 if (touchedInputChannel != NULL) {
2950 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2951 "touched window was removed");
2952 synthesizeCancelationEventsForInputChannelLocked(
2953 touchedInputChannel, options);
2954 }
Ivan Lozano96f12992017-11-09 14:45:38 -08002955 state.windows.removeAt(i);
2956 } else {
2957 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002959 }
2960 }
2961
2962 // Release information for windows that are no longer present.
2963 // This ensures that unused input channels are released promptly.
2964 // Otherwise, they might stick around until the window handle is destroyed
2965 // which might not happen until the next GC.
2966 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2967 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2968 if (!hasWindowHandleLocked(oldWindowHandle)) {
2969#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002970 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971#endif
2972 oldWindowHandle->releaseInfo();
2973 }
2974 }
2975 } // release lock
2976
2977 // Wake up poll loop since it may need to make new input dispatching choices.
2978 mLooper->wake();
2979}
2980
2981void InputDispatcher::setFocusedApplication(
2982 const sp<InputApplicationHandle>& inputApplicationHandle) {
2983#if DEBUG_FOCUS
2984 ALOGD("setFocusedApplication");
2985#endif
2986 { // acquire lock
2987 AutoMutex _l(mLock);
2988
2989 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
2990 if (mFocusedApplicationHandle != inputApplicationHandle) {
2991 if (mFocusedApplicationHandle != NULL) {
2992 resetANRTimeoutsLocked();
2993 mFocusedApplicationHandle->releaseInfo();
2994 }
2995 mFocusedApplicationHandle = inputApplicationHandle;
2996 }
2997 } else if (mFocusedApplicationHandle != NULL) {
2998 resetANRTimeoutsLocked();
2999 mFocusedApplicationHandle->releaseInfo();
3000 mFocusedApplicationHandle.clear();
3001 }
3002
3003#if DEBUG_FOCUS
3004 //logDispatchStateLocked();
3005#endif
3006 } // release lock
3007
3008 // Wake up poll loop since it may need to make new input dispatching choices.
3009 mLooper->wake();
3010}
3011
3012void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3013#if DEBUG_FOCUS
3014 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3015#endif
3016
3017 bool changed;
3018 { // acquire lock
3019 AutoMutex _l(mLock);
3020
3021 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3022 if (mDispatchFrozen && !frozen) {
3023 resetANRTimeoutsLocked();
3024 }
3025
3026 if (mDispatchEnabled && !enabled) {
3027 resetAndDropEverythingLocked("dispatcher is being disabled");
3028 }
3029
3030 mDispatchEnabled = enabled;
3031 mDispatchFrozen = frozen;
3032 changed = true;
3033 } else {
3034 changed = false;
3035 }
3036
3037#if DEBUG_FOCUS
3038 //logDispatchStateLocked();
3039#endif
3040 } // release lock
3041
3042 if (changed) {
3043 // Wake up poll loop since it may need to make new input dispatching choices.
3044 mLooper->wake();
3045 }
3046}
3047
3048void InputDispatcher::setInputFilterEnabled(bool enabled) {
3049#if DEBUG_FOCUS
3050 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3051#endif
3052
3053 { // acquire lock
3054 AutoMutex _l(mLock);
3055
3056 if (mInputFilterEnabled == enabled) {
3057 return;
3058 }
3059
3060 mInputFilterEnabled = enabled;
3061 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3062 } // release lock
3063
3064 // Wake up poll loop since there might be work to do to drop everything.
3065 mLooper->wake();
3066}
3067
3068bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3069 const sp<InputChannel>& toChannel) {
3070#if DEBUG_FOCUS
3071 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003072 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073#endif
3074 { // acquire lock
3075 AutoMutex _l(mLock);
3076
3077 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3078 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3079 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
3080#if DEBUG_FOCUS
3081 ALOGD("Cannot transfer focus because from or to window not found.");
3082#endif
3083 return false;
3084 }
3085 if (fromWindowHandle == toWindowHandle) {
3086#if DEBUG_FOCUS
3087 ALOGD("Trivial transfer to same window.");
3088#endif
3089 return true;
3090 }
3091 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3092#if DEBUG_FOCUS
3093 ALOGD("Cannot transfer focus because windows are on different displays.");
3094#endif
3095 return false;
3096 }
3097
3098 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003099 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3100 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3101 for (size_t i = 0; i < state.windows.size(); i++) {
3102 const TouchedWindow& touchedWindow = state.windows[i];
3103 if (touchedWindow.windowHandle == fromWindowHandle) {
3104 int32_t oldTargetFlags = touchedWindow.targetFlags;
3105 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106
Jeff Brownf086ddb2014-02-11 14:28:48 -08003107 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108
Jeff Brownf086ddb2014-02-11 14:28:48 -08003109 int32_t newTargetFlags = oldTargetFlags
3110 & (InputTarget::FLAG_FOREGROUND
3111 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3112 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113
Jeff Brownf086ddb2014-02-11 14:28:48 -08003114 found = true;
3115 goto Found;
3116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 }
3118 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003119Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120
3121 if (! found) {
3122#if DEBUG_FOCUS
3123 ALOGD("Focus transfer failed because from window did not have focus.");
3124#endif
3125 return false;
3126 }
3127
3128 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3129 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3130 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3131 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3132 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3133
3134 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3135 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3136 "transferring touch focus from this window to another window");
3137 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3138 }
3139
3140#if DEBUG_FOCUS
3141 logDispatchStateLocked();
3142#endif
3143 } // release lock
3144
3145 // Wake up poll loop since it may need to make new input dispatching choices.
3146 mLooper->wake();
3147 return true;
3148}
3149
3150void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3151#if DEBUG_FOCUS
3152 ALOGD("Resetting and dropping all events (%s).", reason);
3153#endif
3154
3155 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3156 synthesizeCancelationEventsForAllConnectionsLocked(options);
3157
3158 resetKeyRepeatLocked();
3159 releasePendingEventLocked();
3160 drainInboundQueueLocked();
3161 resetANRTimeoutsLocked();
3162
Jeff Brownf086ddb2014-02-11 14:28:48 -08003163 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003165 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166}
3167
3168void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003169 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 dumpDispatchStateLocked(dump);
3171
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003172 std::istringstream stream(dump);
3173 std::string line;
3174
3175 while (std::getline(stream, line, '\n')) {
3176 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 }
3178}
3179
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003180void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3181 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3182 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183
3184 if (mFocusedApplicationHandle != NULL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003185 dump += StringPrintf(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
3186 mFocusedApplicationHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 mFocusedApplicationHandle->getDispatchingTimeout(
3188 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3189 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003190 dump += StringPrintf(INDENT "FocusedApplication: <null>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003192 dump += StringPrintf(INDENT "FocusedWindow: name='%s'\n",
3193 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().c_str() : "<null>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194
Jeff Brownf086ddb2014-02-11 14:28:48 -08003195 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003196 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003197 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3198 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003199 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003200 state.displayId, toString(state.down), toString(state.split),
3201 state.deviceId, state.source);
3202 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003203 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003204 for (size_t i = 0; i < state.windows.size(); i++) {
3205 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003206 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3207 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003208 touchedWindow.pointerIds.value,
3209 touchedWindow.targetFlags);
3210 }
3211 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003212 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003213 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 }
3215 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003216 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 }
3218
3219 if (!mWindowHandles.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003220 dump += INDENT "Windows:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3222 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3223 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3224
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003225 dump += StringPrintf(INDENT2 "%zu: name='%s', displayId=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3227 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3228 "frame=[%d,%d][%d,%d], scale=%f, "
3229 "touchableRegion=",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003230 i, windowInfo->name.c_str(), windowInfo->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 toString(windowInfo->paused),
3232 toString(windowInfo->hasFocus),
3233 toString(windowInfo->hasWallpaper),
3234 toString(windowInfo->visible),
3235 toString(windowInfo->canReceiveKeys),
3236 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3237 windowInfo->layer,
3238 windowInfo->frameLeft, windowInfo->frameTop,
3239 windowInfo->frameRight, windowInfo->frameBottom,
3240 windowInfo->scaleFactor);
3241 dumpRegion(dump, windowInfo->touchableRegion);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003242 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3243 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 windowInfo->ownerPid, windowInfo->ownerUid,
3245 windowInfo->dispatchingTimeout / 1000000.0);
3246 }
3247 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003248 dump += INDENT "Windows: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 }
3250
3251 if (!mMonitoringChannels.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003252 dump += INDENT "MonitoringChannels:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3254 const sp<InputChannel>& channel = mMonitoringChannels[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003255 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 }
3257 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003258 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259 }
3260
3261 nsecs_t currentTime = now();
3262
3263 // Dump recently dispatched or dropped events from oldest to newest.
3264 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003265 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003267 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003269 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270 (currentTime - entry->eventTime) * 0.000001f);
3271 }
3272 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003273 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274 }
3275
3276 // Dump event currently being dispatched.
3277 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003278 dump += INDENT "PendingEvent:\n";
3279 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003281 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3283 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003284 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285 }
3286
3287 // Dump inbound events from oldest to newest.
3288 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003289 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003291 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003292 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003293 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294 (currentTime - entry->eventTime) * 0.000001f);
3295 }
3296 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003297 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298 }
3299
Michael Wright78f24442014-08-06 15:55:28 -07003300 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003301 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003302 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3303 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3304 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003305 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003306 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3307 }
3308 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003309 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003310 }
3311
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003313 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3315 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003316 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003318 i, connection->getInputChannelName().c_str(),
3319 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 connection->getStatusLabel(), toString(connection->monitor),
3321 toString(connection->inputPublisherBlocked));
3322
3323 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003324 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 connection->outboundQueue.count());
3326 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3327 entry = entry->next) {
3328 dump.append(INDENT4);
3329 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003330 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331 entry->targetFlags, entry->resolvedAction,
3332 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3333 }
3334 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003335 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003336 }
3337
3338 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003339 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 connection->waitQueue.count());
3341 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3342 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003343 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003345 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346 "age=%0.1fms, wait=%0.1fms\n",
3347 entry->targetFlags, entry->resolvedAction,
3348 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3349 (currentTime - entry->deliveryTime) * 0.000001f);
3350 }
3351 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003352 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353 }
3354 }
3355 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003356 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 }
3358
3359 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003360 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361 (mAppSwitchDueTime - now()) / 1000000.0);
3362 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003363 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364 }
3365
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003366 dump += INDENT "Configuration:\n";
3367 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003369 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370 mConfig.keyRepeatTimeout * 0.000001f);
3371}
3372
3373status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3374 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
3375#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003376 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003377 toString(monitor));
3378#endif
3379
3380 { // acquire lock
3381 AutoMutex _l(mLock);
3382
3383 if (getConnectionIndexLocked(inputChannel) >= 0) {
3384 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003385 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 return BAD_VALUE;
3387 }
3388
3389 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3390
3391 int fd = inputChannel->getFd();
3392 mConnectionsByFd.add(fd, connection);
3393
3394 if (monitor) {
3395 mMonitoringChannels.push(inputChannel);
3396 }
3397
3398 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3399 } // release lock
3400
3401 // Wake the looper because some connections have changed.
3402 mLooper->wake();
3403 return OK;
3404}
3405
3406status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3407#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003408 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409#endif
3410
3411 { // acquire lock
3412 AutoMutex _l(mLock);
3413
3414 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3415 if (status) {
3416 return status;
3417 }
3418 } // release lock
3419
3420 // Wake the poll loop because removing the connection may have changed the current
3421 // synchronization state.
3422 mLooper->wake();
3423 return OK;
3424}
3425
3426status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3427 bool notify) {
3428 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3429 if (connectionIndex < 0) {
3430 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003431 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 return BAD_VALUE;
3433 }
3434
3435 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3436 mConnectionsByFd.removeItemsAt(connectionIndex);
3437
3438 if (connection->monitor) {
3439 removeMonitorChannelLocked(inputChannel);
3440 }
3441
3442 mLooper->removeFd(inputChannel->getFd());
3443
3444 nsecs_t currentTime = now();
3445 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3446
3447 connection->status = Connection::STATUS_ZOMBIE;
3448 return OK;
3449}
3450
3451void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3452 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3453 if (mMonitoringChannels[i] == inputChannel) {
3454 mMonitoringChannels.removeAt(i);
3455 break;
3456 }
3457 }
3458}
3459
3460ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
3461 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3462 if (connectionIndex >= 0) {
3463 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3464 if (connection->inputChannel.get() == inputChannel.get()) {
3465 return connectionIndex;
3466 }
3467 }
3468
3469 return -1;
3470}
3471
3472void InputDispatcher::onDispatchCycleFinishedLocked(
3473 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3474 CommandEntry* commandEntry = postCommandLocked(
3475 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3476 commandEntry->connection = connection;
3477 commandEntry->eventTime = currentTime;
3478 commandEntry->seq = seq;
3479 commandEntry->handled = handled;
3480}
3481
3482void InputDispatcher::onDispatchCycleBrokenLocked(
3483 nsecs_t currentTime, const sp<Connection>& connection) {
3484 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003485 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486
3487 CommandEntry* commandEntry = postCommandLocked(
3488 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3489 commandEntry->connection = connection;
3490}
3491
3492void InputDispatcher::onANRLocked(
3493 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3494 const sp<InputWindowHandle>& windowHandle,
3495 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3496 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3497 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3498 ALOGI("Application is not responding: %s. "
3499 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003500 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501 dispatchLatency, waitDuration, reason);
3502
3503 // Capture a record of the InputDispatcher state at the time of the ANR.
3504 time_t t = time(NULL);
3505 struct tm tm;
3506 localtime_r(&t, &tm);
3507 char timestr[64];
3508 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3509 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003510 mLastANRState += INDENT "ANR:\n";
3511 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3512 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3513 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3514 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3515 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3516 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 dumpDispatchStateLocked(mLastANRState);
3518
3519 CommandEntry* commandEntry = postCommandLocked(
3520 & InputDispatcher::doNotifyANRLockedInterruptible);
3521 commandEntry->inputApplicationHandle = applicationHandle;
3522 commandEntry->inputWindowHandle = windowHandle;
3523 commandEntry->reason = reason;
3524}
3525
3526void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3527 CommandEntry* commandEntry) {
3528 mLock.unlock();
3529
3530 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3531
3532 mLock.lock();
3533}
3534
3535void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3536 CommandEntry* commandEntry) {
3537 sp<Connection> connection = commandEntry->connection;
3538
3539 if (connection->status != Connection::STATUS_ZOMBIE) {
3540 mLock.unlock();
3541
3542 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3543
3544 mLock.lock();
3545 }
3546}
3547
3548void InputDispatcher::doNotifyANRLockedInterruptible(
3549 CommandEntry* commandEntry) {
3550 mLock.unlock();
3551
3552 nsecs_t newTimeout = mPolicy->notifyANR(
3553 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3554 commandEntry->reason);
3555
3556 mLock.lock();
3557
3558 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3559 commandEntry->inputWindowHandle != NULL
3560 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
3561}
3562
3563void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3564 CommandEntry* commandEntry) {
3565 KeyEntry* entry = commandEntry->keyEntry;
3566
3567 KeyEvent event;
3568 initializeKeyEvent(&event, entry);
3569
3570 mLock.unlock();
3571
Michael Wright2b3c3302018-03-02 17:19:13 +00003572 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3574 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003575 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3576 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3577 std::to_string(t.duration().count()).c_str());
3578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579
3580 mLock.lock();
3581
3582 if (delay < 0) {
3583 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3584 } else if (!delay) {
3585 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3586 } else {
3587 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3588 entry->interceptKeyWakeupTime = now() + delay;
3589 }
3590 entry->release();
3591}
3592
3593void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3594 CommandEntry* commandEntry) {
3595 sp<Connection> connection = commandEntry->connection;
3596 nsecs_t finishTime = commandEntry->eventTime;
3597 uint32_t seq = commandEntry->seq;
3598 bool handled = commandEntry->handled;
3599
3600 // Handle post-event policy actions.
3601 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3602 if (dispatchEntry) {
3603 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3604 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003605 std::string msg =
3606 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003607 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003609 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 }
3611
3612 bool restartEvent;
3613 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3614 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3615 restartEvent = afterKeyEventLockedInterruptible(connection,
3616 dispatchEntry, keyEntry, handled);
3617 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3618 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3619 restartEvent = afterMotionEventLockedInterruptible(connection,
3620 dispatchEntry, motionEntry, handled);
3621 } else {
3622 restartEvent = false;
3623 }
3624
3625 // Dequeue the event and start the next cycle.
3626 // Note that because the lock might have been released, it is possible that the
3627 // contents of the wait queue to have been drained, so we need to double-check
3628 // a few things.
3629 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3630 connection->waitQueue.dequeue(dispatchEntry);
3631 traceWaitQueueLengthLocked(connection);
3632 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3633 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3634 traceOutboundQueueLengthLocked(connection);
3635 } else {
3636 releaseDispatchEntryLocked(dispatchEntry);
3637 }
3638 }
3639
3640 // Start the next dispatch cycle for this connection.
3641 startDispatchCycleLocked(now(), connection);
3642 }
3643}
3644
3645bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3646 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3647 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3648 // Get the fallback key state.
3649 // Clear it out after dispatching the UP.
3650 int32_t originalKeyCode = keyEntry->keyCode;
3651 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3652 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3653 connection->inputState.removeFallbackKey(originalKeyCode);
3654 }
3655
3656 if (handled || !dispatchEntry->hasForegroundTarget()) {
3657 // If the application handles the original key for which we previously
3658 // generated a fallback or if the window is not a foreground window,
3659 // then cancel the associated fallback key, if any.
3660 if (fallbackKeyCode != -1) {
3661 // Dispatch the unhandled key to the policy with the cancel flag.
3662#if DEBUG_OUTBOUND_EVENT_DETAILS
3663 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3664 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3665 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3666 keyEntry->policyFlags);
3667#endif
3668 KeyEvent event;
3669 initializeKeyEvent(&event, keyEntry);
3670 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3671
3672 mLock.unlock();
3673
3674 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3675 &event, keyEntry->policyFlags, &event);
3676
3677 mLock.lock();
3678
3679 // Cancel the fallback key.
3680 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3681 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3682 "application handled the original non-fallback key "
3683 "or is no longer a foreground target, "
3684 "canceling previously dispatched fallback key");
3685 options.keyCode = fallbackKeyCode;
3686 synthesizeCancelationEventsForConnectionLocked(connection, options);
3687 }
3688 connection->inputState.removeFallbackKey(originalKeyCode);
3689 }
3690 } else {
3691 // If the application did not handle a non-fallback key, first check
3692 // that we are in a good state to perform unhandled key event processing
3693 // Then ask the policy what to do with it.
3694 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3695 && keyEntry->repeatCount == 0;
3696 if (fallbackKeyCode == -1 && !initialDown) {
3697#if DEBUG_OUTBOUND_EVENT_DETAILS
3698 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3699 "since this is not an initial down. "
3700 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3701 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3702 keyEntry->policyFlags);
3703#endif
3704 return false;
3705 }
3706
3707 // Dispatch the unhandled key to the policy.
3708#if DEBUG_OUTBOUND_EVENT_DETAILS
3709 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
3710 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3711 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3712 keyEntry->policyFlags);
3713#endif
3714 KeyEvent event;
3715 initializeKeyEvent(&event, keyEntry);
3716
3717 mLock.unlock();
3718
3719 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3720 &event, keyEntry->policyFlags, &event);
3721
3722 mLock.lock();
3723
3724 if (connection->status != Connection::STATUS_NORMAL) {
3725 connection->inputState.removeFallbackKey(originalKeyCode);
3726 return false;
3727 }
3728
3729 // Latch the fallback keycode for this key on an initial down.
3730 // The fallback keycode cannot change at any other point in the lifecycle.
3731 if (initialDown) {
3732 if (fallback) {
3733 fallbackKeyCode = event.getKeyCode();
3734 } else {
3735 fallbackKeyCode = AKEYCODE_UNKNOWN;
3736 }
3737 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3738 }
3739
3740 ALOG_ASSERT(fallbackKeyCode != -1);
3741
3742 // Cancel the fallback key if the policy decides not to send it anymore.
3743 // We will continue to dispatch the key to the policy but we will no
3744 // longer dispatch a fallback key to the application.
3745 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3746 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3747#if DEBUG_OUTBOUND_EVENT_DETAILS
3748 if (fallback) {
3749 ALOGD("Unhandled key event: Policy requested to send key %d"
3750 "as a fallback for %d, but on the DOWN it had requested "
3751 "to send %d instead. Fallback canceled.",
3752 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3753 } else {
3754 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
3755 "but on the DOWN it had requested to send %d. "
3756 "Fallback canceled.",
3757 originalKeyCode, fallbackKeyCode);
3758 }
3759#endif
3760
3761 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3762 "canceling fallback, policy no longer desires it");
3763 options.keyCode = fallbackKeyCode;
3764 synthesizeCancelationEventsForConnectionLocked(connection, options);
3765
3766 fallback = false;
3767 fallbackKeyCode = AKEYCODE_UNKNOWN;
3768 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3769 connection->inputState.setFallbackKey(originalKeyCode,
3770 fallbackKeyCode);
3771 }
3772 }
3773
3774#if DEBUG_OUTBOUND_EVENT_DETAILS
3775 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003776 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003777 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3778 connection->inputState.getFallbackKeys();
3779 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003780 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781 fallbackKeys.valueAt(i));
3782 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003783 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003784 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785 }
3786#endif
3787
3788 if (fallback) {
3789 // Restart the dispatch cycle using the fallback key.
3790 keyEntry->eventTime = event.getEventTime();
3791 keyEntry->deviceId = event.getDeviceId();
3792 keyEntry->source = event.getSource();
3793 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3794 keyEntry->keyCode = fallbackKeyCode;
3795 keyEntry->scanCode = event.getScanCode();
3796 keyEntry->metaState = event.getMetaState();
3797 keyEntry->repeatCount = event.getRepeatCount();
3798 keyEntry->downTime = event.getDownTime();
3799 keyEntry->syntheticRepeat = false;
3800
3801#if DEBUG_OUTBOUND_EVENT_DETAILS
3802 ALOGD("Unhandled key event: Dispatching fallback key. "
3803 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3804 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3805#endif
3806 return true; // restart the event
3807 } else {
3808#if DEBUG_OUTBOUND_EVENT_DETAILS
3809 ALOGD("Unhandled key event: No fallback key.");
3810#endif
3811 }
3812 }
3813 }
3814 return false;
3815}
3816
3817bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3818 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3819 return false;
3820}
3821
3822void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3823 mLock.unlock();
3824
3825 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
3826
3827 mLock.lock();
3828}
3829
3830void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3831 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3832 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3833 entry->downTime, entry->eventTime);
3834}
3835
3836void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3837 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3838 // TODO Write some statistics about how long we spend waiting.
3839}
3840
3841void InputDispatcher::traceInboundQueueLengthLocked() {
3842 if (ATRACE_ENABLED()) {
3843 ATRACE_INT("iq", mInboundQueue.count());
3844 }
3845}
3846
3847void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3848 if (ATRACE_ENABLED()) {
3849 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003850 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851 ATRACE_INT(counterName, connection->outboundQueue.count());
3852 }
3853}
3854
3855void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3856 if (ATRACE_ENABLED()) {
3857 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003858 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859 ATRACE_INT(counterName, connection->waitQueue.count());
3860 }
3861}
3862
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003863void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864 AutoMutex _l(mLock);
3865
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003866 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 dumpDispatchStateLocked(dump);
3868
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003869 if (!mLastANRState.empty()) {
3870 dump += "\nInput Dispatcher State at time of last ANR:\n";
3871 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 }
3873}
3874
3875void InputDispatcher::monitor() {
3876 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3877 mLock.lock();
3878 mLooper->wake();
3879 mDispatcherIsAliveCondition.wait(mLock);
3880 mLock.unlock();
3881}
3882
3883
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884// --- InputDispatcher::InjectionState ---
3885
3886InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3887 refCount(1),
3888 injectorPid(injectorPid), injectorUid(injectorUid),
3889 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3890 pendingForegroundDispatches(0) {
3891}
3892
3893InputDispatcher::InjectionState::~InjectionState() {
3894}
3895
3896void InputDispatcher::InjectionState::release() {
3897 refCount -= 1;
3898 if (refCount == 0) {
3899 delete this;
3900 } else {
3901 ALOG_ASSERT(refCount > 0);
3902 }
3903}
3904
3905
3906// --- InputDispatcher::EventEntry ---
3907
3908InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3909 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3910 injectionState(NULL), dispatchInProgress(false) {
3911}
3912
3913InputDispatcher::EventEntry::~EventEntry() {
3914 releaseInjectionState();
3915}
3916
3917void InputDispatcher::EventEntry::release() {
3918 refCount -= 1;
3919 if (refCount == 0) {
3920 delete this;
3921 } else {
3922 ALOG_ASSERT(refCount > 0);
3923 }
3924}
3925
3926void InputDispatcher::EventEntry::releaseInjectionState() {
3927 if (injectionState) {
3928 injectionState->release();
3929 injectionState = NULL;
3930 }
3931}
3932
3933
3934// --- InputDispatcher::ConfigurationChangedEntry ---
3935
3936InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3937 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3938}
3939
3940InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3941}
3942
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003943void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
3944 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945}
3946
3947
3948// --- InputDispatcher::DeviceResetEntry ---
3949
3950InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3951 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3952 deviceId(deviceId) {
3953}
3954
3955InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3956}
3957
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003958void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
3959 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960 deviceId, policyFlags);
3961}
3962
3963
3964// --- InputDispatcher::KeyEntry ---
3965
3966InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
3967 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
3968 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3969 int32_t repeatCount, nsecs_t downTime) :
3970 EventEntry(TYPE_KEY, eventTime, policyFlags),
3971 deviceId(deviceId), source(source), action(action), flags(flags),
3972 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3973 repeatCount(repeatCount), downTime(downTime),
3974 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3975 interceptKeyWakeupTime(0) {
3976}
3977
3978InputDispatcher::KeyEntry::~KeyEntry() {
3979}
3980
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003981void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
3982 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, action=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
3984 "repeatCount=%d), policyFlags=0x%08x",
3985 deviceId, source, action, flags, keyCode, scanCode, metaState,
3986 repeatCount, policyFlags);
3987}
3988
3989void InputDispatcher::KeyEntry::recycle() {
3990 releaseInjectionState();
3991
3992 dispatchInProgress = false;
3993 syntheticRepeat = false;
3994 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
3995 interceptKeyWakeupTime = 0;
3996}
3997
3998
3999// --- InputDispatcher::MotionEntry ---
4000
Michael Wright7b159c92015-05-14 14:48:03 +01004001InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004002 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4003 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004004 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4005 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004006 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004007 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4008 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4010 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004011 deviceId(deviceId), source(source), displayId(displayId), action(action),
4012 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004013 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004014 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015 for (uint32_t i = 0; i < pointerCount; i++) {
4016 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4017 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004018 if (xOffset || yOffset) {
4019 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004021 }
4022}
4023
4024InputDispatcher::MotionEntry::~MotionEntry() {
4025}
4026
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004027void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004028 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
4029 ", action=%d, actionButton=0x%08x, "
Michael Wright7b159c92015-05-14 14:48:03 +01004030 "flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004031 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
4032 deviceId, source, displayId, action, actionButton, flags, metaState, buttonState,
4033 edgeFlags, xPrecision, yPrecision);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034 for (uint32_t i = 0; i < pointerCount; i++) {
4035 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004036 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004038 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004039 pointerCoords[i].getX(), pointerCoords[i].getY());
4040 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004041 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042}
4043
4044
4045// --- InputDispatcher::DispatchEntry ---
4046
4047volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4048
4049InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4050 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4051 seq(nextSeq()),
4052 eventEntry(eventEntry), targetFlags(targetFlags),
4053 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4054 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4055 eventEntry->refCount += 1;
4056}
4057
4058InputDispatcher::DispatchEntry::~DispatchEntry() {
4059 eventEntry->release();
4060}
4061
4062uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4063 // Sequence number 0 is reserved and will never be returned.
4064 uint32_t seq;
4065 do {
4066 seq = android_atomic_inc(&sNextSeqAtomic);
4067 } while (!seq);
4068 return seq;
4069}
4070
4071
4072// --- InputDispatcher::InputState ---
4073
4074InputDispatcher::InputState::InputState() {
4075}
4076
4077InputDispatcher::InputState::~InputState() {
4078}
4079
4080bool InputDispatcher::InputState::isNeutral() const {
4081 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4082}
4083
4084bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4085 int32_t displayId) const {
4086 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4087 const MotionMemento& memento = mMotionMementos.itemAt(i);
4088 if (memento.deviceId == deviceId
4089 && memento.source == source
4090 && memento.displayId == displayId
4091 && memento.hovering) {
4092 return true;
4093 }
4094 }
4095 return false;
4096}
4097
4098bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4099 int32_t action, int32_t flags) {
4100 switch (action) {
4101 case AKEY_EVENT_ACTION_UP: {
4102 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4103 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4104 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4105 mFallbackKeys.removeItemsAt(i);
4106 } else {
4107 i += 1;
4108 }
4109 }
4110 }
4111 ssize_t index = findKeyMemento(entry);
4112 if (index >= 0) {
4113 mKeyMementos.removeAt(index);
4114 return true;
4115 }
4116 /* FIXME: We can't just drop the key up event because that prevents creating
4117 * popup windows that are automatically shown when a key is held and then
4118 * dismissed when the key is released. The problem is that the popup will
4119 * not have received the original key down, so the key up will be considered
4120 * to be inconsistent with its observed state. We could perhaps handle this
4121 * by synthesizing a key down but that will cause other problems.
4122 *
4123 * So for now, allow inconsistent key up events to be dispatched.
4124 *
4125#if DEBUG_OUTBOUND_EVENT_DETAILS
4126 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4127 "keyCode=%d, scanCode=%d",
4128 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4129#endif
4130 return false;
4131 */
4132 return true;
4133 }
4134
4135 case AKEY_EVENT_ACTION_DOWN: {
4136 ssize_t index = findKeyMemento(entry);
4137 if (index >= 0) {
4138 mKeyMementos.removeAt(index);
4139 }
4140 addKeyMemento(entry, flags);
4141 return true;
4142 }
4143
4144 default:
4145 return true;
4146 }
4147}
4148
4149bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4150 int32_t action, int32_t flags) {
4151 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4152 switch (actionMasked) {
4153 case AMOTION_EVENT_ACTION_UP:
4154 case AMOTION_EVENT_ACTION_CANCEL: {
4155 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4156 if (index >= 0) {
4157 mMotionMementos.removeAt(index);
4158 return true;
4159 }
4160#if DEBUG_OUTBOUND_EVENT_DETAILS
4161 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004162 "displayId=%" PRId32 ", actionMasked=%d",
4163 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164#endif
4165 return false;
4166 }
4167
4168 case AMOTION_EVENT_ACTION_DOWN: {
4169 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4170 if (index >= 0) {
4171 mMotionMementos.removeAt(index);
4172 }
4173 addMotionMemento(entry, flags, false /*hovering*/);
4174 return true;
4175 }
4176
4177 case AMOTION_EVENT_ACTION_POINTER_UP:
4178 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4179 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004180 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4181 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4182 // generate cancellation events for these since they're based in relative rather than
4183 // absolute units.
4184 return true;
4185 }
4186
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004188
4189 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4190 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4191 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4192 // other value and we need to track the motion so we can send cancellation events for
4193 // anything generating fallback events (e.g. DPad keys for joystick movements).
4194 if (index >= 0) {
4195 if (entry->pointerCoords[0].isEmpty()) {
4196 mMotionMementos.removeAt(index);
4197 } else {
4198 MotionMemento& memento = mMotionMementos.editItemAt(index);
4199 memento.setPointers(entry);
4200 }
4201 } else if (!entry->pointerCoords[0].isEmpty()) {
4202 addMotionMemento(entry, flags, false /*hovering*/);
4203 }
4204
4205 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4206 return true;
4207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 if (index >= 0) {
4209 MotionMemento& memento = mMotionMementos.editItemAt(index);
4210 memento.setPointers(entry);
4211 return true;
4212 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213#if DEBUG_OUTBOUND_EVENT_DETAILS
4214 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004215 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4216 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217#endif
4218 return false;
4219 }
4220
4221 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4222 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4223 if (index >= 0) {
4224 mMotionMementos.removeAt(index);
4225 return true;
4226 }
4227#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004228 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4229 "displayId=%" PRId32,
4230 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231#endif
4232 return false;
4233 }
4234
4235 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4236 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4237 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4238 if (index >= 0) {
4239 mMotionMementos.removeAt(index);
4240 }
4241 addMotionMemento(entry, flags, true /*hovering*/);
4242 return true;
4243 }
4244
4245 default:
4246 return true;
4247 }
4248}
4249
4250ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4251 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4252 const KeyMemento& memento = mKeyMementos.itemAt(i);
4253 if (memento.deviceId == entry->deviceId
4254 && memento.source == entry->source
4255 && memento.keyCode == entry->keyCode
4256 && memento.scanCode == entry->scanCode) {
4257 return i;
4258 }
4259 }
4260 return -1;
4261}
4262
4263ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4264 bool hovering) const {
4265 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4266 const MotionMemento& memento = mMotionMementos.itemAt(i);
4267 if (memento.deviceId == entry->deviceId
4268 && memento.source == entry->source
4269 && memento.displayId == entry->displayId
4270 && memento.hovering == hovering) {
4271 return i;
4272 }
4273 }
4274 return -1;
4275}
4276
4277void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4278 mKeyMementos.push();
4279 KeyMemento& memento = mKeyMementos.editTop();
4280 memento.deviceId = entry->deviceId;
4281 memento.source = entry->source;
4282 memento.keyCode = entry->keyCode;
4283 memento.scanCode = entry->scanCode;
4284 memento.metaState = entry->metaState;
4285 memento.flags = flags;
4286 memento.downTime = entry->downTime;
4287 memento.policyFlags = entry->policyFlags;
4288}
4289
4290void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4291 int32_t flags, bool hovering) {
4292 mMotionMementos.push();
4293 MotionMemento& memento = mMotionMementos.editTop();
4294 memento.deviceId = entry->deviceId;
4295 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004296 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 memento.flags = flags;
4298 memento.xPrecision = entry->xPrecision;
4299 memento.yPrecision = entry->yPrecision;
4300 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 memento.setPointers(entry);
4302 memento.hovering = hovering;
4303 memento.policyFlags = entry->policyFlags;
4304}
4305
4306void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4307 pointerCount = entry->pointerCount;
4308 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4309 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4310 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4311 }
4312}
4313
4314void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4315 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4316 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4317 const KeyMemento& memento = mKeyMementos.itemAt(i);
4318 if (shouldCancelKey(memento, options)) {
4319 outEvents.push(new KeyEntry(currentTime,
4320 memento.deviceId, memento.source, memento.policyFlags,
4321 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4322 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4323 }
4324 }
4325
4326 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4327 const MotionMemento& memento = mMotionMementos.itemAt(i);
4328 if (shouldCancelMotion(memento, options)) {
4329 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004330 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 memento.hovering
4332 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4333 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004334 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004336 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4337 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 }
4339 }
4340}
4341
4342void InputDispatcher::InputState::clear() {
4343 mKeyMementos.clear();
4344 mMotionMementos.clear();
4345 mFallbackKeys.clear();
4346}
4347
4348void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4349 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4350 const MotionMemento& memento = mMotionMementos.itemAt(i);
4351 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4352 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4353 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4354 if (memento.deviceId == otherMemento.deviceId
4355 && memento.source == otherMemento.source
4356 && memento.displayId == otherMemento.displayId) {
4357 other.mMotionMementos.removeAt(j);
4358 } else {
4359 j += 1;
4360 }
4361 }
4362 other.mMotionMementos.push(memento);
4363 }
4364 }
4365}
4366
4367int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4368 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4369 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4370}
4371
4372void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4373 int32_t fallbackKeyCode) {
4374 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4375 if (index >= 0) {
4376 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4377 } else {
4378 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4379 }
4380}
4381
4382void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4383 mFallbackKeys.removeItem(originalKeyCode);
4384}
4385
4386bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4387 const CancelationOptions& options) {
4388 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4389 return false;
4390 }
4391
4392 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4393 return false;
4394 }
4395
4396 switch (options.mode) {
4397 case CancelationOptions::CANCEL_ALL_EVENTS:
4398 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4399 return true;
4400 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4401 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4402 default:
4403 return false;
4404 }
4405}
4406
4407bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4408 const CancelationOptions& options) {
4409 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4410 return false;
4411 }
4412
4413 switch (options.mode) {
4414 case CancelationOptions::CANCEL_ALL_EVENTS:
4415 return true;
4416 case CancelationOptions::CANCEL_POINTER_EVENTS:
4417 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4418 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4419 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4420 default:
4421 return false;
4422 }
4423}
4424
4425
4426// --- InputDispatcher::Connection ---
4427
4428InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4429 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4430 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4431 monitor(monitor),
4432 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4433}
4434
4435InputDispatcher::Connection::~Connection() {
4436}
4437
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004438const std::string InputDispatcher::Connection::getWindowName() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004439 if (inputWindowHandle != NULL) {
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004440 return inputWindowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441 }
4442 if (monitor) {
4443 return "monitor";
4444 }
4445 return "?";
4446}
4447
4448const char* InputDispatcher::Connection::getStatusLabel() const {
4449 switch (status) {
4450 case STATUS_NORMAL:
4451 return "NORMAL";
4452
4453 case STATUS_BROKEN:
4454 return "BROKEN";
4455
4456 case STATUS_ZOMBIE:
4457 return "ZOMBIE";
4458
4459 default:
4460 return "UNKNOWN";
4461 }
4462}
4463
4464InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4465 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4466 if (entry->seq == seq) {
4467 return entry;
4468 }
4469 }
4470 return NULL;
4471}
4472
4473
4474// --- InputDispatcher::CommandEntry ---
4475
4476InputDispatcher::CommandEntry::CommandEntry(Command command) :
4477 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4478 seq(0), handled(false) {
4479}
4480
4481InputDispatcher::CommandEntry::~CommandEntry() {
4482}
4483
4484
4485// --- InputDispatcher::TouchState ---
4486
4487InputDispatcher::TouchState::TouchState() :
4488 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
4489}
4490
4491InputDispatcher::TouchState::~TouchState() {
4492}
4493
4494void InputDispatcher::TouchState::reset() {
4495 down = false;
4496 split = false;
4497 deviceId = -1;
4498 source = 0;
4499 displayId = -1;
4500 windows.clear();
4501}
4502
4503void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4504 down = other.down;
4505 split = other.split;
4506 deviceId = other.deviceId;
4507 source = other.source;
4508 displayId = other.displayId;
4509 windows = other.windows;
4510}
4511
4512void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4513 int32_t targetFlags, BitSet32 pointerIds) {
4514 if (targetFlags & InputTarget::FLAG_SPLIT) {
4515 split = true;
4516 }
4517
4518 for (size_t i = 0; i < windows.size(); i++) {
4519 TouchedWindow& touchedWindow = windows.editItemAt(i);
4520 if (touchedWindow.windowHandle == windowHandle) {
4521 touchedWindow.targetFlags |= targetFlags;
4522 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4523 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4524 }
4525 touchedWindow.pointerIds.value |= pointerIds.value;
4526 return;
4527 }
4528 }
4529
4530 windows.push();
4531
4532 TouchedWindow& touchedWindow = windows.editTop();
4533 touchedWindow.windowHandle = windowHandle;
4534 touchedWindow.targetFlags = targetFlags;
4535 touchedWindow.pointerIds = pointerIds;
4536}
4537
4538void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4539 for (size_t i = 0; i < windows.size(); i++) {
4540 if (windows.itemAt(i).windowHandle == windowHandle) {
4541 windows.removeAt(i);
4542 return;
4543 }
4544 }
4545}
4546
4547void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4548 for (size_t i = 0 ; i < windows.size(); ) {
4549 TouchedWindow& window = windows.editItemAt(i);
4550 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4551 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4552 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4553 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4554 i += 1;
4555 } else {
4556 windows.removeAt(i);
4557 }
4558 }
4559}
4560
4561sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4562 for (size_t i = 0; i < windows.size(); i++) {
4563 const TouchedWindow& window = windows.itemAt(i);
4564 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4565 return window.windowHandle;
4566 }
4567 }
4568 return NULL;
4569}
4570
4571bool InputDispatcher::TouchState::isSlippery() const {
4572 // Must have exactly one foreground window.
4573 bool haveSlipperyForegroundWindow = false;
4574 for (size_t i = 0; i < windows.size(); i++) {
4575 const TouchedWindow& window = windows.itemAt(i);
4576 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4577 if (haveSlipperyForegroundWindow
4578 || !(window.windowHandle->getInfo()->layoutParamsFlags
4579 & InputWindowInfo::FLAG_SLIPPERY)) {
4580 return false;
4581 }
4582 haveSlipperyForegroundWindow = true;
4583 }
4584 }
4585 return haveSlipperyForegroundWindow;
4586}
4587
4588
4589// --- InputDispatcherThread ---
4590
4591InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4592 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4593}
4594
4595InputDispatcherThread::~InputDispatcherThread() {
4596}
4597
4598bool InputDispatcherThread::threadLoop() {
4599 mDispatcher->dispatchOnce();
4600 return true;
4601}
4602
4603} // namespace android