blob: 86492fd043838d951390d8533dbf54cf7b7404cd [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
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080055#include <android-base/stringprintf.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070056#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070057#include <utils/Trace.h>
58#include <powermanager/PowerManager.h>
59#include <ui/Region.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
61#define INDENT " "
62#define INDENT2 " "
63#define INDENT3 " "
64#define INDENT4 " "
65
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080066using android::base::StringPrintf;
67
Michael Wrightd02c5b62014-02-10 15:10:22 -080068namespace android {
69
70// Default input dispatching timeout if there is no focused application or paused window
71// from which to determine an appropriate dispatching timeout.
72const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
73
74// Amount of time to allow for all pending events to be processed when an app switch
75// key is on the way. This is used to preempt input dispatch and drop input events
76// when an application takes too long to respond and the user has pressed an app switch key.
77const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
78
79// Amount of time to allow for an event to be dispatched (measured since its eventTime)
80// before considering it stale and dropping it.
81const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
82
83// Amount of time to allow touch events to be streamed out to a connection before requiring
84// that the first event be finished. This value extends the ANR timeout by the specified
85// amount. For example, if streaming is allowed to get ahead by one second relative to the
86// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
87const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
88
89// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
90const nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
91
92// Number of recent events to keep for debugging purposes.
93const size_t RECENT_QUEUE_MAX_SIZE = 10;
94
95static inline nsecs_t now() {
96 return systemTime(SYSTEM_TIME_MONOTONIC);
97}
98
99static inline const char* toString(bool value) {
100 return value ? "true" : "false";
101}
102
103static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
104 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
105 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
106}
107
108static bool isValidKeyAction(int32_t action) {
109 switch (action) {
110 case AKEY_EVENT_ACTION_DOWN:
111 case AKEY_EVENT_ACTION_UP:
112 return true;
113 default:
114 return false;
115 }
116}
117
118static bool validateKeyEvent(int32_t action) {
119 if (! isValidKeyAction(action)) {
120 ALOGE("Key event has invalid action code 0x%x", action);
121 return false;
122 }
123 return true;
124}
125
Michael Wright7b159c92015-05-14 14:48:03 +0100126static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127 switch (action & AMOTION_EVENT_ACTION_MASK) {
128 case AMOTION_EVENT_ACTION_DOWN:
129 case AMOTION_EVENT_ACTION_UP:
130 case AMOTION_EVENT_ACTION_CANCEL:
131 case AMOTION_EVENT_ACTION_MOVE:
132 case AMOTION_EVENT_ACTION_OUTSIDE:
133 case AMOTION_EVENT_ACTION_HOVER_ENTER:
134 case AMOTION_EVENT_ACTION_HOVER_MOVE:
135 case AMOTION_EVENT_ACTION_HOVER_EXIT:
136 case AMOTION_EVENT_ACTION_SCROLL:
137 return true;
138 case AMOTION_EVENT_ACTION_POINTER_DOWN:
139 case AMOTION_EVENT_ACTION_POINTER_UP: {
140 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800141 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142 }
Michael Wright7b159c92015-05-14 14:48:03 +0100143 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
144 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
145 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800146 default:
147 return false;
148 }
149}
150
Michael Wright7b159c92015-05-14 14:48:03 +0100151static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800152 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100153 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154 ALOGE("Motion event has invalid action code 0x%x", action);
155 return false;
156 }
157 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000158 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800159 pointerCount, MAX_POINTERS);
160 return false;
161 }
162 BitSet32 pointerIdBits;
163 for (size_t i = 0; i < pointerCount; i++) {
164 int32_t id = pointerProperties[i].id;
165 if (id < 0 || id > MAX_POINTER_ID) {
166 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
167 id, MAX_POINTER_ID);
168 return false;
169 }
170 if (pointerIdBits.hasBit(id)) {
171 ALOGE("Motion event has duplicate pointer id %d", id);
172 return false;
173 }
174 pointerIdBits.markBit(id);
175 }
176 return true;
177}
178
179static bool isMainDisplay(int32_t displayId) {
180 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
181}
182
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800183static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800185 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186 return;
187 }
188
189 bool first = true;
190 Region::const_iterator cur = region.begin();
191 Region::const_iterator const tail = region.end();
192 while (cur != tail) {
193 if (first) {
194 first = false;
195 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800196 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800197 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800198 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 cur++;
200 }
201}
202
203
204// --- InputDispatcher ---
205
206InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
207 mPolicy(policy),
Michael Wright3a981722015-06-10 15:26:13 +0100208 mPendingEvent(NULL), mLastDropReason(DROP_REASON_NOT_DROPPED),
209 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800210 mNextUnblockedEvent(NULL),
211 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
212 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
213 mLooper = new Looper(false);
214
215 mKeyRepeatState.lastKeyEntry = NULL;
216
217 policy->getDispatcherConfiguration(&mConfig);
218}
219
220InputDispatcher::~InputDispatcher() {
221 { // acquire lock
222 AutoMutex _l(mLock);
223
224 resetKeyRepeatLocked();
225 releasePendingEventLocked();
226 drainInboundQueueLocked();
227 }
228
229 while (mConnectionsByFd.size() != 0) {
230 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
231 }
232}
233
234void InputDispatcher::dispatchOnce() {
235 nsecs_t nextWakeupTime = LONG_LONG_MAX;
236 { // acquire lock
237 AutoMutex _l(mLock);
238 mDispatcherIsAliveCondition.broadcast();
239
240 // Run a dispatch loop if there are no pending commands.
241 // The dispatch loop might enqueue commands to run afterwards.
242 if (!haveCommandsLocked()) {
243 dispatchOnceInnerLocked(&nextWakeupTime);
244 }
245
246 // Run all pending commands if there are any.
247 // If any commands were run then force the next poll to wake up immediately.
248 if (runCommandsLockedInterruptible()) {
249 nextWakeupTime = LONG_LONG_MIN;
250 }
251 } // release lock
252
253 // Wait for callback or timeout or wake. (make sure we round up, not down)
254 nsecs_t currentTime = now();
255 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
256 mLooper->pollOnce(timeoutMillis);
257}
258
259void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
260 nsecs_t currentTime = now();
261
Jeff Browndc5992e2014-04-11 01:27:26 -0700262 // Reset the key repeat timer whenever normal dispatch is suspended while the
263 // device is in a non-interactive state. This is to ensure that we abort a key
264 // repeat if the device is just coming out of sleep.
265 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800266 resetKeyRepeatLocked();
267 }
268
269 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
270 if (mDispatchFrozen) {
271#if DEBUG_FOCUS
272 ALOGD("Dispatch frozen. Waiting some more.");
273#endif
274 return;
275 }
276
277 // Optimize latency of app switches.
278 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
279 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
280 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
281 if (mAppSwitchDueTime < *nextWakeupTime) {
282 *nextWakeupTime = mAppSwitchDueTime;
283 }
284
285 // Ready to start a new event.
286 // If we don't already have a pending event, go grab one.
287 if (! mPendingEvent) {
288 if (mInboundQueue.isEmpty()) {
289 if (isAppSwitchDue) {
290 // The inbound queue is empty so the app switch key we were waiting
291 // for will never arrive. Stop waiting for it.
292 resetPendingAppSwitchLocked(false);
293 isAppSwitchDue = false;
294 }
295
296 // Synthesize a key repeat if appropriate.
297 if (mKeyRepeatState.lastKeyEntry) {
298 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
299 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
300 } else {
301 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
302 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
303 }
304 }
305 }
306
307 // Nothing to do if there is no pending event.
308 if (!mPendingEvent) {
309 return;
310 }
311 } else {
312 // Inbound queue has at least one entry.
313 mPendingEvent = mInboundQueue.dequeueAtHead();
314 traceInboundQueueLengthLocked();
315 }
316
317 // Poke user activity for this event.
318 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
319 pokeUserActivityLocked(mPendingEvent);
320 }
321
322 // Get ready to dispatch the event.
323 resetANRTimeoutsLocked();
324 }
325
326 // Now we have an event to dispatch.
327 // All events are eventually dequeued and processed this way, even if we intend to drop them.
328 ALOG_ASSERT(mPendingEvent != NULL);
329 bool done = false;
330 DropReason dropReason = DROP_REASON_NOT_DROPPED;
331 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
332 dropReason = DROP_REASON_POLICY;
333 } else if (!mDispatchEnabled) {
334 dropReason = DROP_REASON_DISABLED;
335 }
336
337 if (mNextUnblockedEvent == mPendingEvent) {
338 mNextUnblockedEvent = NULL;
339 }
340
341 switch (mPendingEvent->type) {
342 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
343 ConfigurationChangedEntry* typedEntry =
344 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
345 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
346 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
347 break;
348 }
349
350 case EventEntry::TYPE_DEVICE_RESET: {
351 DeviceResetEntry* typedEntry =
352 static_cast<DeviceResetEntry*>(mPendingEvent);
353 done = dispatchDeviceResetLocked(currentTime, typedEntry);
354 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
355 break;
356 }
357
358 case EventEntry::TYPE_KEY: {
359 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
360 if (isAppSwitchDue) {
361 if (isAppSwitchKeyEventLocked(typedEntry)) {
362 resetPendingAppSwitchLocked(true);
363 isAppSwitchDue = false;
364 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
365 dropReason = DROP_REASON_APP_SWITCH;
366 }
367 }
368 if (dropReason == DROP_REASON_NOT_DROPPED
369 && isStaleEventLocked(currentTime, typedEntry)) {
370 dropReason = DROP_REASON_STALE;
371 }
372 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
373 dropReason = DROP_REASON_BLOCKED;
374 }
375 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
376 break;
377 }
378
379 case EventEntry::TYPE_MOTION: {
380 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
381 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
382 dropReason = DROP_REASON_APP_SWITCH;
383 }
384 if (dropReason == DROP_REASON_NOT_DROPPED
385 && isStaleEventLocked(currentTime, typedEntry)) {
386 dropReason = DROP_REASON_STALE;
387 }
388 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
389 dropReason = DROP_REASON_BLOCKED;
390 }
391 done = dispatchMotionLocked(currentTime, typedEntry,
392 &dropReason, nextWakeupTime);
393 break;
394 }
395
396 default:
397 ALOG_ASSERT(false);
398 break;
399 }
400
401 if (done) {
402 if (dropReason != DROP_REASON_NOT_DROPPED) {
403 dropInboundEventLocked(mPendingEvent, dropReason);
404 }
Michael Wright3a981722015-06-10 15:26:13 +0100405 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406
407 releasePendingEventLocked();
408 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
409 }
410}
411
412bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
413 bool needWake = mInboundQueue.isEmpty();
414 mInboundQueue.enqueueAtTail(entry);
415 traceInboundQueueLengthLocked();
416
417 switch (entry->type) {
418 case EventEntry::TYPE_KEY: {
419 // Optimize app switch latency.
420 // If the application takes too long to catch up then we drop all events preceding
421 // the app switch key.
422 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
423 if (isAppSwitchKeyEventLocked(keyEntry)) {
424 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
425 mAppSwitchSawKeyDown = true;
426 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
427 if (mAppSwitchSawKeyDown) {
428#if DEBUG_APP_SWITCH
429 ALOGD("App switch is pending!");
430#endif
431 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
432 mAppSwitchSawKeyDown = false;
433 needWake = true;
434 }
435 }
436 }
437 break;
438 }
439
440 case EventEntry::TYPE_MOTION: {
441 // Optimize case where the current application is unresponsive and the user
442 // decides to touch a window in a different application.
443 // If the application takes too long to catch up then we drop all events preceding
444 // the touch into the other window.
445 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
446 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
447 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
448 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
449 && mInputTargetWaitApplicationHandle != NULL) {
450 int32_t displayId = motionEntry->displayId;
451 int32_t x = int32_t(motionEntry->pointerCoords[0].
452 getAxisValue(AMOTION_EVENT_AXIS_X));
453 int32_t y = int32_t(motionEntry->pointerCoords[0].
454 getAxisValue(AMOTION_EVENT_AXIS_Y));
455 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
456 if (touchedWindowHandle != NULL
457 && touchedWindowHandle->inputApplicationHandle
458 != mInputTargetWaitApplicationHandle) {
459 // User touched a different application than the one we are waiting on.
460 // Flag the event, and start pruning the input queue.
461 mNextUnblockedEvent = motionEntry;
462 needWake = true;
463 }
464 }
465 break;
466 }
467 }
468
469 return needWake;
470}
471
472void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
473 entry->refCount += 1;
474 mRecentQueue.enqueueAtTail(entry);
475 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
476 mRecentQueue.dequeueAtHead()->release();
477 }
478}
479
480sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
481 int32_t x, int32_t y) {
482 // Traverse windows from front to back to find touched window.
483 size_t numWindows = mWindowHandles.size();
484 for (size_t i = 0; i < numWindows; i++) {
485 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
486 const InputWindowInfo* windowInfo = windowHandle->getInfo();
487 if (windowInfo->displayId == displayId) {
488 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489
490 if (windowInfo->visible) {
491 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
492 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
493 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
494 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
495 // Found window.
496 return windowHandle;
497 }
498 }
499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500 }
501 }
502 return NULL;
503}
504
505void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
506 const char* reason;
507 switch (dropReason) {
508 case DROP_REASON_POLICY:
509#if DEBUG_INBOUND_EVENT_DETAILS
510 ALOGD("Dropped event because policy consumed it.");
511#endif
512 reason = "inbound event was dropped because the policy consumed it";
513 break;
514 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100515 if (mLastDropReason != DROP_REASON_DISABLED) {
516 ALOGI("Dropped event because input dispatch is disabled.");
517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518 reason = "inbound event was dropped because input dispatch is disabled";
519 break;
520 case DROP_REASON_APP_SWITCH:
521 ALOGI("Dropped event because of pending overdue app switch.");
522 reason = "inbound event was dropped because of pending overdue app switch";
523 break;
524 case DROP_REASON_BLOCKED:
525 ALOGI("Dropped event because the current application is not responding and the user "
526 "has started interacting with a different application.");
527 reason = "inbound event was dropped because the current application is not responding "
528 "and the user has started interacting with a different application";
529 break;
530 case DROP_REASON_STALE:
531 ALOGI("Dropped event because it is stale.");
532 reason = "inbound event was dropped because it is stale";
533 break;
534 default:
535 ALOG_ASSERT(false);
536 return;
537 }
538
539 switch (entry->type) {
540 case EventEntry::TYPE_KEY: {
541 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
542 synthesizeCancelationEventsForAllConnectionsLocked(options);
543 break;
544 }
545 case EventEntry::TYPE_MOTION: {
546 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
547 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
548 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
549 synthesizeCancelationEventsForAllConnectionsLocked(options);
550 } else {
551 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
552 synthesizeCancelationEventsForAllConnectionsLocked(options);
553 }
554 break;
555 }
556 }
557}
558
559bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
560 return keyCode == AKEYCODE_HOME
561 || keyCode == AKEYCODE_ENDCALL
562 || keyCode == AKEYCODE_APP_SWITCH;
563}
564
565bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
566 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
567 && isAppSwitchKeyCode(keyEntry->keyCode)
568 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
569 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
570}
571
572bool InputDispatcher::isAppSwitchPendingLocked() {
573 return mAppSwitchDueTime != LONG_LONG_MAX;
574}
575
576void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
577 mAppSwitchDueTime = LONG_LONG_MAX;
578
579#if DEBUG_APP_SWITCH
580 if (handled) {
581 ALOGD("App switch has arrived.");
582 } else {
583 ALOGD("App switch was abandoned.");
584 }
585#endif
586}
587
588bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
589 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
590}
591
592bool InputDispatcher::haveCommandsLocked() const {
593 return !mCommandQueue.isEmpty();
594}
595
596bool InputDispatcher::runCommandsLockedInterruptible() {
597 if (mCommandQueue.isEmpty()) {
598 return false;
599 }
600
601 do {
602 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
603
604 Command command = commandEntry->command;
605 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
606
607 commandEntry->connection.clear();
608 delete commandEntry;
609 } while (! mCommandQueue.isEmpty());
610 return true;
611}
612
613InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
614 CommandEntry* commandEntry = new CommandEntry(command);
615 mCommandQueue.enqueueAtTail(commandEntry);
616 return commandEntry;
617}
618
619void InputDispatcher::drainInboundQueueLocked() {
620 while (! mInboundQueue.isEmpty()) {
621 EventEntry* entry = mInboundQueue.dequeueAtHead();
622 releaseInboundEventLocked(entry);
623 }
624 traceInboundQueueLengthLocked();
625}
626
627void InputDispatcher::releasePendingEventLocked() {
628 if (mPendingEvent) {
629 resetANRTimeoutsLocked();
630 releaseInboundEventLocked(mPendingEvent);
631 mPendingEvent = NULL;
632 }
633}
634
635void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
636 InjectionState* injectionState = entry->injectionState;
637 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
638#if DEBUG_DISPATCH_CYCLE
639 ALOGD("Injected inbound event was dropped.");
640#endif
641 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
642 }
643 if (entry == mNextUnblockedEvent) {
644 mNextUnblockedEvent = NULL;
645 }
646 addRecentEventLocked(entry);
647 entry->release();
648}
649
650void InputDispatcher::resetKeyRepeatLocked() {
651 if (mKeyRepeatState.lastKeyEntry) {
652 mKeyRepeatState.lastKeyEntry->release();
653 mKeyRepeatState.lastKeyEntry = NULL;
654 }
655}
656
657InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
658 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
659
660 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700661 uint32_t policyFlags = entry->policyFlags &
662 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 if (entry->refCount == 1) {
664 entry->recycle();
665 entry->eventTime = currentTime;
666 entry->policyFlags = policyFlags;
667 entry->repeatCount += 1;
668 } else {
669 KeyEntry* newEntry = new KeyEntry(currentTime,
670 entry->deviceId, entry->source, policyFlags,
671 entry->action, entry->flags, entry->keyCode, entry->scanCode,
672 entry->metaState, entry->repeatCount + 1, entry->downTime);
673
674 mKeyRepeatState.lastKeyEntry = newEntry;
675 entry->release();
676
677 entry = newEntry;
678 }
679 entry->syntheticRepeat = true;
680
681 // Increment reference count since we keep a reference to the event in
682 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
683 entry->refCount += 1;
684
685 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
686 return entry;
687}
688
689bool InputDispatcher::dispatchConfigurationChangedLocked(
690 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
691#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700692 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693#endif
694
695 // Reset key repeating in case a keyboard device was added or removed or something.
696 resetKeyRepeatLocked();
697
698 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
699 CommandEntry* commandEntry = postCommandLocked(
700 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
701 commandEntry->eventTime = entry->eventTime;
702 return true;
703}
704
705bool InputDispatcher::dispatchDeviceResetLocked(
706 nsecs_t currentTime, DeviceResetEntry* entry) {
707#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700708 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
709 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710#endif
711
712 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
713 "device was reset");
714 options.deviceId = entry->deviceId;
715 synthesizeCancelationEventsForAllConnectionsLocked(options);
716 return true;
717}
718
719bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
720 DropReason* dropReason, nsecs_t* nextWakeupTime) {
721 // Preprocessing.
722 if (! entry->dispatchInProgress) {
723 if (entry->repeatCount == 0
724 && entry->action == AKEY_EVENT_ACTION_DOWN
725 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
726 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
727 if (mKeyRepeatState.lastKeyEntry
728 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
729 // We have seen two identical key downs in a row which indicates that the device
730 // driver is automatically generating key repeats itself. We take note of the
731 // repeat here, but we disable our own next key repeat timer since it is clear that
732 // we will not need to synthesize key repeats ourselves.
733 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
734 resetKeyRepeatLocked();
735 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
736 } else {
737 // Not a repeat. Save key down state in case we do see a repeat later.
738 resetKeyRepeatLocked();
739 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
740 }
741 mKeyRepeatState.lastKeyEntry = entry;
742 entry->refCount += 1;
743 } else if (! entry->syntheticRepeat) {
744 resetKeyRepeatLocked();
745 }
746
747 if (entry->repeatCount == 1) {
748 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
749 } else {
750 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
751 }
752
753 entry->dispatchInProgress = true;
754
755 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
756 }
757
758 // Handle case where the policy asked us to try again later last time.
759 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
760 if (currentTime < entry->interceptKeyWakeupTime) {
761 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
762 *nextWakeupTime = entry->interceptKeyWakeupTime;
763 }
764 return false; // wait until next wakeup
765 }
766 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
767 entry->interceptKeyWakeupTime = 0;
768 }
769
770 // Give the policy a chance to intercept the key.
771 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
772 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
773 CommandEntry* commandEntry = postCommandLocked(
774 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
775 if (mFocusedWindowHandle != NULL) {
776 commandEntry->inputWindowHandle = mFocusedWindowHandle;
777 }
778 commandEntry->keyEntry = entry;
779 entry->refCount += 1;
780 return false; // wait for the command to run
781 } else {
782 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
783 }
784 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
785 if (*dropReason == DROP_REASON_NOT_DROPPED) {
786 *dropReason = DROP_REASON_POLICY;
787 }
788 }
789
790 // Clean up if dropping the event.
791 if (*dropReason != DROP_REASON_NOT_DROPPED) {
792 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
793 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
794 return true;
795 }
796
797 // Identify targets.
798 Vector<InputTarget> inputTargets;
799 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
800 entry, inputTargets, nextWakeupTime);
801 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
802 return false;
803 }
804
805 setInjectionResultLocked(entry, injectionResult);
806 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
807 return true;
808 }
809
810 addMonitoringTargetsLocked(inputTargets);
811
812 // Dispatch the key.
813 dispatchEventLocked(currentTime, entry, inputTargets);
814 return true;
815}
816
817void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
818#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700819 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, policyFlags=0x%x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800820 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700821 "repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 prefix,
823 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
824 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
825 entry->repeatCount, entry->downTime);
826#endif
827}
828
829bool InputDispatcher::dispatchMotionLocked(
830 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
831 // Preprocessing.
832 if (! entry->dispatchInProgress) {
833 entry->dispatchInProgress = true;
834
835 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
836 }
837
838 // Clean up if dropping the event.
839 if (*dropReason != DROP_REASON_NOT_DROPPED) {
840 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
841 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
842 return true;
843 }
844
845 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
846
847 // Identify targets.
848 Vector<InputTarget> inputTargets;
849
850 bool conflictingPointerActions = false;
851 int32_t injectionResult;
852 if (isPointerEvent) {
853 // Pointer event. (eg. touchscreen)
854 injectionResult = findTouchedWindowTargetsLocked(currentTime,
855 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
856 } else {
857 // Non touch event. (eg. trackball)
858 injectionResult = findFocusedWindowTargetsLocked(currentTime,
859 entry, inputTargets, nextWakeupTime);
860 }
861 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
862 return false;
863 }
864
865 setInjectionResultLocked(entry, injectionResult);
866 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100867 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
868 CancelationOptions::Mode mode(isPointerEvent ?
869 CancelationOptions::CANCEL_POINTER_EVENTS :
870 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
871 CancelationOptions options(mode, "input event injection failed");
872 synthesizeCancelationEventsForMonitorsLocked(options);
873 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 return true;
875 }
876
Tarandeep Singh48aeb512017-07-17 11:22:52 -0700877 addMonitoringTargetsLocked(inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878
879 // Dispatch the motion.
880 if (conflictingPointerActions) {
881 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
882 "conflicting pointer actions");
883 synthesizeCancelationEventsForAllConnectionsLocked(options);
884 }
885 dispatchEventLocked(currentTime, entry, inputTargets);
886 return true;
887}
888
889
890void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
891#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700892 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100893 "action=0x%x, actionButton=0x%x, flags=0x%x, "
894 "metaState=0x%x, buttonState=0x%x,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700895 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 prefix,
897 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100898 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 entry->metaState, entry->buttonState,
900 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
901 entry->downTime);
902
903 for (uint32_t i = 0; i < entry->pointerCount; i++) {
904 ALOGD(" Pointer %d: id=%d, toolType=%d, "
905 "x=%f, y=%f, pressure=%f, size=%f, "
906 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800907 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 i, entry->pointerProperties[i].id,
909 entry->pointerProperties[i].toolType,
910 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
911 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
912 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
913 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
914 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
915 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
916 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
917 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800918 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919 }
920#endif
921}
922
923void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
924 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
925#if DEBUG_DISPATCH_CYCLE
926 ALOGD("dispatchEventToCurrentInputTargets");
927#endif
928
929 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
930
931 pokeUserActivityLocked(eventEntry);
932
933 for (size_t i = 0; i < inputTargets.size(); i++) {
934 const InputTarget& inputTarget = inputTargets.itemAt(i);
935
936 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
937 if (connectionIndex >= 0) {
938 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
939 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
940 } else {
941#if DEBUG_FOCUS
942 ALOGD("Dropping event delivery to target with channel '%s' because it "
943 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800944 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945#endif
946 }
947 }
948}
949
950int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
951 const EventEntry* entry,
952 const sp<InputApplicationHandle>& applicationHandle,
953 const sp<InputWindowHandle>& windowHandle,
954 nsecs_t* nextWakeupTime, const char* reason) {
955 if (applicationHandle == NULL && windowHandle == NULL) {
956 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
957#if DEBUG_FOCUS
958 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
959#endif
960 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
961 mInputTargetWaitStartTime = currentTime;
962 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
963 mInputTargetWaitTimeoutExpired = false;
964 mInputTargetWaitApplicationHandle.clear();
965 }
966 } else {
967 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
968#if DEBUG_FOCUS
969 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800970 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 reason);
972#endif
973 nsecs_t timeout;
974 if (windowHandle != NULL) {
975 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
976 } else if (applicationHandle != NULL) {
977 timeout = applicationHandle->getDispatchingTimeout(
978 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
979 } else {
980 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
981 }
982
983 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
984 mInputTargetWaitStartTime = currentTime;
985 mInputTargetWaitTimeoutTime = currentTime + timeout;
986 mInputTargetWaitTimeoutExpired = false;
987 mInputTargetWaitApplicationHandle.clear();
988
989 if (windowHandle != NULL) {
990 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
991 }
992 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
993 mInputTargetWaitApplicationHandle = applicationHandle;
994 }
995 }
996 }
997
998 if (mInputTargetWaitTimeoutExpired) {
999 return INPUT_EVENT_INJECTION_TIMED_OUT;
1000 }
1001
1002 if (currentTime >= mInputTargetWaitTimeoutTime) {
1003 onANRLocked(currentTime, applicationHandle, windowHandle,
1004 entry->eventTime, mInputTargetWaitStartTime, reason);
1005
1006 // Force poll loop to wake up immediately on next iteration once we get the
1007 // ANR response back from the policy.
1008 *nextWakeupTime = LONG_LONG_MIN;
1009 return INPUT_EVENT_INJECTION_PENDING;
1010 } else {
1011 // Force poll loop to wake up when timeout is due.
1012 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1013 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1014 }
1015 return INPUT_EVENT_INJECTION_PENDING;
1016 }
1017}
1018
1019void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1020 const sp<InputChannel>& inputChannel) {
1021 if (newTimeout > 0) {
1022 // Extend the timeout.
1023 mInputTargetWaitTimeoutTime = now() + newTimeout;
1024 } else {
1025 // Give up.
1026 mInputTargetWaitTimeoutExpired = true;
1027
1028 // Input state will not be realistic. Mark it out of sync.
1029 if (inputChannel.get()) {
1030 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1031 if (connectionIndex >= 0) {
1032 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1033 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1034
1035 if (windowHandle != NULL) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001036 const InputWindowInfo* info = windowHandle->getInfo();
1037 if (info) {
1038 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId);
1039 if (stateIndex >= 0) {
1040 mTouchStatesByDisplay.editValueAt(stateIndex).removeWindow(
1041 windowHandle);
1042 }
1043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 }
1045
1046 if (connection->status == Connection::STATUS_NORMAL) {
1047 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1048 "application not responding");
1049 synthesizeCancelationEventsForConnectionLocked(connection, options);
1050 }
1051 }
1052 }
1053 }
1054}
1055
1056nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1057 nsecs_t currentTime) {
1058 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1059 return currentTime - mInputTargetWaitStartTime;
1060 }
1061 return 0;
1062}
1063
1064void InputDispatcher::resetANRTimeoutsLocked() {
1065#if DEBUG_FOCUS
1066 ALOGD("Resetting ANR timeouts.");
1067#endif
1068
1069 // Reset input target wait timeout.
1070 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1071 mInputTargetWaitApplicationHandle.clear();
1072}
1073
1074int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1075 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1076 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001077 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078
1079 // If there is no currently focused window and no focused application
1080 // then drop the event.
1081 if (mFocusedWindowHandle == NULL) {
1082 if (mFocusedApplicationHandle != NULL) {
1083 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1084 mFocusedApplicationHandle, NULL, nextWakeupTime,
1085 "Waiting because no window has focus but there is a "
1086 "focused application that may eventually add a window "
1087 "when it finishes starting up.");
1088 goto Unresponsive;
1089 }
1090
1091 ALOGI("Dropping event because there is no focused window or focused application.");
1092 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1093 goto Failed;
1094 }
1095
1096 // Check permissions.
1097 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
1098 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1099 goto Failed;
1100 }
1101
Jeff Brownffb49772014-10-10 19:01:34 -07001102 // Check whether the window is ready for more input.
1103 reason = checkWindowReadyForMoreInputLocked(currentTime,
1104 mFocusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001105 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001107 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108 goto Unresponsive;
1109 }
1110
1111 // Success! Output targets.
1112 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1113 addWindowTargetLocked(mFocusedWindowHandle,
1114 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1115 inputTargets);
1116
1117 // Done.
1118Failed:
1119Unresponsive:
1120 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1121 updateDispatchStatisticsLocked(currentTime, entry,
1122 injectionResult, timeSpentWaitingForApplication);
1123#if DEBUG_FOCUS
1124 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1125 "timeSpentWaitingForApplication=%0.1fms",
1126 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1127#endif
1128 return injectionResult;
1129}
1130
1131int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1132 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1133 bool* outConflictingPointerActions) {
1134 enum InjectionPermission {
1135 INJECTION_PERMISSION_UNKNOWN,
1136 INJECTION_PERMISSION_GRANTED,
1137 INJECTION_PERMISSION_DENIED
1138 };
1139
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 // For security reasons, we defer updating the touch state until we are sure that
1141 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142 int32_t displayId = entry->displayId;
1143 int32_t action = entry->action;
1144 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1145
1146 // Update the touch state as needed based on the properties of the touch event.
1147 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1148 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1149 sp<InputWindowHandle> newHoverWindowHandle;
1150
Jeff Brownf086ddb2014-02-11 14:28:48 -08001151 // Copy current touch state into mTempTouchState.
1152 // This state is always reset at the end of this function, so if we don't find state
1153 // for the specified display then our initial state will be empty.
1154 const TouchState* oldState = NULL;
1155 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1156 if (oldStateIndex >= 0) {
1157 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1158 mTempTouchState.copyFrom(*oldState);
1159 }
1160
1161 bool isSplit = mTempTouchState.split;
1162 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1163 && (mTempTouchState.deviceId != entry->deviceId
1164 || mTempTouchState.source != entry->source
1165 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1167 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1168 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1169 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1170 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1171 || isHoverAction);
1172 bool wrongDevice = false;
1173 if (newGesture) {
1174 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001175 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176#if DEBUG_FOCUS
1177 ALOGD("Dropping event because a pointer for a different device is already down.");
1178#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001179 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1181 switchedDevice = false;
1182 wrongDevice = true;
1183 goto Failed;
1184 }
1185 mTempTouchState.reset();
1186 mTempTouchState.down = down;
1187 mTempTouchState.deviceId = entry->deviceId;
1188 mTempTouchState.source = entry->source;
1189 mTempTouchState.displayId = displayId;
1190 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001191 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1192#if DEBUG_FOCUS
1193 ALOGI("Dropping move event because a pointer for a different device is already active.");
1194#endif
1195 // TODO: test multiple simultaneous input streams.
1196 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1197 switchedDevice = false;
1198 wrongDevice = true;
1199 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 }
1201
1202 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1203 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1204
1205 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1206 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1207 getAxisValue(AMOTION_EVENT_AXIS_X));
1208 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1209 getAxisValue(AMOTION_EVENT_AXIS_Y));
1210 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 bool isTouchModal = false;
1212
1213 // Traverse windows from front to back to find touched window and outside targets.
1214 size_t numWindows = mWindowHandles.size();
1215 for (size_t i = 0; i < numWindows; i++) {
1216 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1217 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1218 if (windowInfo->displayId != displayId) {
1219 continue; // wrong display
1220 }
1221
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 int32_t flags = windowInfo->layoutParamsFlags;
1223 if (windowInfo->visible) {
1224 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1225 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1226 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1227 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001228 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 break; // found touched window, exit window loop
1230 }
1231 }
1232
1233 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1234 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001236 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 }
1238 }
1239 }
1240
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 // Figure out whether splitting will be allowed for this window.
1242 if (newTouchedWindowHandle != NULL
1243 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1244 // New window supports splitting.
1245 isSplit = true;
1246 } else if (isSplit) {
1247 // New window does not support splitting but we have already split events.
1248 // Ignore the new window.
1249 newTouchedWindowHandle = NULL;
1250 }
1251
1252 // Handle the case where we did not find a window.
1253 if (newTouchedWindowHandle == NULL) {
1254 // Try to assign the pointer to the first foreground window we find, if there is one.
1255 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1256 if (newTouchedWindowHandle == NULL) {
1257 ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y);
1258 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1259 goto Failed;
1260 }
1261 }
1262
1263 // Set target flags.
1264 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1265 if (isSplit) {
1266 targetFlags |= InputTarget::FLAG_SPLIT;
1267 }
1268 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1269 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001270 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1271 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 }
1273
1274 // Update hover state.
1275 if (isHoverAction) {
1276 newHoverWindowHandle = newTouchedWindowHandle;
1277 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1278 newHoverWindowHandle = mLastHoverWindowHandle;
1279 }
1280
1281 // Update the temporary touch state.
1282 BitSet32 pointerIds;
1283 if (isSplit) {
1284 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1285 pointerIds.markBit(pointerId);
1286 }
1287 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1288 } else {
1289 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1290
1291 // If the pointer is not currently down, then ignore the event.
1292 if (! mTempTouchState.down) {
1293#if DEBUG_FOCUS
1294 ALOGD("Dropping event because the pointer is not down or we previously "
1295 "dropped the pointer down event.");
1296#endif
1297 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1298 goto Failed;
1299 }
1300
1301 // Check whether touches should slip outside of the current foreground window.
1302 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1303 && entry->pointerCount == 1
1304 && mTempTouchState.isSlippery()) {
1305 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1306 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1307
1308 sp<InputWindowHandle> oldTouchedWindowHandle =
1309 mTempTouchState.getFirstForegroundWindowHandle();
1310 sp<InputWindowHandle> newTouchedWindowHandle =
1311 findTouchedWindowAtLocked(displayId, x, y);
1312 if (oldTouchedWindowHandle != newTouchedWindowHandle
1313 && newTouchedWindowHandle != NULL) {
1314#if DEBUG_FOCUS
1315 ALOGD("Touch is slipping out of window %s into window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001316 oldTouchedWindowHandle->getName().c_str(),
1317 newTouchedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318#endif
1319 // Make a slippery exit from the old window.
1320 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1321 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1322
1323 // Make a slippery entrance into the new window.
1324 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1325 isSplit = true;
1326 }
1327
1328 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1329 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1330 if (isSplit) {
1331 targetFlags |= InputTarget::FLAG_SPLIT;
1332 }
1333 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1334 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1335 }
1336
1337 BitSet32 pointerIds;
1338 if (isSplit) {
1339 pointerIds.markBit(entry->pointerProperties[0].id);
1340 }
1341 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1342 }
1343 }
1344 }
1345
1346 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1347 // Let the previous window know that the hover sequence is over.
1348 if (mLastHoverWindowHandle != NULL) {
1349#if DEBUG_HOVER
1350 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001351 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352#endif
1353 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1354 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1355 }
1356
1357 // Let the new window know that the hover sequence is starting.
1358 if (newHoverWindowHandle != NULL) {
1359#if DEBUG_HOVER
1360 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001361 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362#endif
1363 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1364 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1365 }
1366 }
1367
1368 // Check permission to inject into all touched foreground windows and ensure there
1369 // is at least one touched foreground window.
1370 {
1371 bool haveForegroundWindow = false;
1372 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1373 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1374 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1375 haveForegroundWindow = true;
1376 if (! checkInjectionPermission(touchedWindow.windowHandle,
1377 entry->injectionState)) {
1378 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1379 injectionPermission = INJECTION_PERMISSION_DENIED;
1380 goto Failed;
1381 }
1382 }
1383 }
1384 if (! haveForegroundWindow) {
1385#if DEBUG_FOCUS
1386 ALOGD("Dropping event because there is no touched foreground window to receive it.");
1387#endif
1388 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1389 goto Failed;
1390 }
1391
1392 // Permission granted to injection into all touched foreground windows.
1393 injectionPermission = INJECTION_PERMISSION_GRANTED;
1394 }
1395
1396 // Check whether windows listening for outside touches are owned by the same UID. If it is
1397 // set the policy flag that we will not reveal coordinate information to this window.
1398 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1399 sp<InputWindowHandle> foregroundWindowHandle =
1400 mTempTouchState.getFirstForegroundWindowHandle();
1401 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1402 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1403 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1404 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1405 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1406 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1407 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1408 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1409 }
1410 }
1411 }
1412 }
1413
1414 // Ensure all touched foreground windows are ready for new input.
1415 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1416 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1417 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001418 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001419 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001420 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001421 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001422 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001423 NULL, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 goto Unresponsive;
1425 }
1426 }
1427 }
1428
1429 // If this is the first pointer going down and the touched window has a wallpaper
1430 // then also add the touched wallpaper windows so they are locked in for the duration
1431 // of the touch gesture.
1432 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1433 // engine only supports touch events. We would need to add a mechanism similar
1434 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1435 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1436 sp<InputWindowHandle> foregroundWindowHandle =
1437 mTempTouchState.getFirstForegroundWindowHandle();
1438 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
1439 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1440 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1441 const InputWindowInfo* info = windowHandle->getInfo();
1442 if (info->displayId == displayId
1443 && windowHandle->getInfo()->layoutParamsType
1444 == InputWindowInfo::TYPE_WALLPAPER) {
1445 mTempTouchState.addOrUpdateWindow(windowHandle,
1446 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001447 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 | InputTarget::FLAG_DISPATCH_AS_IS,
1449 BitSet32(0));
1450 }
1451 }
1452 }
1453 }
1454
1455 // Success! Output targets.
1456 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1457
1458 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1459 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1460 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1461 touchedWindow.pointerIds, inputTargets);
1462 }
1463
1464 // Drop the outside or hover touch windows since we will not care about them
1465 // in the next iteration.
1466 mTempTouchState.filterNonAsIsTouchWindows();
1467
1468Failed:
1469 // Check injection permission once and for all.
1470 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
1471 if (checkInjectionPermission(NULL, entry->injectionState)) {
1472 injectionPermission = INJECTION_PERMISSION_GRANTED;
1473 } else {
1474 injectionPermission = INJECTION_PERMISSION_DENIED;
1475 }
1476 }
1477
1478 // Update final pieces of touch state if the injector had permission.
1479 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1480 if (!wrongDevice) {
1481 if (switchedDevice) {
1482#if DEBUG_FOCUS
1483 ALOGD("Conflicting pointer actions: Switched to a different device.");
1484#endif
1485 *outConflictingPointerActions = true;
1486 }
1487
1488 if (isHoverAction) {
1489 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001490 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491#if DEBUG_FOCUS
1492 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1493#endif
1494 *outConflictingPointerActions = true;
1495 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001496 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001497 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1498 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001499 mTempTouchState.deviceId = entry->deviceId;
1500 mTempTouchState.source = entry->source;
1501 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 }
1503 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1504 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1505 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001506 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1508 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001509 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510#if DEBUG_FOCUS
1511 ALOGD("Conflicting pointer actions: Down received while already down.");
1512#endif
1513 *outConflictingPointerActions = true;
1514 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1516 // One pointer went up.
1517 if (isSplit) {
1518 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1519 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1520
1521 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1522 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1523 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1524 touchedWindow.pointerIds.clearBit(pointerId);
1525 if (touchedWindow.pointerIds.isEmpty()) {
1526 mTempTouchState.windows.removeAt(i);
1527 continue;
1528 }
1529 }
1530 i += 1;
1531 }
1532 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001533 }
1534
1535 // Save changes unless the action was scroll in which case the temporary touch
1536 // state was only valid for this one action.
1537 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1538 if (mTempTouchState.displayId >= 0) {
1539 if (oldStateIndex >= 0) {
1540 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1541 } else {
1542 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1543 }
1544 } else if (oldStateIndex >= 0) {
1545 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 }
1548
1549 // Update hover state.
1550 mLastHoverWindowHandle = newHoverWindowHandle;
1551 }
1552 } else {
1553#if DEBUG_FOCUS
1554 ALOGD("Not updating touch focus because injection was denied.");
1555#endif
1556 }
1557
1558Unresponsive:
1559 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1560 mTempTouchState.reset();
1561
1562 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1563 updateDispatchStatisticsLocked(currentTime, entry,
1564 injectionResult, timeSpentWaitingForApplication);
1565#if DEBUG_FOCUS
1566 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1567 "timeSpentWaitingForApplication=%0.1fms",
1568 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1569#endif
1570 return injectionResult;
1571}
1572
1573void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1574 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1575 inputTargets.push();
1576
1577 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1578 InputTarget& target = inputTargets.editTop();
1579 target.inputChannel = windowInfo->inputChannel;
1580 target.flags = targetFlags;
1581 target.xOffset = - windowInfo->frameLeft;
1582 target.yOffset = - windowInfo->frameTop;
1583 target.scaleFactor = windowInfo->scaleFactor;
1584 target.pointerIds = pointerIds;
1585}
1586
1587void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
1588 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1589 inputTargets.push();
1590
1591 InputTarget& target = inputTargets.editTop();
1592 target.inputChannel = mMonitoringChannels[i];
1593 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1594 target.xOffset = 0;
1595 target.yOffset = 0;
1596 target.pointerIds.clear();
1597 target.scaleFactor = 1.0f;
1598 }
1599}
1600
1601bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1602 const InjectionState* injectionState) {
1603 if (injectionState
1604 && (windowHandle == NULL
1605 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1606 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1607 if (windowHandle != NULL) {
1608 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1609 "owned by uid %d",
1610 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001611 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 windowHandle->getInfo()->ownerUid);
1613 } else {
1614 ALOGW("Permission denied: injecting event from pid %d uid %d",
1615 injectionState->injectorPid, injectionState->injectorUid);
1616 }
1617 return false;
1618 }
1619 return true;
1620}
1621
1622bool InputDispatcher::isWindowObscuredAtPointLocked(
1623 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1624 int32_t displayId = windowHandle->getInfo()->displayId;
1625 size_t numWindows = mWindowHandles.size();
1626 for (size_t i = 0; i < numWindows; i++) {
1627 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1628 if (otherHandle == windowHandle) {
1629 break;
1630 }
1631
1632 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1633 if (otherInfo->displayId == displayId
1634 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1635 && otherInfo->frameContainsPoint(x, y)) {
1636 return true;
1637 }
1638 }
1639 return false;
1640}
1641
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001642
1643bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1644 int32_t displayId = windowHandle->getInfo()->displayId;
1645 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1646 size_t numWindows = mWindowHandles.size();
1647 for (size_t i = 0; i < numWindows; i++) {
1648 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1649 if (otherHandle == windowHandle) {
1650 break;
1651 }
1652
1653 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1654 if (otherInfo->displayId == displayId
1655 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1656 && otherInfo->overlaps(windowInfo)) {
1657 return true;
1658 }
1659 }
1660 return false;
1661}
1662
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001663std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001664 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1665 const char* targetType) {
1666 // If the window is paused then keep waiting.
1667 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001668 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001669 }
1670
1671 // If the window's connection is not registered then keep waiting.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brownffb49772014-10-10 19:01:34 -07001673 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001674 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001675 "registered with the input dispatcher. The window may be in the process "
1676 "of being removed.", targetType);
1677 }
1678
1679 // If the connection is dead then keep waiting.
1680 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1681 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001682 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001683 "The window may be in the process of being removed.", targetType,
1684 connection->getStatusLabel());
1685 }
1686
1687 // If the connection is backed up then keep waiting.
1688 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001689 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001690 "Outbound queue length: %d. Wait queue length: %d.",
1691 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1692 }
1693
1694 // Ensure that the dispatch queues aren't too far backed up for this event.
1695 if (eventEntry->type == EventEntry::TYPE_KEY) {
1696 // If the event is a key event, then we must wait for all previous events to
1697 // complete before delivering it because previous events may have the
1698 // side-effect of transferring focus to a different window and we want to
1699 // ensure that the following keys are sent to the new window.
1700 //
1701 // Suppose the user touches a button in a window then immediately presses "A".
1702 // If the button causes a pop-up window to appear then we want to ensure that
1703 // the "A" key is delivered to the new pop-up window. This is because users
1704 // often anticipate pending UI changes when typing on a keyboard.
1705 // To obtain this behavior, we must serialize key events with respect to all
1706 // prior input events.
1707 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001708 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001709 "finished processing all of the input events that were previously "
1710 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1711 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 }
Jeff Brownffb49772014-10-10 19:01:34 -07001713 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 // Touch events can always be sent to a window immediately because the user intended
1715 // to touch whatever was visible at the time. Even if focus changes or a new
1716 // window appears moments later, the touch event was meant to be delivered to
1717 // whatever window happened to be on screen at the time.
1718 //
1719 // Generic motion events, such as trackball or joystick events are a little trickier.
1720 // Like key events, generic motion events are delivered to the focused window.
1721 // Unlike key events, generic motion events don't tend to transfer focus to other
1722 // windows and it is not important for them to be serialized. So we prefer to deliver
1723 // generic motion events as soon as possible to improve efficiency and reduce lag
1724 // through batching.
1725 //
1726 // The one case where we pause input event delivery is when the wait queue is piling
1727 // up with lots of events because the application is not responding.
1728 // This condition ensures that ANRs are detected reliably.
1729 if (!connection->waitQueue.isEmpty()
1730 && currentTime >= connection->waitQueue.head->deliveryTime
1731 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001732 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001733 "finished processing certain input events that were delivered to it over "
1734 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1735 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1736 connection->waitQueue.count(),
1737 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 }
1739 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001740 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741}
1742
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001743std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 const sp<InputApplicationHandle>& applicationHandle,
1745 const sp<InputWindowHandle>& windowHandle) {
1746 if (applicationHandle != NULL) {
1747 if (windowHandle != NULL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001748 std::string label(applicationHandle->getName());
1749 label += " - ";
1750 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 return label;
1752 } else {
1753 return applicationHandle->getName();
1754 }
1755 } else if (windowHandle != NULL) {
1756 return windowHandle->getName();
1757 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001758 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001759 }
1760}
1761
1762void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
1763 if (mFocusedWindowHandle != NULL) {
1764 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1765 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1766#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001767 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001768#endif
1769 return;
1770 }
1771 }
1772
1773 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1774 switch (eventEntry->type) {
1775 case EventEntry::TYPE_MOTION: {
1776 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1777 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1778 return;
1779 }
1780
1781 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1782 eventType = USER_ACTIVITY_EVENT_TOUCH;
1783 }
1784 break;
1785 }
1786 case EventEntry::TYPE_KEY: {
1787 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1788 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1789 return;
1790 }
1791 eventType = USER_ACTIVITY_EVENT_BUTTON;
1792 break;
1793 }
1794 }
1795
1796 CommandEntry* commandEntry = postCommandLocked(
1797 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1798 commandEntry->eventTime = eventEntry->eventTime;
1799 commandEntry->userActivityEventType = eventType;
1800}
1801
1802void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1803 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1804#if DEBUG_DISPATCH_CYCLE
1805 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1806 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1807 "pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001808 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 inputTarget->xOffset, inputTarget->yOffset,
1810 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1811#endif
1812
1813 // Skip this event if the connection status is not normal.
1814 // We don't want to enqueue additional outbound events if the connection is broken.
1815 if (connection->status != Connection::STATUS_NORMAL) {
1816#if DEBUG_DISPATCH_CYCLE
1817 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001818 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819#endif
1820 return;
1821 }
1822
1823 // Split a motion event if needed.
1824 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1825 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1826
1827 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1828 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1829 MotionEntry* splitMotionEntry = splitMotionEvent(
1830 originalMotionEntry, inputTarget->pointerIds);
1831 if (!splitMotionEntry) {
1832 return; // split event was dropped
1833 }
1834#if DEBUG_FOCUS
1835 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001836 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001837 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1838#endif
1839 enqueueDispatchEntriesLocked(currentTime, connection,
1840 splitMotionEntry, inputTarget);
1841 splitMotionEntry->release();
1842 return;
1843 }
1844 }
1845
1846 // Not splitting. Enqueue dispatch entries for the event as is.
1847 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1848}
1849
1850void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1851 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1852 bool wasEmpty = connection->outboundQueue.isEmpty();
1853
1854 // Enqueue dispatch entries for the requested modes.
1855 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1856 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1857 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1858 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1859 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1860 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1861 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1862 InputTarget::FLAG_DISPATCH_AS_IS);
1863 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1864 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1865 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1866 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1867
1868 // If the outbound queue was previously empty, start the dispatch cycle going.
1869 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1870 startDispatchCycleLocked(currentTime, connection);
1871 }
1872}
1873
1874void InputDispatcher::enqueueDispatchEntryLocked(
1875 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1876 int32_t dispatchMode) {
1877 int32_t inputTargetFlags = inputTarget->flags;
1878 if (!(inputTargetFlags & dispatchMode)) {
1879 return;
1880 }
1881 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1882
1883 // This is a new event.
1884 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1885 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1886 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1887 inputTarget->scaleFactor);
1888
1889 // Apply target flags and update the connection's input state.
1890 switch (eventEntry->type) {
1891 case EventEntry::TYPE_KEY: {
1892 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1893 dispatchEntry->resolvedAction = keyEntry->action;
1894 dispatchEntry->resolvedFlags = keyEntry->flags;
1895
1896 if (!connection->inputState.trackKey(keyEntry,
1897 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1898#if DEBUG_DISPATCH_CYCLE
1899 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001900 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901#endif
1902 delete dispatchEntry;
1903 return; // skip the inconsistent event
1904 }
1905 break;
1906 }
1907
1908 case EventEntry::TYPE_MOTION: {
1909 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1910 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1911 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1912 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1913 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1914 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1915 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1916 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1917 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1918 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1919 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1920 } else {
1921 dispatchEntry->resolvedAction = motionEntry->action;
1922 }
1923 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1924 && !connection->inputState.isHovering(
1925 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
1926#if DEBUG_DISPATCH_CYCLE
1927 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001928 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929#endif
1930 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1931 }
1932
1933 dispatchEntry->resolvedFlags = motionEntry->flags;
1934 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1935 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1936 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001937 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
1938 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001940
1941 if (!connection->inputState.trackMotion(motionEntry,
1942 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1943#if DEBUG_DISPATCH_CYCLE
1944 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001945 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946#endif
1947 delete dispatchEntry;
1948 return; // skip the inconsistent event
1949 }
1950 break;
1951 }
1952 }
1953
1954 // Remember that we are waiting for this dispatch to complete.
1955 if (dispatchEntry->hasForegroundTarget()) {
1956 incrementPendingForegroundDispatchesLocked(eventEntry);
1957 }
1958
1959 // Enqueue the dispatch entry.
1960 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1961 traceOutboundQueueLengthLocked(connection);
1962}
1963
1964void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
1965 const sp<Connection>& connection) {
1966#if DEBUG_DISPATCH_CYCLE
1967 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001968 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969#endif
1970
1971 while (connection->status == Connection::STATUS_NORMAL
1972 && !connection->outboundQueue.isEmpty()) {
1973 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
1974 dispatchEntry->deliveryTime = currentTime;
1975
1976 // Publish the event.
1977 status_t status;
1978 EventEntry* eventEntry = dispatchEntry->eventEntry;
1979 switch (eventEntry->type) {
1980 case EventEntry::TYPE_KEY: {
1981 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1982
1983 // Publish the key event.
1984 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
1985 keyEntry->deviceId, keyEntry->source,
1986 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1987 keyEntry->keyCode, keyEntry->scanCode,
1988 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1989 keyEntry->eventTime);
1990 break;
1991 }
1992
1993 case EventEntry::TYPE_MOTION: {
1994 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1995
1996 PointerCoords scaledCoords[MAX_POINTERS];
1997 const PointerCoords* usingCoords = motionEntry->pointerCoords;
1998
1999 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002000 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2002 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002003 float scaleFactor = dispatchEntry->scaleFactor;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 xOffset = dispatchEntry->xOffset * scaleFactor;
2005 yOffset = dispatchEntry->yOffset * scaleFactor;
2006 if (scaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002007 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 scaledCoords[i] = motionEntry->pointerCoords[i];
2009 scaledCoords[i].scale(scaleFactor);
2010 }
2011 usingCoords = scaledCoords;
2012 }
2013 } else {
2014 xOffset = 0.0f;
2015 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016
2017 // We don't want the dispatch target to know.
2018 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002019 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 scaledCoords[i].clear();
2021 }
2022 usingCoords = scaledCoords;
2023 }
2024 }
2025
2026 // Publish the motion event.
2027 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002028 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002029 dispatchEntry->resolvedAction, motionEntry->actionButton,
2030 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2031 motionEntry->metaState, motionEntry->buttonState,
2032 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 motionEntry->downTime, motionEntry->eventTime,
2034 motionEntry->pointerCount, motionEntry->pointerProperties,
2035 usingCoords);
2036 break;
2037 }
2038
2039 default:
2040 ALOG_ASSERT(false);
2041 return;
2042 }
2043
2044 // Check the result.
2045 if (status) {
2046 if (status == WOULD_BLOCK) {
2047 if (connection->waitQueue.isEmpty()) {
2048 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2049 "This is unexpected because the wait queue is empty, so the pipe "
2050 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002051 "event to it, status=%d", connection->getInputChannelName().c_str(),
2052 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2054 } else {
2055 // Pipe is full and we are waiting for the app to finish process some events
2056 // before sending more events to it.
2057#if DEBUG_DISPATCH_CYCLE
2058 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2059 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002060 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061#endif
2062 connection->inputPublisherBlocked = true;
2063 }
2064 } else {
2065 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002066 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2068 }
2069 return;
2070 }
2071
2072 // Re-enqueue the event on the wait queue.
2073 connection->outboundQueue.dequeue(dispatchEntry);
2074 traceOutboundQueueLengthLocked(connection);
2075 connection->waitQueue.enqueueAtTail(dispatchEntry);
2076 traceWaitQueueLengthLocked(connection);
2077 }
2078}
2079
2080void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2081 const sp<Connection>& connection, uint32_t seq, bool handled) {
2082#if DEBUG_DISPATCH_CYCLE
2083 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002084 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085#endif
2086
2087 connection->inputPublisherBlocked = false;
2088
2089 if (connection->status == Connection::STATUS_BROKEN
2090 || connection->status == Connection::STATUS_ZOMBIE) {
2091 return;
2092 }
2093
2094 // Notify other system components and prepare to start the next dispatch cycle.
2095 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2096}
2097
2098void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2099 const sp<Connection>& connection, bool notify) {
2100#if DEBUG_DISPATCH_CYCLE
2101 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002102 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103#endif
2104
2105 // Clear the dispatch queues.
2106 drainDispatchQueueLocked(&connection->outboundQueue);
2107 traceOutboundQueueLengthLocked(connection);
2108 drainDispatchQueueLocked(&connection->waitQueue);
2109 traceWaitQueueLengthLocked(connection);
2110
2111 // The connection appears to be unrecoverably broken.
2112 // Ignore already broken or zombie connections.
2113 if (connection->status == Connection::STATUS_NORMAL) {
2114 connection->status = Connection::STATUS_BROKEN;
2115
2116 if (notify) {
2117 // Notify other system components.
2118 onDispatchCycleBrokenLocked(currentTime, connection);
2119 }
2120 }
2121}
2122
2123void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2124 while (!queue->isEmpty()) {
2125 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2126 releaseDispatchEntryLocked(dispatchEntry);
2127 }
2128}
2129
2130void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2131 if (dispatchEntry->hasForegroundTarget()) {
2132 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2133 }
2134 delete dispatchEntry;
2135}
2136
2137int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2138 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2139
2140 { // acquire lock
2141 AutoMutex _l(d->mLock);
2142
2143 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2144 if (connectionIndex < 0) {
2145 ALOGE("Received spurious receive callback for unknown input channel. "
2146 "fd=%d, events=0x%x", fd, events);
2147 return 0; // remove the callback
2148 }
2149
2150 bool notify;
2151 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2152 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2153 if (!(events & ALOOPER_EVENT_INPUT)) {
2154 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002155 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 return 1;
2157 }
2158
2159 nsecs_t currentTime = now();
2160 bool gotOne = false;
2161 status_t status;
2162 for (;;) {
2163 uint32_t seq;
2164 bool handled;
2165 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2166 if (status) {
2167 break;
2168 }
2169 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2170 gotOne = true;
2171 }
2172 if (gotOne) {
2173 d->runCommandsLockedInterruptible();
2174 if (status == WOULD_BLOCK) {
2175 return 1;
2176 }
2177 }
2178
2179 notify = status != DEAD_OBJECT || !connection->monitor;
2180 if (notify) {
2181 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002182 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 }
2184 } else {
2185 // Monitor channels are never explicitly unregistered.
2186 // We do it automatically when the remote endpoint is closed so don't warn
2187 // about them.
2188 notify = !connection->monitor;
2189 if (notify) {
2190 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002191 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 }
2193 }
2194
2195 // Unregister the channel.
2196 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2197 return 0; // remove the callback
2198 } // release lock
2199}
2200
2201void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2202 const CancelationOptions& options) {
2203 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2204 synthesizeCancelationEventsForConnectionLocked(
2205 mConnectionsByFd.valueAt(i), options);
2206 }
2207}
2208
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002209void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2210 const CancelationOptions& options) {
2211 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2212 synthesizeCancelationEventsForInputChannelLocked(mMonitoringChannels[i], options);
2213 }
2214}
2215
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2217 const sp<InputChannel>& channel, const CancelationOptions& options) {
2218 ssize_t index = getConnectionIndexLocked(channel);
2219 if (index >= 0) {
2220 synthesizeCancelationEventsForConnectionLocked(
2221 mConnectionsByFd.valueAt(index), options);
2222 }
2223}
2224
2225void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2226 const sp<Connection>& connection, const CancelationOptions& options) {
2227 if (connection->status == Connection::STATUS_BROKEN) {
2228 return;
2229 }
2230
2231 nsecs_t currentTime = now();
2232
2233 Vector<EventEntry*> cancelationEvents;
2234 connection->inputState.synthesizeCancelationEvents(currentTime,
2235 cancelationEvents, options);
2236
2237 if (!cancelationEvents.isEmpty()) {
2238#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002239 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002241 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 options.reason, options.mode);
2243#endif
2244 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2245 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2246 switch (cancelationEventEntry->type) {
2247 case EventEntry::TYPE_KEY:
2248 logOutboundKeyDetailsLocked("cancel - ",
2249 static_cast<KeyEntry*>(cancelationEventEntry));
2250 break;
2251 case EventEntry::TYPE_MOTION:
2252 logOutboundMotionDetailsLocked("cancel - ",
2253 static_cast<MotionEntry*>(cancelationEventEntry));
2254 break;
2255 }
2256
2257 InputTarget target;
2258 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2259 if (windowHandle != NULL) {
2260 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2261 target.xOffset = -windowInfo->frameLeft;
2262 target.yOffset = -windowInfo->frameTop;
2263 target.scaleFactor = windowInfo->scaleFactor;
2264 } else {
2265 target.xOffset = 0;
2266 target.yOffset = 0;
2267 target.scaleFactor = 1.0f;
2268 }
2269 target.inputChannel = connection->inputChannel;
2270 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2271
2272 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2273 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2274
2275 cancelationEventEntry->release();
2276 }
2277
2278 startDispatchCycleLocked(currentTime, connection);
2279 }
2280}
2281
2282InputDispatcher::MotionEntry*
2283InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2284 ALOG_ASSERT(pointerIds.value != 0);
2285
2286 uint32_t splitPointerIndexMap[MAX_POINTERS];
2287 PointerProperties splitPointerProperties[MAX_POINTERS];
2288 PointerCoords splitPointerCoords[MAX_POINTERS];
2289
2290 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2291 uint32_t splitPointerCount = 0;
2292
2293 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2294 originalPointerIndex++) {
2295 const PointerProperties& pointerProperties =
2296 originalMotionEntry->pointerProperties[originalPointerIndex];
2297 uint32_t pointerId = uint32_t(pointerProperties.id);
2298 if (pointerIds.hasBit(pointerId)) {
2299 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2300 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2301 splitPointerCoords[splitPointerCount].copyFrom(
2302 originalMotionEntry->pointerCoords[originalPointerIndex]);
2303 splitPointerCount += 1;
2304 }
2305 }
2306
2307 if (splitPointerCount != pointerIds.count()) {
2308 // This is bad. We are missing some of the pointers that we expected to deliver.
2309 // Most likely this indicates that we received an ACTION_MOVE events that has
2310 // different pointer ids than we expected based on the previous ACTION_DOWN
2311 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2312 // in this way.
2313 ALOGW("Dropping split motion event because the pointer count is %d but "
2314 "we expected there to be %d pointers. This probably means we received "
2315 "a broken sequence of pointer ids from the input device.",
2316 splitPointerCount, pointerIds.count());
2317 return NULL;
2318 }
2319
2320 int32_t action = originalMotionEntry->action;
2321 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2322 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2323 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2324 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2325 const PointerProperties& pointerProperties =
2326 originalMotionEntry->pointerProperties[originalPointerIndex];
2327 uint32_t pointerId = uint32_t(pointerProperties.id);
2328 if (pointerIds.hasBit(pointerId)) {
2329 if (pointerIds.count() == 1) {
2330 // The first/last pointer went down/up.
2331 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2332 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2333 } else {
2334 // A secondary pointer went down/up.
2335 uint32_t splitPointerIndex = 0;
2336 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2337 splitPointerIndex += 1;
2338 }
2339 action = maskedAction | (splitPointerIndex
2340 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2341 }
2342 } else {
2343 // An unrelated pointer changed.
2344 action = AMOTION_EVENT_ACTION_MOVE;
2345 }
2346 }
2347
2348 MotionEntry* splitMotionEntry = new MotionEntry(
2349 originalMotionEntry->eventTime,
2350 originalMotionEntry->deviceId,
2351 originalMotionEntry->source,
2352 originalMotionEntry->policyFlags,
2353 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002354 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 originalMotionEntry->flags,
2356 originalMotionEntry->metaState,
2357 originalMotionEntry->buttonState,
2358 originalMotionEntry->edgeFlags,
2359 originalMotionEntry->xPrecision,
2360 originalMotionEntry->yPrecision,
2361 originalMotionEntry->downTime,
2362 originalMotionEntry->displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002363 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364
2365 if (originalMotionEntry->injectionState) {
2366 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2367 splitMotionEntry->injectionState->refCount += 1;
2368 }
2369
2370 return splitMotionEntry;
2371}
2372
2373void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2374#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002375 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376#endif
2377
2378 bool needWake;
2379 { // acquire lock
2380 AutoMutex _l(mLock);
2381
2382 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2383 needWake = enqueueInboundEventLocked(newEntry);
2384 } // release lock
2385
2386 if (needWake) {
2387 mLooper->wake();
2388 }
2389}
2390
2391void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2392#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002393 ALOGD("notifyKey - eventTime=%" PRId64
2394 ", deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
2395 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 args->eventTime, args->deviceId, args->source, args->policyFlags,
2397 args->action, args->flags, args->keyCode, args->scanCode,
2398 args->metaState, args->downTime);
2399#endif
2400 if (!validateKeyEvent(args->action)) {
2401 return;
2402 }
2403
2404 uint32_t policyFlags = args->policyFlags;
2405 int32_t flags = args->flags;
2406 int32_t metaState = args->metaState;
2407 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2408 policyFlags |= POLICY_FLAG_VIRTUAL;
2409 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2410 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002411 if (policyFlags & POLICY_FLAG_FUNCTION) {
2412 metaState |= AMETA_FUNCTION_ON;
2413 }
2414
2415 policyFlags |= POLICY_FLAG_TRUSTED;
2416
Michael Wright78f24442014-08-06 15:55:28 -07002417 int32_t keyCode = args->keyCode;
2418 if (metaState & AMETA_META_ON && args->action == AKEY_EVENT_ACTION_DOWN) {
2419 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2420 if (keyCode == AKEYCODE_DEL) {
2421 newKeyCode = AKEYCODE_BACK;
2422 } else if (keyCode == AKEYCODE_ENTER) {
2423 newKeyCode = AKEYCODE_HOME;
2424 }
2425 if (newKeyCode != AKEYCODE_UNKNOWN) {
2426 AutoMutex _l(mLock);
2427 struct KeyReplacement replacement = {keyCode, args->deviceId};
2428 mReplacedKeys.add(replacement, newKeyCode);
2429 keyCode = newKeyCode;
Evan Roskye71f0552017-03-21 18:12:36 -07002430 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
Michael Wright78f24442014-08-06 15:55:28 -07002431 }
2432 } else if (args->action == AKEY_EVENT_ACTION_UP) {
2433 // In order to maintain a consistent stream of up and down events, check to see if the key
2434 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2435 // even if the modifier was released between the down and the up events.
2436 AutoMutex _l(mLock);
2437 struct KeyReplacement replacement = {keyCode, args->deviceId};
2438 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2439 if (index >= 0) {
2440 keyCode = mReplacedKeys.valueAt(index);
2441 mReplacedKeys.removeItemsAt(index);
Evan Roskye71f0552017-03-21 18:12:36 -07002442 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
Michael Wright78f24442014-08-06 15:55:28 -07002443 }
2444 }
2445
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446 KeyEvent event;
2447 event.initialize(args->deviceId, args->source, args->action,
Michael Wright78f24442014-08-06 15:55:28 -07002448 flags, keyCode, args->scanCode, metaState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 args->downTime, args->eventTime);
2450
2451 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2452
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 bool needWake;
2454 { // acquire lock
2455 mLock.lock();
2456
2457 if (shouldSendKeyToInputFilterLocked(args)) {
2458 mLock.unlock();
2459
2460 policyFlags |= POLICY_FLAG_FILTERED;
2461 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2462 return; // event was consumed by the filter
2463 }
2464
2465 mLock.lock();
2466 }
2467
2468 int32_t repeatCount = 0;
2469 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2470 args->deviceId, args->source, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002471 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 metaState, repeatCount, args->downTime);
2473
2474 needWake = enqueueInboundEventLocked(newEntry);
2475 mLock.unlock();
2476 } // release lock
2477
2478 if (needWake) {
2479 mLooper->wake();
2480 }
2481}
2482
2483bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2484 return mInputFilterEnabled;
2485}
2486
2487void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2488#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002489 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002490 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002491 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492 args->eventTime, args->deviceId, args->source, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002493 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2495 for (uint32_t i = 0; i < args->pointerCount; i++) {
2496 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2497 "x=%f, y=%f, pressure=%f, size=%f, "
2498 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2499 "orientation=%f",
2500 i, args->pointerProperties[i].id,
2501 args->pointerProperties[i].toolType,
2502 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2503 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2504 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2505 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2506 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2507 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2508 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2509 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2510 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2511 }
2512#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002513 if (!validateMotionEvent(args->action, args->actionButton,
2514 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515 return;
2516 }
2517
2518 uint32_t policyFlags = args->policyFlags;
2519 policyFlags |= POLICY_FLAG_TRUSTED;
2520 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
2521
2522 bool needWake;
2523 { // acquire lock
2524 mLock.lock();
2525
2526 if (shouldSendMotionToInputFilterLocked(args)) {
2527 mLock.unlock();
2528
2529 MotionEvent event;
Michael Wright7b159c92015-05-14 14:48:03 +01002530 event.initialize(args->deviceId, args->source, args->action, args->actionButton,
2531 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2532 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 args->downTime, args->eventTime,
2534 args->pointerCount, args->pointerProperties, args->pointerCoords);
2535
2536 policyFlags |= POLICY_FLAG_FILTERED;
2537 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2538 return; // event was consumed by the filter
2539 }
2540
2541 mLock.lock();
2542 }
2543
2544 // Just enqueue a new motion event.
2545 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2546 args->deviceId, args->source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002547 args->action, args->actionButton, args->flags,
2548 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2550 args->displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002551 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552
2553 needWake = enqueueInboundEventLocked(newEntry);
2554 mLock.unlock();
2555 } // release lock
2556
2557 if (needWake) {
2558 mLooper->wake();
2559 }
2560}
2561
2562bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2563 // TODO: support sending secondary display events to input filter
2564 return mInputFilterEnabled && isMainDisplay(args->displayId);
2565}
2566
2567void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2568#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002569 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2570 "switchMask=0x%08x",
2571 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572#endif
2573
2574 uint32_t policyFlags = args->policyFlags;
2575 policyFlags |= POLICY_FLAG_TRUSTED;
2576 mPolicy->notifySwitch(args->eventTime,
2577 args->switchValues, args->switchMask, policyFlags);
2578}
2579
2580void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2581#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002582 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 args->eventTime, args->deviceId);
2584#endif
2585
2586 bool needWake;
2587 { // acquire lock
2588 AutoMutex _l(mLock);
2589
2590 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2591 needWake = enqueueInboundEventLocked(newEntry);
2592 } // release lock
2593
2594 if (needWake) {
2595 mLooper->wake();
2596 }
2597}
2598
Jeff Brownf086ddb2014-02-11 14:28:48 -08002599int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2601 uint32_t policyFlags) {
2602#if DEBUG_INBOUND_EVENT_DETAILS
2603 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Tarandeep Singh58641502017-07-31 10:51:54 -07002604 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x, displayId=%d",
2605 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags,
2606 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607#endif
2608
2609 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2610
2611 policyFlags |= POLICY_FLAG_INJECTED;
2612 if (hasInjectionPermission(injectorPid, injectorUid)) {
2613 policyFlags |= POLICY_FLAG_TRUSTED;
2614 }
2615
2616 EventEntry* firstInjectedEntry;
2617 EventEntry* lastInjectedEntry;
2618 switch (event->getType()) {
2619 case AINPUT_EVENT_TYPE_KEY: {
2620 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2621 int32_t action = keyEvent->getAction();
2622 if (! validateKeyEvent(action)) {
2623 return INPUT_EVENT_INJECTION_FAILED;
2624 }
2625
2626 int32_t flags = keyEvent->getFlags();
2627 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2628 policyFlags |= POLICY_FLAG_VIRTUAL;
2629 }
2630
2631 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2632 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2633 }
2634
Michael Wrightd02c5b62014-02-10 15:10:22 -08002635 mLock.lock();
2636 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
2637 keyEvent->getDeviceId(), keyEvent->getSource(),
2638 policyFlags, action, flags,
2639 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
2640 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2641 lastInjectedEntry = firstInjectedEntry;
2642 break;
2643 }
2644
2645 case AINPUT_EVENT_TYPE_MOTION: {
2646 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 int32_t action = motionEvent->getAction();
2648 size_t pointerCount = motionEvent->getPointerCount();
2649 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002650 int32_t actionButton = motionEvent->getActionButton();
2651 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652 return INPUT_EVENT_INJECTION_FAILED;
2653 }
2654
2655 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2656 nsecs_t eventTime = motionEvent->getEventTime();
2657 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2658 }
2659
2660 mLock.lock();
2661 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2662 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2663 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
2664 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002665 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666 motionEvent->getMetaState(), motionEvent->getButtonState(),
2667 motionEvent->getEdgeFlags(),
2668 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2669 motionEvent->getDownTime(), displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002670 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2671 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672 lastInjectedEntry = firstInjectedEntry;
2673 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2674 sampleEventTimes += 1;
2675 samplePointerCoords += pointerCount;
2676 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2677 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002678 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679 motionEvent->getMetaState(), motionEvent->getButtonState(),
2680 motionEvent->getEdgeFlags(),
2681 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2682 motionEvent->getDownTime(), displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002683 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2684 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 lastInjectedEntry->next = nextInjectedEntry;
2686 lastInjectedEntry = nextInjectedEntry;
2687 }
2688 break;
2689 }
2690
2691 default:
2692 ALOGW("Cannot inject event of type %d", event->getType());
2693 return INPUT_EVENT_INJECTION_FAILED;
2694 }
2695
2696 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2697 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2698 injectionState->injectionIsAsync = true;
2699 }
2700
2701 injectionState->refCount += 1;
2702 lastInjectedEntry->injectionState = injectionState;
2703
2704 bool needWake = false;
2705 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2706 EventEntry* nextEntry = entry->next;
2707 needWake |= enqueueInboundEventLocked(entry);
2708 entry = nextEntry;
2709 }
2710
2711 mLock.unlock();
2712
2713 if (needWake) {
2714 mLooper->wake();
2715 }
2716
2717 int32_t injectionResult;
2718 { // acquire lock
2719 AutoMutex _l(mLock);
2720
2721 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2722 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2723 } else {
2724 for (;;) {
2725 injectionResult = injectionState->injectionResult;
2726 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2727 break;
2728 }
2729
2730 nsecs_t remainingTimeout = endTime - now();
2731 if (remainingTimeout <= 0) {
2732#if DEBUG_INJECTION
2733 ALOGD("injectInputEvent - Timed out waiting for injection result "
2734 "to become available.");
2735#endif
2736 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2737 break;
2738 }
2739
2740 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2741 }
2742
2743 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2744 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2745 while (injectionState->pendingForegroundDispatches != 0) {
2746#if DEBUG_INJECTION
2747 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2748 injectionState->pendingForegroundDispatches);
2749#endif
2750 nsecs_t remainingTimeout = endTime - now();
2751 if (remainingTimeout <= 0) {
2752#if DEBUG_INJECTION
2753 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2754 "dispatches to finish.");
2755#endif
2756 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2757 break;
2758 }
2759
2760 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2761 }
2762 }
2763 }
2764
2765 injectionState->release();
2766 } // release lock
2767
2768#if DEBUG_INJECTION
2769 ALOGD("injectInputEvent - Finished with result %d. "
2770 "injectorPid=%d, injectorUid=%d",
2771 injectionResult, injectorPid, injectorUid);
2772#endif
2773
2774 return injectionResult;
2775}
2776
2777bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2778 return injectorUid == 0
2779 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2780}
2781
2782void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2783 InjectionState* injectionState = entry->injectionState;
2784 if (injectionState) {
2785#if DEBUG_INJECTION
2786 ALOGD("Setting input event injection result to %d. "
2787 "injectorPid=%d, injectorUid=%d",
2788 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2789#endif
2790
2791 if (injectionState->injectionIsAsync
2792 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2793 // Log the outcome since the injector did not wait for the injection result.
2794 switch (injectionResult) {
2795 case INPUT_EVENT_INJECTION_SUCCEEDED:
2796 ALOGV("Asynchronous input event injection succeeded.");
2797 break;
2798 case INPUT_EVENT_INJECTION_FAILED:
2799 ALOGW("Asynchronous input event injection failed.");
2800 break;
2801 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2802 ALOGW("Asynchronous input event injection permission denied.");
2803 break;
2804 case INPUT_EVENT_INJECTION_TIMED_OUT:
2805 ALOGW("Asynchronous input event injection timed out.");
2806 break;
2807 }
2808 }
2809
2810 injectionState->injectionResult = injectionResult;
2811 mInjectionResultAvailableCondition.broadcast();
2812 }
2813}
2814
2815void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2816 InjectionState* injectionState = entry->injectionState;
2817 if (injectionState) {
2818 injectionState->pendingForegroundDispatches += 1;
2819 }
2820}
2821
2822void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2823 InjectionState* injectionState = entry->injectionState;
2824 if (injectionState) {
2825 injectionState->pendingForegroundDispatches -= 1;
2826
2827 if (injectionState->pendingForegroundDispatches == 0) {
2828 mInjectionSyncFinishedCondition.broadcast();
2829 }
2830 }
2831}
2832
2833sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2834 const sp<InputChannel>& inputChannel) const {
2835 size_t numWindows = mWindowHandles.size();
2836 for (size_t i = 0; i < numWindows; i++) {
2837 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2838 if (windowHandle->getInputChannel() == inputChannel) {
2839 return windowHandle;
2840 }
2841 }
2842 return NULL;
2843}
2844
2845bool InputDispatcher::hasWindowHandleLocked(
2846 const sp<InputWindowHandle>& windowHandle) const {
2847 size_t numWindows = mWindowHandles.size();
2848 for (size_t i = 0; i < numWindows; i++) {
2849 if (mWindowHandles.itemAt(i) == windowHandle) {
2850 return true;
2851 }
2852 }
2853 return false;
2854}
2855
2856void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
2857#if DEBUG_FOCUS
2858 ALOGD("setInputWindows");
2859#endif
2860 { // acquire lock
2861 AutoMutex _l(mLock);
2862
2863 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
2864 mWindowHandles = inputWindowHandles;
2865
2866 sp<InputWindowHandle> newFocusedWindowHandle;
2867 bool foundHoveredWindow = false;
2868 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2869 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2870 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
2871 mWindowHandles.removeAt(i--);
2872 continue;
2873 }
2874 if (windowHandle->getInfo()->hasFocus) {
2875 newFocusedWindowHandle = windowHandle;
2876 }
2877 if (windowHandle == mLastHoverWindowHandle) {
2878 foundHoveredWindow = true;
2879 }
2880 }
2881
2882 if (!foundHoveredWindow) {
2883 mLastHoverWindowHandle = NULL;
2884 }
2885
2886 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2887 if (mFocusedWindowHandle != NULL) {
2888#if DEBUG_FOCUS
2889 ALOGD("Focus left window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002890 mFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891#endif
2892 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2893 if (focusedInputChannel != NULL) {
2894 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2895 "focus left window");
2896 synthesizeCancelationEventsForInputChannelLocked(
2897 focusedInputChannel, options);
2898 }
2899 }
2900 if (newFocusedWindowHandle != NULL) {
2901#if DEBUG_FOCUS
2902 ALOGD("Focus entered window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002903 newFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904#endif
2905 }
2906 mFocusedWindowHandle = newFocusedWindowHandle;
2907 }
2908
Jeff Brownf086ddb2014-02-11 14:28:48 -08002909 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
2910 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
Ivan Lozano96f12992017-11-09 14:45:38 -08002911 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08002912 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
2913 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914#if DEBUG_FOCUS
Jeff Brownf086ddb2014-02-11 14:28:48 -08002915 ALOGD("Touched window was removed: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002916 touchedWindow.windowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08002918 sp<InputChannel> touchedInputChannel =
2919 touchedWindow.windowHandle->getInputChannel();
2920 if (touchedInputChannel != NULL) {
2921 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2922 "touched window was removed");
2923 synthesizeCancelationEventsForInputChannelLocked(
2924 touchedInputChannel, options);
2925 }
Ivan Lozano96f12992017-11-09 14:45:38 -08002926 state.windows.removeAt(i);
2927 } else {
2928 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 }
2931 }
2932
2933 // Release information for windows that are no longer present.
2934 // This ensures that unused input channels are released promptly.
2935 // Otherwise, they might stick around until the window handle is destroyed
2936 // which might not happen until the next GC.
2937 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2938 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2939 if (!hasWindowHandleLocked(oldWindowHandle)) {
2940#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002941 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942#endif
2943 oldWindowHandle->releaseInfo();
2944 }
2945 }
2946 } // release lock
2947
2948 // Wake up poll loop since it may need to make new input dispatching choices.
2949 mLooper->wake();
2950}
2951
2952void InputDispatcher::setFocusedApplication(
2953 const sp<InputApplicationHandle>& inputApplicationHandle) {
2954#if DEBUG_FOCUS
2955 ALOGD("setFocusedApplication");
2956#endif
2957 { // acquire lock
2958 AutoMutex _l(mLock);
2959
2960 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
2961 if (mFocusedApplicationHandle != inputApplicationHandle) {
2962 if (mFocusedApplicationHandle != NULL) {
2963 resetANRTimeoutsLocked();
2964 mFocusedApplicationHandle->releaseInfo();
2965 }
2966 mFocusedApplicationHandle = inputApplicationHandle;
2967 }
2968 } else if (mFocusedApplicationHandle != NULL) {
2969 resetANRTimeoutsLocked();
2970 mFocusedApplicationHandle->releaseInfo();
2971 mFocusedApplicationHandle.clear();
2972 }
2973
2974#if DEBUG_FOCUS
2975 //logDispatchStateLocked();
2976#endif
2977 } // release lock
2978
2979 // Wake up poll loop since it may need to make new input dispatching choices.
2980 mLooper->wake();
2981}
2982
2983void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2984#if DEBUG_FOCUS
2985 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2986#endif
2987
2988 bool changed;
2989 { // acquire lock
2990 AutoMutex _l(mLock);
2991
2992 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
2993 if (mDispatchFrozen && !frozen) {
2994 resetANRTimeoutsLocked();
2995 }
2996
2997 if (mDispatchEnabled && !enabled) {
2998 resetAndDropEverythingLocked("dispatcher is being disabled");
2999 }
3000
3001 mDispatchEnabled = enabled;
3002 mDispatchFrozen = frozen;
3003 changed = true;
3004 } else {
3005 changed = false;
3006 }
3007
3008#if DEBUG_FOCUS
3009 //logDispatchStateLocked();
3010#endif
3011 } // release lock
3012
3013 if (changed) {
3014 // Wake up poll loop since it may need to make new input dispatching choices.
3015 mLooper->wake();
3016 }
3017}
3018
3019void InputDispatcher::setInputFilterEnabled(bool enabled) {
3020#if DEBUG_FOCUS
3021 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3022#endif
3023
3024 { // acquire lock
3025 AutoMutex _l(mLock);
3026
3027 if (mInputFilterEnabled == enabled) {
3028 return;
3029 }
3030
3031 mInputFilterEnabled = enabled;
3032 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3033 } // release lock
3034
3035 // Wake up poll loop since there might be work to do to drop everything.
3036 mLooper->wake();
3037}
3038
3039bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3040 const sp<InputChannel>& toChannel) {
3041#if DEBUG_FOCUS
3042 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003043 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044#endif
3045 { // acquire lock
3046 AutoMutex _l(mLock);
3047
3048 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3049 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3050 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
3051#if DEBUG_FOCUS
3052 ALOGD("Cannot transfer focus because from or to window not found.");
3053#endif
3054 return false;
3055 }
3056 if (fromWindowHandle == toWindowHandle) {
3057#if DEBUG_FOCUS
3058 ALOGD("Trivial transfer to same window.");
3059#endif
3060 return true;
3061 }
3062 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3063#if DEBUG_FOCUS
3064 ALOGD("Cannot transfer focus because windows are on different displays.");
3065#endif
3066 return false;
3067 }
3068
3069 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003070 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3071 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3072 for (size_t i = 0; i < state.windows.size(); i++) {
3073 const TouchedWindow& touchedWindow = state.windows[i];
3074 if (touchedWindow.windowHandle == fromWindowHandle) {
3075 int32_t oldTargetFlags = touchedWindow.targetFlags;
3076 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077
Jeff Brownf086ddb2014-02-11 14:28:48 -08003078 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079
Jeff Brownf086ddb2014-02-11 14:28:48 -08003080 int32_t newTargetFlags = oldTargetFlags
3081 & (InputTarget::FLAG_FOREGROUND
3082 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3083 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084
Jeff Brownf086ddb2014-02-11 14:28:48 -08003085 found = true;
3086 goto Found;
3087 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 }
3089 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003090Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091
3092 if (! found) {
3093#if DEBUG_FOCUS
3094 ALOGD("Focus transfer failed because from window did not have focus.");
3095#endif
3096 return false;
3097 }
3098
3099 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3100 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3101 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3102 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3103 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3104
3105 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3106 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3107 "transferring touch focus from this window to another window");
3108 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3109 }
3110
3111#if DEBUG_FOCUS
3112 logDispatchStateLocked();
3113#endif
3114 } // release lock
3115
3116 // Wake up poll loop since it may need to make new input dispatching choices.
3117 mLooper->wake();
3118 return true;
3119}
3120
3121void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3122#if DEBUG_FOCUS
3123 ALOGD("Resetting and dropping all events (%s).", reason);
3124#endif
3125
3126 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3127 synthesizeCancelationEventsForAllConnectionsLocked(options);
3128
3129 resetKeyRepeatLocked();
3130 releasePendingEventLocked();
3131 drainInboundQueueLocked();
3132 resetANRTimeoutsLocked();
3133
Jeff Brownf086ddb2014-02-11 14:28:48 -08003134 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003136 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003137}
3138
3139void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003140 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141 dumpDispatchStateLocked(dump);
3142
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003143 std::istringstream stream(dump);
3144 std::string line;
3145
3146 while (std::getline(stream, line, '\n')) {
3147 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 }
3149}
3150
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003151void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3152 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3153 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154
3155 if (mFocusedApplicationHandle != NULL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003156 dump += StringPrintf(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
3157 mFocusedApplicationHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 mFocusedApplicationHandle->getDispatchingTimeout(
3159 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3160 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003161 dump += StringPrintf(INDENT "FocusedApplication: <null>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003163 dump += StringPrintf(INDENT "FocusedWindow: name='%s'\n",
3164 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().c_str() : "<null>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165
Jeff Brownf086ddb2014-02-11 14:28:48 -08003166 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003167 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003168 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3169 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003170 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003171 state.displayId, toString(state.down), toString(state.split),
3172 state.deviceId, state.source);
3173 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003174 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003175 for (size_t i = 0; i < state.windows.size(); i++) {
3176 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003177 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3178 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003179 touchedWindow.pointerIds.value,
3180 touchedWindow.targetFlags);
3181 }
3182 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003183 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003184 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 }
3186 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003187 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 }
3189
3190 if (!mWindowHandles.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003191 dump += INDENT "Windows:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3193 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3194 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3195
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003196 dump += StringPrintf(INDENT2 "%zu: name='%s', displayId=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3198 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3199 "frame=[%d,%d][%d,%d], scale=%f, "
3200 "touchableRegion=",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003201 i, windowInfo->name.c_str(), windowInfo->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202 toString(windowInfo->paused),
3203 toString(windowInfo->hasFocus),
3204 toString(windowInfo->hasWallpaper),
3205 toString(windowInfo->visible),
3206 toString(windowInfo->canReceiveKeys),
3207 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3208 windowInfo->layer,
3209 windowInfo->frameLeft, windowInfo->frameTop,
3210 windowInfo->frameRight, windowInfo->frameBottom,
3211 windowInfo->scaleFactor);
3212 dumpRegion(dump, windowInfo->touchableRegion);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003213 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3214 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215 windowInfo->ownerPid, windowInfo->ownerUid,
3216 windowInfo->dispatchingTimeout / 1000000.0);
3217 }
3218 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003219 dump += INDENT "Windows: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 }
3221
3222 if (!mMonitoringChannels.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003223 dump += INDENT "MonitoringChannels:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3225 const sp<InputChannel>& channel = mMonitoringChannels[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003226 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 }
3228 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003229 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 }
3231
3232 nsecs_t currentTime = now();
3233
3234 // Dump recently dispatched or dropped events from oldest to newest.
3235 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003236 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003238 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003240 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 (currentTime - entry->eventTime) * 0.000001f);
3242 }
3243 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003244 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 }
3246
3247 // Dump event currently being dispatched.
3248 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003249 dump += INDENT "PendingEvent:\n";
3250 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003252 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3254 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003255 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 }
3257
3258 // Dump inbound events from oldest to newest.
3259 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003260 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003262 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003264 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265 (currentTime - entry->eventTime) * 0.000001f);
3266 }
3267 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003268 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269 }
3270
Michael Wright78f24442014-08-06 15:55:28 -07003271 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003272 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003273 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3274 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3275 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003276 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003277 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3278 }
3279 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003280 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003281 }
3282
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003284 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3286 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003287 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003289 i, connection->getInputChannelName().c_str(),
3290 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 connection->getStatusLabel(), toString(connection->monitor),
3292 toString(connection->inputPublisherBlocked));
3293
3294 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003295 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 connection->outboundQueue.count());
3297 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3298 entry = entry->next) {
3299 dump.append(INDENT4);
3300 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003301 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 entry->targetFlags, entry->resolvedAction,
3303 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3304 }
3305 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003306 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307 }
3308
3309 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003310 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 connection->waitQueue.count());
3312 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3313 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003314 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003316 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317 "age=%0.1fms, wait=%0.1fms\n",
3318 entry->targetFlags, entry->resolvedAction,
3319 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3320 (currentTime - entry->deliveryTime) * 0.000001f);
3321 }
3322 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003323 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 }
3325 }
3326 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003327 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328 }
3329
3330 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003331 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 (mAppSwitchDueTime - now()) / 1000000.0);
3333 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003334 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335 }
3336
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003337 dump += INDENT "Configuration:\n";
3338 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003340 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 mConfig.keyRepeatTimeout * 0.000001f);
3342}
3343
3344status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3345 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
3346#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003347 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 toString(monitor));
3349#endif
3350
3351 { // acquire lock
3352 AutoMutex _l(mLock);
3353
3354 if (getConnectionIndexLocked(inputChannel) >= 0) {
3355 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003356 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 return BAD_VALUE;
3358 }
3359
3360 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3361
3362 int fd = inputChannel->getFd();
3363 mConnectionsByFd.add(fd, connection);
3364
3365 if (monitor) {
3366 mMonitoringChannels.push(inputChannel);
3367 }
3368
3369 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3370 } // release lock
3371
3372 // Wake the looper because some connections have changed.
3373 mLooper->wake();
3374 return OK;
3375}
3376
3377status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3378#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003379 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380#endif
3381
3382 { // acquire lock
3383 AutoMutex _l(mLock);
3384
3385 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3386 if (status) {
3387 return status;
3388 }
3389 } // release lock
3390
3391 // Wake the poll loop because removing the connection may have changed the current
3392 // synchronization state.
3393 mLooper->wake();
3394 return OK;
3395}
3396
3397status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3398 bool notify) {
3399 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3400 if (connectionIndex < 0) {
3401 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003402 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 return BAD_VALUE;
3404 }
3405
3406 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3407 mConnectionsByFd.removeItemsAt(connectionIndex);
3408
3409 if (connection->monitor) {
3410 removeMonitorChannelLocked(inputChannel);
3411 }
3412
3413 mLooper->removeFd(inputChannel->getFd());
3414
3415 nsecs_t currentTime = now();
3416 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3417
3418 connection->status = Connection::STATUS_ZOMBIE;
3419 return OK;
3420}
3421
3422void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3423 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3424 if (mMonitoringChannels[i] == inputChannel) {
3425 mMonitoringChannels.removeAt(i);
3426 break;
3427 }
3428 }
3429}
3430
3431ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
3432 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3433 if (connectionIndex >= 0) {
3434 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3435 if (connection->inputChannel.get() == inputChannel.get()) {
3436 return connectionIndex;
3437 }
3438 }
3439
3440 return -1;
3441}
3442
3443void InputDispatcher::onDispatchCycleFinishedLocked(
3444 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3445 CommandEntry* commandEntry = postCommandLocked(
3446 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3447 commandEntry->connection = connection;
3448 commandEntry->eventTime = currentTime;
3449 commandEntry->seq = seq;
3450 commandEntry->handled = handled;
3451}
3452
3453void InputDispatcher::onDispatchCycleBrokenLocked(
3454 nsecs_t currentTime, const sp<Connection>& connection) {
3455 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003456 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457
3458 CommandEntry* commandEntry = postCommandLocked(
3459 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3460 commandEntry->connection = connection;
3461}
3462
3463void InputDispatcher::onANRLocked(
3464 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3465 const sp<InputWindowHandle>& windowHandle,
3466 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3467 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3468 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3469 ALOGI("Application is not responding: %s. "
3470 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003471 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472 dispatchLatency, waitDuration, reason);
3473
3474 // Capture a record of the InputDispatcher state at the time of the ANR.
3475 time_t t = time(NULL);
3476 struct tm tm;
3477 localtime_r(&t, &tm);
3478 char timestr[64];
3479 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3480 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003481 mLastANRState += INDENT "ANR:\n";
3482 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3483 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3484 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3485 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3486 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3487 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488 dumpDispatchStateLocked(mLastANRState);
3489
3490 CommandEntry* commandEntry = postCommandLocked(
3491 & InputDispatcher::doNotifyANRLockedInterruptible);
3492 commandEntry->inputApplicationHandle = applicationHandle;
3493 commandEntry->inputWindowHandle = windowHandle;
3494 commandEntry->reason = reason;
3495}
3496
3497void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3498 CommandEntry* commandEntry) {
3499 mLock.unlock();
3500
3501 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3502
3503 mLock.lock();
3504}
3505
3506void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3507 CommandEntry* commandEntry) {
3508 sp<Connection> connection = commandEntry->connection;
3509
3510 if (connection->status != Connection::STATUS_ZOMBIE) {
3511 mLock.unlock();
3512
3513 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3514
3515 mLock.lock();
3516 }
3517}
3518
3519void InputDispatcher::doNotifyANRLockedInterruptible(
3520 CommandEntry* commandEntry) {
3521 mLock.unlock();
3522
3523 nsecs_t newTimeout = mPolicy->notifyANR(
3524 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3525 commandEntry->reason);
3526
3527 mLock.lock();
3528
3529 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3530 commandEntry->inputWindowHandle != NULL
3531 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
3532}
3533
3534void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3535 CommandEntry* commandEntry) {
3536 KeyEntry* entry = commandEntry->keyEntry;
3537
3538 KeyEvent event;
3539 initializeKeyEvent(&event, entry);
3540
3541 mLock.unlock();
3542
3543 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3544 &event, entry->policyFlags);
3545
3546 mLock.lock();
3547
3548 if (delay < 0) {
3549 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3550 } else if (!delay) {
3551 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3552 } else {
3553 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3554 entry->interceptKeyWakeupTime = now() + delay;
3555 }
3556 entry->release();
3557}
3558
3559void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3560 CommandEntry* commandEntry) {
3561 sp<Connection> connection = commandEntry->connection;
3562 nsecs_t finishTime = commandEntry->eventTime;
3563 uint32_t seq = commandEntry->seq;
3564 bool handled = commandEntry->handled;
3565
3566 // Handle post-event policy actions.
3567 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3568 if (dispatchEntry) {
3569 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3570 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003571 std::string msg =
3572 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003573 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003575 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576 }
3577
3578 bool restartEvent;
3579 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3580 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3581 restartEvent = afterKeyEventLockedInterruptible(connection,
3582 dispatchEntry, keyEntry, handled);
3583 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3584 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3585 restartEvent = afterMotionEventLockedInterruptible(connection,
3586 dispatchEntry, motionEntry, handled);
3587 } else {
3588 restartEvent = false;
3589 }
3590
3591 // Dequeue the event and start the next cycle.
3592 // Note that because the lock might have been released, it is possible that the
3593 // contents of the wait queue to have been drained, so we need to double-check
3594 // a few things.
3595 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3596 connection->waitQueue.dequeue(dispatchEntry);
3597 traceWaitQueueLengthLocked(connection);
3598 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3599 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3600 traceOutboundQueueLengthLocked(connection);
3601 } else {
3602 releaseDispatchEntryLocked(dispatchEntry);
3603 }
3604 }
3605
3606 // Start the next dispatch cycle for this connection.
3607 startDispatchCycleLocked(now(), connection);
3608 }
3609}
3610
3611bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3612 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3613 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3614 // Get the fallback key state.
3615 // Clear it out after dispatching the UP.
3616 int32_t originalKeyCode = keyEntry->keyCode;
3617 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3618 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3619 connection->inputState.removeFallbackKey(originalKeyCode);
3620 }
3621
3622 if (handled || !dispatchEntry->hasForegroundTarget()) {
3623 // If the application handles the original key for which we previously
3624 // generated a fallback or if the window is not a foreground window,
3625 // then cancel the associated fallback key, if any.
3626 if (fallbackKeyCode != -1) {
3627 // Dispatch the unhandled key to the policy with the cancel flag.
3628#if DEBUG_OUTBOUND_EVENT_DETAILS
3629 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3630 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3631 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3632 keyEntry->policyFlags);
3633#endif
3634 KeyEvent event;
3635 initializeKeyEvent(&event, keyEntry);
3636 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3637
3638 mLock.unlock();
3639
3640 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3641 &event, keyEntry->policyFlags, &event);
3642
3643 mLock.lock();
3644
3645 // Cancel the fallback key.
3646 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3647 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3648 "application handled the original non-fallback key "
3649 "or is no longer a foreground target, "
3650 "canceling previously dispatched fallback key");
3651 options.keyCode = fallbackKeyCode;
3652 synthesizeCancelationEventsForConnectionLocked(connection, options);
3653 }
3654 connection->inputState.removeFallbackKey(originalKeyCode);
3655 }
3656 } else {
3657 // If the application did not handle a non-fallback key, first check
3658 // that we are in a good state to perform unhandled key event processing
3659 // Then ask the policy what to do with it.
3660 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3661 && keyEntry->repeatCount == 0;
3662 if (fallbackKeyCode == -1 && !initialDown) {
3663#if DEBUG_OUTBOUND_EVENT_DETAILS
3664 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3665 "since this is not an initial down. "
3666 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3667 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3668 keyEntry->policyFlags);
3669#endif
3670 return false;
3671 }
3672
3673 // Dispatch the unhandled key to the policy.
3674#if DEBUG_OUTBOUND_EVENT_DETAILS
3675 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
3676 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3677 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3678 keyEntry->policyFlags);
3679#endif
3680 KeyEvent event;
3681 initializeKeyEvent(&event, keyEntry);
3682
3683 mLock.unlock();
3684
3685 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3686 &event, keyEntry->policyFlags, &event);
3687
3688 mLock.lock();
3689
3690 if (connection->status != Connection::STATUS_NORMAL) {
3691 connection->inputState.removeFallbackKey(originalKeyCode);
3692 return false;
3693 }
3694
3695 // Latch the fallback keycode for this key on an initial down.
3696 // The fallback keycode cannot change at any other point in the lifecycle.
3697 if (initialDown) {
3698 if (fallback) {
3699 fallbackKeyCode = event.getKeyCode();
3700 } else {
3701 fallbackKeyCode = AKEYCODE_UNKNOWN;
3702 }
3703 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3704 }
3705
3706 ALOG_ASSERT(fallbackKeyCode != -1);
3707
3708 // Cancel the fallback key if the policy decides not to send it anymore.
3709 // We will continue to dispatch the key to the policy but we will no
3710 // longer dispatch a fallback key to the application.
3711 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3712 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3713#if DEBUG_OUTBOUND_EVENT_DETAILS
3714 if (fallback) {
3715 ALOGD("Unhandled key event: Policy requested to send key %d"
3716 "as a fallback for %d, but on the DOWN it had requested "
3717 "to send %d instead. Fallback canceled.",
3718 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3719 } else {
3720 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
3721 "but on the DOWN it had requested to send %d. "
3722 "Fallback canceled.",
3723 originalKeyCode, fallbackKeyCode);
3724 }
3725#endif
3726
3727 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3728 "canceling fallback, policy no longer desires it");
3729 options.keyCode = fallbackKeyCode;
3730 synthesizeCancelationEventsForConnectionLocked(connection, options);
3731
3732 fallback = false;
3733 fallbackKeyCode = AKEYCODE_UNKNOWN;
3734 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3735 connection->inputState.setFallbackKey(originalKeyCode,
3736 fallbackKeyCode);
3737 }
3738 }
3739
3740#if DEBUG_OUTBOUND_EVENT_DETAILS
3741 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003742 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3744 connection->inputState.getFallbackKeys();
3745 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003746 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747 fallbackKeys.valueAt(i));
3748 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003749 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003750 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 }
3752#endif
3753
3754 if (fallback) {
3755 // Restart the dispatch cycle using the fallback key.
3756 keyEntry->eventTime = event.getEventTime();
3757 keyEntry->deviceId = event.getDeviceId();
3758 keyEntry->source = event.getSource();
3759 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3760 keyEntry->keyCode = fallbackKeyCode;
3761 keyEntry->scanCode = event.getScanCode();
3762 keyEntry->metaState = event.getMetaState();
3763 keyEntry->repeatCount = event.getRepeatCount();
3764 keyEntry->downTime = event.getDownTime();
3765 keyEntry->syntheticRepeat = false;
3766
3767#if DEBUG_OUTBOUND_EVENT_DETAILS
3768 ALOGD("Unhandled key event: Dispatching fallback key. "
3769 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3770 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3771#endif
3772 return true; // restart the event
3773 } else {
3774#if DEBUG_OUTBOUND_EVENT_DETAILS
3775 ALOGD("Unhandled key event: No fallback key.");
3776#endif
3777 }
3778 }
3779 }
3780 return false;
3781}
3782
3783bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3784 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3785 return false;
3786}
3787
3788void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3789 mLock.unlock();
3790
3791 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
3792
3793 mLock.lock();
3794}
3795
3796void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3797 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3798 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3799 entry->downTime, entry->eventTime);
3800}
3801
3802void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3803 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3804 // TODO Write some statistics about how long we spend waiting.
3805}
3806
3807void InputDispatcher::traceInboundQueueLengthLocked() {
3808 if (ATRACE_ENABLED()) {
3809 ATRACE_INT("iq", mInboundQueue.count());
3810 }
3811}
3812
3813void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3814 if (ATRACE_ENABLED()) {
3815 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003816 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 ATRACE_INT(counterName, connection->outboundQueue.count());
3818 }
3819}
3820
3821void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3822 if (ATRACE_ENABLED()) {
3823 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003824 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 ATRACE_INT(counterName, connection->waitQueue.count());
3826 }
3827}
3828
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003829void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 AutoMutex _l(mLock);
3831
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003832 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 dumpDispatchStateLocked(dump);
3834
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003835 if (!mLastANRState.empty()) {
3836 dump += "\nInput Dispatcher State at time of last ANR:\n";
3837 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
3839}
3840
3841void InputDispatcher::monitor() {
3842 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3843 mLock.lock();
3844 mLooper->wake();
3845 mDispatcherIsAliveCondition.wait(mLock);
3846 mLock.unlock();
3847}
3848
3849
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850// --- InputDispatcher::InjectionState ---
3851
3852InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3853 refCount(1),
3854 injectorPid(injectorPid), injectorUid(injectorUid),
3855 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3856 pendingForegroundDispatches(0) {
3857}
3858
3859InputDispatcher::InjectionState::~InjectionState() {
3860}
3861
3862void InputDispatcher::InjectionState::release() {
3863 refCount -= 1;
3864 if (refCount == 0) {
3865 delete this;
3866 } else {
3867 ALOG_ASSERT(refCount > 0);
3868 }
3869}
3870
3871
3872// --- InputDispatcher::EventEntry ---
3873
3874InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3875 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3876 injectionState(NULL), dispatchInProgress(false) {
3877}
3878
3879InputDispatcher::EventEntry::~EventEntry() {
3880 releaseInjectionState();
3881}
3882
3883void InputDispatcher::EventEntry::release() {
3884 refCount -= 1;
3885 if (refCount == 0) {
3886 delete this;
3887 } else {
3888 ALOG_ASSERT(refCount > 0);
3889 }
3890}
3891
3892void InputDispatcher::EventEntry::releaseInjectionState() {
3893 if (injectionState) {
3894 injectionState->release();
3895 injectionState = NULL;
3896 }
3897}
3898
3899
3900// --- InputDispatcher::ConfigurationChangedEntry ---
3901
3902InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3903 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3904}
3905
3906InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3907}
3908
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003909void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
3910 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911}
3912
3913
3914// --- InputDispatcher::DeviceResetEntry ---
3915
3916InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3917 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3918 deviceId(deviceId) {
3919}
3920
3921InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3922}
3923
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003924void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
3925 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926 deviceId, policyFlags);
3927}
3928
3929
3930// --- InputDispatcher::KeyEntry ---
3931
3932InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
3933 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
3934 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3935 int32_t repeatCount, nsecs_t downTime) :
3936 EventEntry(TYPE_KEY, eventTime, policyFlags),
3937 deviceId(deviceId), source(source), action(action), flags(flags),
3938 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3939 repeatCount(repeatCount), downTime(downTime),
3940 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3941 interceptKeyWakeupTime(0) {
3942}
3943
3944InputDispatcher::KeyEntry::~KeyEntry() {
3945}
3946
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003947void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
3948 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, action=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
3950 "repeatCount=%d), policyFlags=0x%08x",
3951 deviceId, source, action, flags, keyCode, scanCode, metaState,
3952 repeatCount, policyFlags);
3953}
3954
3955void InputDispatcher::KeyEntry::recycle() {
3956 releaseInjectionState();
3957
3958 dispatchInProgress = false;
3959 syntheticRepeat = false;
3960 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
3961 interceptKeyWakeupTime = 0;
3962}
3963
3964
3965// --- InputDispatcher::MotionEntry ---
3966
Michael Wright7b159c92015-05-14 14:48:03 +01003967InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
3968 uint32_t source, uint32_t policyFlags, int32_t action, int32_t actionButton,
3969 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3970 float xPrecision, float yPrecision, nsecs_t downTime,
3971 int32_t displayId, uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08003972 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
3973 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 EventEntry(TYPE_MOTION, eventTime, policyFlags),
3975 eventTime(eventTime),
Michael Wright7b159c92015-05-14 14:48:03 +01003976 deviceId(deviceId), source(source), action(action), actionButton(actionButton),
3977 flags(flags), metaState(metaState), buttonState(buttonState),
3978 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003979 downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
3980 for (uint32_t i = 0; i < pointerCount; i++) {
3981 this->pointerProperties[i].copyFrom(pointerProperties[i]);
3982 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003983 if (xOffset || yOffset) {
3984 this->pointerCoords[i].applyOffset(xOffset, yOffset);
3985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003986 }
3987}
3988
3989InputDispatcher::MotionEntry::~MotionEntry() {
3990}
3991
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003992void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
3993 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, action=%d, actionButton=0x%08x, "
Michael Wright7b159c92015-05-14 14:48:03 +01003994 "flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
3995 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, displayId=%d, pointers=[",
3996 deviceId, source, action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997 xPrecision, yPrecision, displayId);
3998 for (uint32_t i = 0; i < pointerCount; i++) {
3999 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004000 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004002 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003 pointerCoords[i].getX(), pointerCoords[i].getY());
4004 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004005 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006}
4007
4008
4009// --- InputDispatcher::DispatchEntry ---
4010
4011volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4012
4013InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4014 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4015 seq(nextSeq()),
4016 eventEntry(eventEntry), targetFlags(targetFlags),
4017 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4018 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4019 eventEntry->refCount += 1;
4020}
4021
4022InputDispatcher::DispatchEntry::~DispatchEntry() {
4023 eventEntry->release();
4024}
4025
4026uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4027 // Sequence number 0 is reserved and will never be returned.
4028 uint32_t seq;
4029 do {
4030 seq = android_atomic_inc(&sNextSeqAtomic);
4031 } while (!seq);
4032 return seq;
4033}
4034
4035
4036// --- InputDispatcher::InputState ---
4037
4038InputDispatcher::InputState::InputState() {
4039}
4040
4041InputDispatcher::InputState::~InputState() {
4042}
4043
4044bool InputDispatcher::InputState::isNeutral() const {
4045 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4046}
4047
4048bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4049 int32_t displayId) const {
4050 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4051 const MotionMemento& memento = mMotionMementos.itemAt(i);
4052 if (memento.deviceId == deviceId
4053 && memento.source == source
4054 && memento.displayId == displayId
4055 && memento.hovering) {
4056 return true;
4057 }
4058 }
4059 return false;
4060}
4061
4062bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4063 int32_t action, int32_t flags) {
4064 switch (action) {
4065 case AKEY_EVENT_ACTION_UP: {
4066 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4067 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4068 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4069 mFallbackKeys.removeItemsAt(i);
4070 } else {
4071 i += 1;
4072 }
4073 }
4074 }
4075 ssize_t index = findKeyMemento(entry);
4076 if (index >= 0) {
4077 mKeyMementos.removeAt(index);
4078 return true;
4079 }
4080 /* FIXME: We can't just drop the key up event because that prevents creating
4081 * popup windows that are automatically shown when a key is held and then
4082 * dismissed when the key is released. The problem is that the popup will
4083 * not have received the original key down, so the key up will be considered
4084 * to be inconsistent with its observed state. We could perhaps handle this
4085 * by synthesizing a key down but that will cause other problems.
4086 *
4087 * So for now, allow inconsistent key up events to be dispatched.
4088 *
4089#if DEBUG_OUTBOUND_EVENT_DETAILS
4090 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4091 "keyCode=%d, scanCode=%d",
4092 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4093#endif
4094 return false;
4095 */
4096 return true;
4097 }
4098
4099 case AKEY_EVENT_ACTION_DOWN: {
4100 ssize_t index = findKeyMemento(entry);
4101 if (index >= 0) {
4102 mKeyMementos.removeAt(index);
4103 }
4104 addKeyMemento(entry, flags);
4105 return true;
4106 }
4107
4108 default:
4109 return true;
4110 }
4111}
4112
4113bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4114 int32_t action, int32_t flags) {
4115 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4116 switch (actionMasked) {
4117 case AMOTION_EVENT_ACTION_UP:
4118 case AMOTION_EVENT_ACTION_CANCEL: {
4119 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4120 if (index >= 0) {
4121 mMotionMementos.removeAt(index);
4122 return true;
4123 }
4124#if DEBUG_OUTBOUND_EVENT_DETAILS
4125 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4126 "actionMasked=%d",
4127 entry->deviceId, entry->source, actionMasked);
4128#endif
4129 return false;
4130 }
4131
4132 case AMOTION_EVENT_ACTION_DOWN: {
4133 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4134 if (index >= 0) {
4135 mMotionMementos.removeAt(index);
4136 }
4137 addMotionMemento(entry, flags, false /*hovering*/);
4138 return true;
4139 }
4140
4141 case AMOTION_EVENT_ACTION_POINTER_UP:
4142 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4143 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004144 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4145 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4146 // generate cancellation events for these since they're based in relative rather than
4147 // absolute units.
4148 return true;
4149 }
4150
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004152
4153 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4154 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4155 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4156 // other value and we need to track the motion so we can send cancellation events for
4157 // anything generating fallback events (e.g. DPad keys for joystick movements).
4158 if (index >= 0) {
4159 if (entry->pointerCoords[0].isEmpty()) {
4160 mMotionMementos.removeAt(index);
4161 } else {
4162 MotionMemento& memento = mMotionMementos.editItemAt(index);
4163 memento.setPointers(entry);
4164 }
4165 } else if (!entry->pointerCoords[0].isEmpty()) {
4166 addMotionMemento(entry, flags, false /*hovering*/);
4167 }
4168
4169 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4170 return true;
4171 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 if (index >= 0) {
4173 MotionMemento& memento = mMotionMementos.editItemAt(index);
4174 memento.setPointers(entry);
4175 return true;
4176 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177#if DEBUG_OUTBOUND_EVENT_DETAILS
4178 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
4179 "deviceId=%d, source=%08x, actionMasked=%d",
4180 entry->deviceId, entry->source, actionMasked);
4181#endif
4182 return false;
4183 }
4184
4185 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4186 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4187 if (index >= 0) {
4188 mMotionMementos.removeAt(index);
4189 return true;
4190 }
4191#if DEBUG_OUTBOUND_EVENT_DETAILS
4192 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4193 entry->deviceId, entry->source);
4194#endif
4195 return false;
4196 }
4197
4198 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4199 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4200 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4201 if (index >= 0) {
4202 mMotionMementos.removeAt(index);
4203 }
4204 addMotionMemento(entry, flags, true /*hovering*/);
4205 return true;
4206 }
4207
4208 default:
4209 return true;
4210 }
4211}
4212
4213ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4214 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4215 const KeyMemento& memento = mKeyMementos.itemAt(i);
4216 if (memento.deviceId == entry->deviceId
4217 && memento.source == entry->source
4218 && memento.keyCode == entry->keyCode
4219 && memento.scanCode == entry->scanCode) {
4220 return i;
4221 }
4222 }
4223 return -1;
4224}
4225
4226ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4227 bool hovering) const {
4228 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4229 const MotionMemento& memento = mMotionMementos.itemAt(i);
4230 if (memento.deviceId == entry->deviceId
4231 && memento.source == entry->source
4232 && memento.displayId == entry->displayId
4233 && memento.hovering == hovering) {
4234 return i;
4235 }
4236 }
4237 return -1;
4238}
4239
4240void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4241 mKeyMementos.push();
4242 KeyMemento& memento = mKeyMementos.editTop();
4243 memento.deviceId = entry->deviceId;
4244 memento.source = entry->source;
4245 memento.keyCode = entry->keyCode;
4246 memento.scanCode = entry->scanCode;
4247 memento.metaState = entry->metaState;
4248 memento.flags = flags;
4249 memento.downTime = entry->downTime;
4250 memento.policyFlags = entry->policyFlags;
4251}
4252
4253void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4254 int32_t flags, bool hovering) {
4255 mMotionMementos.push();
4256 MotionMemento& memento = mMotionMementos.editTop();
4257 memento.deviceId = entry->deviceId;
4258 memento.source = entry->source;
4259 memento.flags = flags;
4260 memento.xPrecision = entry->xPrecision;
4261 memento.yPrecision = entry->yPrecision;
4262 memento.downTime = entry->downTime;
4263 memento.displayId = entry->displayId;
4264 memento.setPointers(entry);
4265 memento.hovering = hovering;
4266 memento.policyFlags = entry->policyFlags;
4267}
4268
4269void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4270 pointerCount = entry->pointerCount;
4271 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4272 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4273 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4274 }
4275}
4276
4277void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4278 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4279 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4280 const KeyMemento& memento = mKeyMementos.itemAt(i);
4281 if (shouldCancelKey(memento, options)) {
4282 outEvents.push(new KeyEntry(currentTime,
4283 memento.deviceId, memento.source, memento.policyFlags,
4284 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4285 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4286 }
4287 }
4288
4289 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4290 const MotionMemento& memento = mMotionMementos.itemAt(i);
4291 if (shouldCancelMotion(memento, options)) {
4292 outEvents.push(new MotionEntry(currentTime,
4293 memento.deviceId, memento.source, memento.policyFlags,
4294 memento.hovering
4295 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4296 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004297 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 memento.xPrecision, memento.yPrecision, memento.downTime,
4299 memento.displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004300 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4301 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 }
4303 }
4304}
4305
4306void InputDispatcher::InputState::clear() {
4307 mKeyMementos.clear();
4308 mMotionMementos.clear();
4309 mFallbackKeys.clear();
4310}
4311
4312void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4313 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4314 const MotionMemento& memento = mMotionMementos.itemAt(i);
4315 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4316 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4317 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4318 if (memento.deviceId == otherMemento.deviceId
4319 && memento.source == otherMemento.source
4320 && memento.displayId == otherMemento.displayId) {
4321 other.mMotionMementos.removeAt(j);
4322 } else {
4323 j += 1;
4324 }
4325 }
4326 other.mMotionMementos.push(memento);
4327 }
4328 }
4329}
4330
4331int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4332 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4333 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4334}
4335
4336void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4337 int32_t fallbackKeyCode) {
4338 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4339 if (index >= 0) {
4340 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4341 } else {
4342 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4343 }
4344}
4345
4346void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4347 mFallbackKeys.removeItem(originalKeyCode);
4348}
4349
4350bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4351 const CancelationOptions& options) {
4352 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4353 return false;
4354 }
4355
4356 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4357 return false;
4358 }
4359
4360 switch (options.mode) {
4361 case CancelationOptions::CANCEL_ALL_EVENTS:
4362 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4363 return true;
4364 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4365 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4366 default:
4367 return false;
4368 }
4369}
4370
4371bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4372 const CancelationOptions& options) {
4373 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4374 return false;
4375 }
4376
4377 switch (options.mode) {
4378 case CancelationOptions::CANCEL_ALL_EVENTS:
4379 return true;
4380 case CancelationOptions::CANCEL_POINTER_EVENTS:
4381 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4382 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4383 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4384 default:
4385 return false;
4386 }
4387}
4388
4389
4390// --- InputDispatcher::Connection ---
4391
4392InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4393 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4394 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4395 monitor(monitor),
4396 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4397}
4398
4399InputDispatcher::Connection::~Connection() {
4400}
4401
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004402const std::string InputDispatcher::Connection::getWindowName() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 if (inputWindowHandle != NULL) {
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004404 return inputWindowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 }
4406 if (monitor) {
4407 return "monitor";
4408 }
4409 return "?";
4410}
4411
4412const char* InputDispatcher::Connection::getStatusLabel() const {
4413 switch (status) {
4414 case STATUS_NORMAL:
4415 return "NORMAL";
4416
4417 case STATUS_BROKEN:
4418 return "BROKEN";
4419
4420 case STATUS_ZOMBIE:
4421 return "ZOMBIE";
4422
4423 default:
4424 return "UNKNOWN";
4425 }
4426}
4427
4428InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4429 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4430 if (entry->seq == seq) {
4431 return entry;
4432 }
4433 }
4434 return NULL;
4435}
4436
4437
4438// --- InputDispatcher::CommandEntry ---
4439
4440InputDispatcher::CommandEntry::CommandEntry(Command command) :
4441 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4442 seq(0), handled(false) {
4443}
4444
4445InputDispatcher::CommandEntry::~CommandEntry() {
4446}
4447
4448
4449// --- InputDispatcher::TouchState ---
4450
4451InputDispatcher::TouchState::TouchState() :
4452 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
4453}
4454
4455InputDispatcher::TouchState::~TouchState() {
4456}
4457
4458void InputDispatcher::TouchState::reset() {
4459 down = false;
4460 split = false;
4461 deviceId = -1;
4462 source = 0;
4463 displayId = -1;
4464 windows.clear();
4465}
4466
4467void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4468 down = other.down;
4469 split = other.split;
4470 deviceId = other.deviceId;
4471 source = other.source;
4472 displayId = other.displayId;
4473 windows = other.windows;
4474}
4475
4476void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4477 int32_t targetFlags, BitSet32 pointerIds) {
4478 if (targetFlags & InputTarget::FLAG_SPLIT) {
4479 split = true;
4480 }
4481
4482 for (size_t i = 0; i < windows.size(); i++) {
4483 TouchedWindow& touchedWindow = windows.editItemAt(i);
4484 if (touchedWindow.windowHandle == windowHandle) {
4485 touchedWindow.targetFlags |= targetFlags;
4486 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4487 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4488 }
4489 touchedWindow.pointerIds.value |= pointerIds.value;
4490 return;
4491 }
4492 }
4493
4494 windows.push();
4495
4496 TouchedWindow& touchedWindow = windows.editTop();
4497 touchedWindow.windowHandle = windowHandle;
4498 touchedWindow.targetFlags = targetFlags;
4499 touchedWindow.pointerIds = pointerIds;
4500}
4501
4502void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4503 for (size_t i = 0; i < windows.size(); i++) {
4504 if (windows.itemAt(i).windowHandle == windowHandle) {
4505 windows.removeAt(i);
4506 return;
4507 }
4508 }
4509}
4510
4511void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4512 for (size_t i = 0 ; i < windows.size(); ) {
4513 TouchedWindow& window = windows.editItemAt(i);
4514 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4515 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4516 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4517 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4518 i += 1;
4519 } else {
4520 windows.removeAt(i);
4521 }
4522 }
4523}
4524
4525sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4526 for (size_t i = 0; i < windows.size(); i++) {
4527 const TouchedWindow& window = windows.itemAt(i);
4528 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4529 return window.windowHandle;
4530 }
4531 }
4532 return NULL;
4533}
4534
4535bool InputDispatcher::TouchState::isSlippery() const {
4536 // Must have exactly one foreground window.
4537 bool haveSlipperyForegroundWindow = false;
4538 for (size_t i = 0; i < windows.size(); i++) {
4539 const TouchedWindow& window = windows.itemAt(i);
4540 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4541 if (haveSlipperyForegroundWindow
4542 || !(window.windowHandle->getInfo()->layoutParamsFlags
4543 & InputWindowInfo::FLAG_SLIPPERY)) {
4544 return false;
4545 }
4546 haveSlipperyForegroundWindow = true;
4547 }
4548 }
4549 return haveSlipperyForegroundWindow;
4550}
4551
4552
4553// --- InputDispatcherThread ---
4554
4555InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4556 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4557}
4558
4559InputDispatcherThread::~InputDispatcherThread() {
4560}
4561
4562bool InputDispatcherThread::threadLoop() {
4563 mDispatcher->dispatchOnce();
4564 return true;
4565}
4566
4567} // namespace android