2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define LOG_TAG "InputDispatcher"
18 #define ATRACE_TAG ATRACE_TAG_INPUT
20 //#define LOG_NDEBUG 0
22 // Log detailed debug messages about each inbound event notification to the dispatcher.
23 #define DEBUG_INBOUND_EVENT_DETAILS 0
25 // Log detailed debug messages about each outbound event processed by the dispatcher.
26 #define DEBUG_OUTBOUND_EVENT_DETAILS 0
28 // Log debug messages about the dispatch cycle.
29 #define DEBUG_DISPATCH_CYCLE 0
31 // Log debug messages about registrations.
32 #define DEBUG_REGISTRATION 0
34 // Log debug messages about input event injection.
35 #define DEBUG_INJECTION 0
37 // Log debug messages about input focus tracking.
40 // Log debug messages about the app switch latency optimization.
41 #define DEBUG_APP_SWITCH 0
43 // Log debug messages about hover events.
46 #include "InputDispatcher.h"
48 #include <utils/Trace.h>
49 #include <cutils/log.h>
50 #include <androidfw/PowerManager.h>
65 // Default input dispatching timeout if there is no focused application or paused window
66 // from which to determine an appropriate dispatching timeout.
67 const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
69 // Amount of time to allow for all pending events to be processed when an app switch
70 // key is on the way. This is used to preempt input dispatch and drop input events
71 // when an application takes too long to respond and the user has pressed an app switch key.
72 const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
74 // Amount of time to allow for an event to be dispatched (measured since its eventTime)
75 // before considering it stale and dropping it.
76 const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
78 // Amount of time to allow touch events to be streamed out to a connection before requiring
79 // that the first event be finished. This value extends the ANR timeout by the specified
80 // amount. For example, if streaming is allowed to get ahead by one second relative to the
81 // queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
82 const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
84 // Log a warning when an event takes longer than this to process, even if an ANR does not occur.
85 const nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
87 // Number of recent events to keep for debugging purposes.
88 const size_t RECENT_QUEUE_MAX_SIZE = 10;
90 static inline nsecs_t now() {
91 return systemTime(SYSTEM_TIME_MONOTONIC);
94 static inline const char* toString(bool value) {
95 return value ? "true" : "false";
98 static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
99 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
100 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
103 static bool isValidKeyAction(int32_t action) {
105 case AKEY_EVENT_ACTION_DOWN:
106 case AKEY_EVENT_ACTION_UP:
113 static bool validateKeyEvent(int32_t action) {
114 if (! isValidKeyAction(action)) {
115 ALOGE("Key event has invalid action code 0x%x", action);
121 static bool isValidMotionAction(int32_t action, size_t pointerCount) {
122 switch (action & AMOTION_EVENT_ACTION_MASK) {
123 case AMOTION_EVENT_ACTION_DOWN:
124 case AMOTION_EVENT_ACTION_UP:
125 case AMOTION_EVENT_ACTION_CANCEL:
126 case AMOTION_EVENT_ACTION_MOVE:
127 case AMOTION_EVENT_ACTION_OUTSIDE:
128 case AMOTION_EVENT_ACTION_HOVER_ENTER:
129 case AMOTION_EVENT_ACTION_HOVER_MOVE:
130 case AMOTION_EVENT_ACTION_HOVER_EXIT:
131 case AMOTION_EVENT_ACTION_SCROLL:
133 case AMOTION_EVENT_ACTION_POINTER_DOWN:
134 case AMOTION_EVENT_ACTION_POINTER_UP: {
135 int32_t index = getMotionEventActionPointerIndex(action);
136 return index >= 0 && size_t(index) < pointerCount;
143 static bool validateMotionEvent(int32_t action, size_t pointerCount,
144 const PointerProperties* pointerProperties) {
145 if (! isValidMotionAction(action, pointerCount)) {
146 ALOGE("Motion event has invalid action code 0x%x", action);
149 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
150 ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
151 pointerCount, MAX_POINTERS);
154 BitSet32 pointerIdBits;
155 for (size_t i = 0; i < pointerCount; i++) {
156 int32_t id = pointerProperties[i].id;
157 if (id < 0 || id > MAX_POINTER_ID) {
158 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
162 if (pointerIdBits.hasBit(id)) {
163 ALOGE("Motion event has duplicate pointer id %d", id);
166 pointerIdBits.markBit(id);
171 static bool isMainDisplay(int32_t displayId) {
172 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
175 static void dumpRegion(String8& dump, const SkRegion& region) {
176 if (region.isEmpty()) {
177 dump.append("<empty>");
182 for (SkRegion::Iterator it(region); !it.done(); it.next()) {
188 const SkIRect& rect = it.rect();
189 dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
194 // --- InputDispatcher ---
196 InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
198 mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
199 mNextUnblockedEvent(NULL),
200 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
201 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
202 mLooper = new Looper(false);
204 mKeyRepeatState.lastKeyEntry = NULL;
206 policy->getDispatcherConfiguration(&mConfig);
209 InputDispatcher::~InputDispatcher() {
213 resetKeyRepeatLocked();
214 releasePendingEventLocked();
215 drainInboundQueueLocked();
218 while (mConnectionsByFd.size() != 0) {
219 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
223 void InputDispatcher::dispatchOnce() {
224 nsecs_t nextWakeupTime = LONG_LONG_MAX;
227 mDispatcherIsAliveCondition.broadcast();
229 // Run a dispatch loop if there are no pending commands.
230 // The dispatch loop might enqueue commands to run afterwards.
231 if (!haveCommandsLocked()) {
232 dispatchOnceInnerLocked(&nextWakeupTime);
235 // Run all pending commands if there are any.
236 // If any commands were run then force the next poll to wake up immediately.
237 if (runCommandsLockedInterruptible()) {
238 nextWakeupTime = LONG_LONG_MIN;
242 // Wait for callback or timeout or wake. (make sure we round up, not down)
243 nsecs_t currentTime = now();
244 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
245 mLooper->pollOnce(timeoutMillis);
248 void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
249 nsecs_t currentTime = now();
251 // Reset the key repeat timer whenever normal dispatch is suspended while the
252 // device is in a non-interactive state. This is to ensure that we abort a key
253 // repeat if the device is just coming out of sleep.
254 if (!mDispatchEnabled) {
255 resetKeyRepeatLocked();
258 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
259 if (mDispatchFrozen) {
261 ALOGD("Dispatch frozen. Waiting some more.");
266 // Optimize latency of app switches.
267 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
268 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
269 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
270 if (mAppSwitchDueTime < *nextWakeupTime) {
271 *nextWakeupTime = mAppSwitchDueTime;
274 // Ready to start a new event.
275 // If we don't already have a pending event, go grab one.
276 if (! mPendingEvent) {
277 if (mInboundQueue.isEmpty()) {
278 if (isAppSwitchDue) {
279 // The inbound queue is empty so the app switch key we were waiting
280 // for will never arrive. Stop waiting for it.
281 resetPendingAppSwitchLocked(false);
282 isAppSwitchDue = false;
285 // Synthesize a key repeat if appropriate.
286 if (mKeyRepeatState.lastKeyEntry) {
287 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
288 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
290 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
291 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
296 // Nothing to do if there is no pending event.
297 if (!mPendingEvent) {
301 // Inbound queue has at least one entry.
302 mPendingEvent = mInboundQueue.dequeueAtHead();
303 traceInboundQueueLengthLocked();
306 // Poke user activity for this event.
307 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
308 pokeUserActivityLocked(mPendingEvent);
311 // Get ready to dispatch the event.
312 resetANRTimeoutsLocked();
315 // Now we have an event to dispatch.
316 // All events are eventually dequeued and processed this way, even if we intend to drop them.
317 ALOG_ASSERT(mPendingEvent != NULL);
319 DropReason dropReason = DROP_REASON_NOT_DROPPED;
320 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
321 dropReason = DROP_REASON_POLICY;
322 } else if (!mDispatchEnabled) {
323 dropReason = DROP_REASON_DISABLED;
326 if (mNextUnblockedEvent == mPendingEvent) {
327 mNextUnblockedEvent = NULL;
330 switch (mPendingEvent->type) {
331 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
332 ConfigurationChangedEntry* typedEntry =
333 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
334 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
335 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
339 case EventEntry::TYPE_DEVICE_RESET: {
340 DeviceResetEntry* typedEntry =
341 static_cast<DeviceResetEntry*>(mPendingEvent);
342 done = dispatchDeviceResetLocked(currentTime, typedEntry);
343 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
347 case EventEntry::TYPE_KEY: {
348 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
349 if (isAppSwitchDue) {
350 if (isAppSwitchKeyEventLocked(typedEntry)) {
351 resetPendingAppSwitchLocked(true);
352 isAppSwitchDue = false;
353 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
354 dropReason = DROP_REASON_APP_SWITCH;
357 if (dropReason == DROP_REASON_NOT_DROPPED
358 && isStaleEventLocked(currentTime, typedEntry)) {
359 dropReason = DROP_REASON_STALE;
361 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
362 dropReason = DROP_REASON_BLOCKED;
364 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
368 case EventEntry::TYPE_MOTION: {
369 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
370 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
371 dropReason = DROP_REASON_APP_SWITCH;
373 if (dropReason == DROP_REASON_NOT_DROPPED
374 && isStaleEventLocked(currentTime, typedEntry)) {
375 dropReason = DROP_REASON_STALE;
377 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
378 dropReason = DROP_REASON_BLOCKED;
380 done = dispatchMotionLocked(currentTime, typedEntry,
381 &dropReason, nextWakeupTime);
391 if (dropReason != DROP_REASON_NOT_DROPPED) {
392 dropInboundEventLocked(mPendingEvent, dropReason);
395 releasePendingEventLocked();
396 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
400 bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
401 bool needWake = mInboundQueue.isEmpty();
402 mInboundQueue.enqueueAtTail(entry);
403 traceInboundQueueLengthLocked();
405 switch (entry->type) {
406 case EventEntry::TYPE_KEY: {
407 // Optimize app switch latency.
408 // If the application takes too long to catch up then we drop all events preceding
409 // the app switch key.
410 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
411 if (isAppSwitchKeyEventLocked(keyEntry)) {
412 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
413 mAppSwitchSawKeyDown = true;
414 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
415 if (mAppSwitchSawKeyDown) {
417 ALOGD("App switch is pending!");
419 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
420 mAppSwitchSawKeyDown = false;
428 case EventEntry::TYPE_MOTION: {
429 // Optimize case where the current application is unresponsive and the user
430 // decides to touch a window in a different application.
431 // If the application takes too long to catch up then we drop all events preceding
432 // the touch into the other window.
433 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
434 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
435 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
436 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
437 && mInputTargetWaitApplicationHandle != NULL) {
438 int32_t displayId = motionEntry->displayId;
439 int32_t x = int32_t(motionEntry->pointerCoords[0].
440 getAxisValue(AMOTION_EVENT_AXIS_X));
441 int32_t y = int32_t(motionEntry->pointerCoords[0].
442 getAxisValue(AMOTION_EVENT_AXIS_Y));
443 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
444 if (touchedWindowHandle != NULL
445 && touchedWindowHandle->inputApplicationHandle
446 != mInputTargetWaitApplicationHandle) {
447 // User touched a different application than the one we are waiting on.
448 // Flag the event, and start pruning the input queue.
449 mNextUnblockedEvent = motionEntry;
460 void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
461 entry->refCount += 1;
462 mRecentQueue.enqueueAtTail(entry);
463 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
464 mRecentQueue.dequeueAtHead()->release();
468 sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
469 int32_t x, int32_t y) {
470 // Traverse windows from front to back to find touched window.
471 size_t numWindows = mWindowHandles.size();
472 for (size_t i = 0; i < numWindows; i++) {
473 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
474 const InputWindowInfo* windowInfo = windowHandle->getInfo();
475 if (windowInfo->displayId == displayId) {
476 int32_t flags = windowInfo->layoutParamsFlags;
477 int32_t privateFlags = windowInfo->layoutParamsPrivateFlags;
479 if (windowInfo->visible) {
480 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
481 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
482 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
483 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
490 if (privateFlags & InputWindowInfo::PRIVATE_FLAG_SYSTEM_ERROR) {
491 // Error window is on top but not visible, so touch is dropped.
499 void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
501 switch (dropReason) {
502 case DROP_REASON_POLICY:
503 #if DEBUG_INBOUND_EVENT_DETAILS
504 ALOGD("Dropped event because policy consumed it.");
506 reason = "inbound event was dropped because the policy consumed it";
508 case DROP_REASON_DISABLED:
509 ALOGI("Dropped event because input dispatch is disabled.");
510 reason = "inbound event was dropped because input dispatch is disabled";
512 case DROP_REASON_APP_SWITCH:
513 ALOGI("Dropped event because of pending overdue app switch.");
514 reason = "inbound event was dropped because of pending overdue app switch";
516 case DROP_REASON_BLOCKED:
517 ALOGI("Dropped event because the current application is not responding and the user "
518 "has started interacting with a different application.");
519 reason = "inbound event was dropped because the current application is not responding "
520 "and the user has started interacting with a different application";
522 case DROP_REASON_STALE:
523 ALOGI("Dropped event because it is stale.");
524 reason = "inbound event was dropped because it is stale";
531 switch (entry->type) {
532 case EventEntry::TYPE_KEY: {
533 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
534 synthesizeCancelationEventsForAllConnectionsLocked(options);
537 case EventEntry::TYPE_MOTION: {
538 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
539 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
540 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
541 synthesizeCancelationEventsForAllConnectionsLocked(options);
543 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
544 synthesizeCancelationEventsForAllConnectionsLocked(options);
551 bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
552 return keyCode == AKEYCODE_HOME
553 || keyCode == AKEYCODE_ENDCALL
554 || keyCode == AKEYCODE_APP_SWITCH;
557 bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
558 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
559 && isAppSwitchKeyCode(keyEntry->keyCode)
560 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
561 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
564 bool InputDispatcher::isAppSwitchPendingLocked() {
565 return mAppSwitchDueTime != LONG_LONG_MAX;
568 void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
569 mAppSwitchDueTime = LONG_LONG_MAX;
573 ALOGD("App switch has arrived.");
575 ALOGD("App switch was abandoned.");
580 bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
581 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
584 bool InputDispatcher::haveCommandsLocked() const {
585 return !mCommandQueue.isEmpty();
588 bool InputDispatcher::runCommandsLockedInterruptible() {
589 if (mCommandQueue.isEmpty()) {
594 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
596 Command command = commandEntry->command;
597 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
599 commandEntry->connection.clear();
601 } while (! mCommandQueue.isEmpty());
605 InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
606 CommandEntry* commandEntry = new CommandEntry(command);
607 mCommandQueue.enqueueAtTail(commandEntry);
611 void InputDispatcher::drainInboundQueueLocked() {
612 while (! mInboundQueue.isEmpty()) {
613 EventEntry* entry = mInboundQueue.dequeueAtHead();
614 releaseInboundEventLocked(entry);
616 traceInboundQueueLengthLocked();
619 void InputDispatcher::releasePendingEventLocked() {
621 resetANRTimeoutsLocked();
622 releaseInboundEventLocked(mPendingEvent);
623 mPendingEvent = NULL;
627 void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
628 InjectionState* injectionState = entry->injectionState;
629 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
630 #if DEBUG_DISPATCH_CYCLE
631 ALOGD("Injected inbound event was dropped.");
633 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
635 if (entry == mNextUnblockedEvent) {
636 mNextUnblockedEvent = NULL;
638 addRecentEventLocked(entry);
642 void InputDispatcher::resetKeyRepeatLocked() {
643 if (mKeyRepeatState.lastKeyEntry) {
644 mKeyRepeatState.lastKeyEntry->release();
645 mKeyRepeatState.lastKeyEntry = NULL;
649 InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
650 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
652 // Reuse the repeated key entry if it is otherwise unreferenced.
653 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
654 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
655 if (entry->refCount == 1) {
657 entry->eventTime = currentTime;
658 entry->policyFlags = policyFlags;
659 entry->repeatCount += 1;
661 KeyEntry* newEntry = new KeyEntry(currentTime,
662 entry->deviceId, entry->source, policyFlags,
663 entry->action, entry->flags, entry->keyCode, entry->scanCode,
664 entry->metaState, entry->repeatCount + 1, entry->downTime);
666 mKeyRepeatState.lastKeyEntry = newEntry;
671 entry->syntheticRepeat = true;
673 // Increment reference count since we keep a reference to the event in
674 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
675 entry->refCount += 1;
677 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
681 bool InputDispatcher::dispatchConfigurationChangedLocked(
682 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
683 #if DEBUG_OUTBOUND_EVENT_DETAILS
684 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
687 // Reset key repeating in case a keyboard device was added or removed or something.
688 resetKeyRepeatLocked();
690 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
691 CommandEntry* commandEntry = postCommandLocked(
692 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
693 commandEntry->eventTime = entry->eventTime;
697 bool InputDispatcher::dispatchDeviceResetLocked(
698 nsecs_t currentTime, DeviceResetEntry* entry) {
699 #if DEBUG_OUTBOUND_EVENT_DETAILS
700 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
703 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
705 options.deviceId = entry->deviceId;
706 synthesizeCancelationEventsForAllConnectionsLocked(options);
710 bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
711 DropReason* dropReason, nsecs_t* nextWakeupTime) {
713 if (! entry->dispatchInProgress) {
714 if (entry->repeatCount == 0
715 && entry->action == AKEY_EVENT_ACTION_DOWN
716 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
717 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
718 if (mKeyRepeatState.lastKeyEntry
719 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
720 // We have seen two identical key downs in a row which indicates that the device
721 // driver is automatically generating key repeats itself. We take note of the
722 // repeat here, but we disable our own next key repeat timer since it is clear that
723 // we will not need to synthesize key repeats ourselves.
724 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
725 resetKeyRepeatLocked();
726 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
728 // Not a repeat. Save key down state in case we do see a repeat later.
729 resetKeyRepeatLocked();
730 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
732 mKeyRepeatState.lastKeyEntry = entry;
733 entry->refCount += 1;
734 } else if (! entry->syntheticRepeat) {
735 resetKeyRepeatLocked();
738 if (entry->repeatCount == 1) {
739 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
741 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
744 entry->dispatchInProgress = true;
746 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
749 // Handle case where the policy asked us to try again later last time.
750 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
751 if (currentTime < entry->interceptKeyWakeupTime) {
752 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
753 *nextWakeupTime = entry->interceptKeyWakeupTime;
755 return false; // wait until next wakeup
757 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
758 entry->interceptKeyWakeupTime = 0;
761 // Give the policy a chance to intercept the key.
762 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
763 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
764 CommandEntry* commandEntry = postCommandLocked(
765 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
766 if (mFocusedWindowHandle != NULL) {
767 commandEntry->inputWindowHandle = mFocusedWindowHandle;
769 commandEntry->keyEntry = entry;
770 entry->refCount += 1;
771 return false; // wait for the command to run
773 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
775 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
776 if (*dropReason == DROP_REASON_NOT_DROPPED) {
777 *dropReason = DROP_REASON_POLICY;
781 // Clean up if dropping the event.
782 if (*dropReason != DROP_REASON_NOT_DROPPED) {
783 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
784 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
789 Vector<InputTarget> inputTargets;
790 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
791 entry, inputTargets, nextWakeupTime);
792 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
796 setInjectionResultLocked(entry, injectionResult);
797 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
801 addMonitoringTargetsLocked(inputTargets);
804 dispatchEventLocked(currentTime, entry, inputTargets);
808 void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
809 #if DEBUG_OUTBOUND_EVENT_DETAILS
810 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
811 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
812 "repeatCount=%d, downTime=%lld",
814 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
815 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
816 entry->repeatCount, entry->downTime);
820 bool InputDispatcher::dispatchMotionLocked(
821 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
823 if (! entry->dispatchInProgress) {
824 entry->dispatchInProgress = true;
826 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
829 // Clean up if dropping the event.
830 if (*dropReason != DROP_REASON_NOT_DROPPED) {
831 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
832 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
836 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
839 Vector<InputTarget> inputTargets;
841 bool conflictingPointerActions = false;
842 int32_t injectionResult;
843 if (isPointerEvent) {
844 // Pointer event. (eg. touchscreen)
845 injectionResult = findTouchedWindowTargetsLocked(currentTime,
846 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
848 // Non touch event. (eg. trackball)
849 injectionResult = findFocusedWindowTargetsLocked(currentTime,
850 entry, inputTargets, nextWakeupTime);
852 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
856 setInjectionResultLocked(entry, injectionResult);
857 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
861 // TODO: support sending secondary display events to input monitors
862 if (isMainDisplay(entry->displayId)) {
863 addMonitoringTargetsLocked(inputTargets);
866 // Dispatch the motion.
867 if (conflictingPointerActions) {
868 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
869 "conflicting pointer actions");
870 synthesizeCancelationEventsForAllConnectionsLocked(options);
872 dispatchEventLocked(currentTime, entry, inputTargets);
877 void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
878 #if DEBUG_OUTBOUND_EVENT_DETAILS
879 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
880 "action=0x%x, flags=0x%x, "
881 "metaState=0x%x, buttonState=0x%x, "
882 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
884 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
885 entry->action, entry->flags,
886 entry->metaState, entry->buttonState,
887 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
890 for (uint32_t i = 0; i < entry->pointerCount; i++) {
891 ALOGD(" Pointer %d: id=%d, toolType=%d, "
892 "x=%f, y=%f, pressure=%f, size=%f, "
893 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
895 i, entry->pointerProperties[i].id,
896 entry->pointerProperties[i].toolType,
897 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
898 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
899 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
900 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
901 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
902 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
903 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
904 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
905 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
910 void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
911 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
912 #if DEBUG_DISPATCH_CYCLE
913 ALOGD("dispatchEventToCurrentInputTargets");
916 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
918 pokeUserActivityLocked(eventEntry);
920 for (size_t i = 0; i < inputTargets.size(); i++) {
921 const InputTarget& inputTarget = inputTargets.itemAt(i);
923 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
924 if (connectionIndex >= 0) {
925 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
926 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
929 ALOGD("Dropping event delivery to target with channel '%s' because it "
930 "is no longer registered with the input dispatcher.",
931 inputTarget.inputChannel->getName().string());
937 int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
938 const EventEntry* entry,
939 const sp<InputApplicationHandle>& applicationHandle,
940 const sp<InputWindowHandle>& windowHandle,
941 nsecs_t* nextWakeupTime, const char* reason) {
942 if (applicationHandle == NULL && windowHandle == NULL) {
943 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
945 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
947 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
948 mInputTargetWaitStartTime = currentTime;
949 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
950 mInputTargetWaitTimeoutExpired = false;
951 mInputTargetWaitApplicationHandle.clear();
954 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
956 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
957 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
961 if (windowHandle != NULL) {
962 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
963 } else if (applicationHandle != NULL) {
964 timeout = applicationHandle->getDispatchingTimeout(
965 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
967 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
970 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
971 mInputTargetWaitStartTime = currentTime;
972 mInputTargetWaitTimeoutTime = currentTime + timeout;
973 mInputTargetWaitTimeoutExpired = false;
974 mInputTargetWaitApplicationHandle.clear();
976 if (windowHandle != NULL) {
977 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
979 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
980 mInputTargetWaitApplicationHandle = applicationHandle;
985 if (mInputTargetWaitTimeoutExpired) {
986 return INPUT_EVENT_INJECTION_TIMED_OUT;
989 if (currentTime >= mInputTargetWaitTimeoutTime) {
990 onANRLocked(currentTime, applicationHandle, windowHandle,
991 entry->eventTime, mInputTargetWaitStartTime, reason);
993 // Force poll loop to wake up immediately on next iteration once we get the
994 // ANR response back from the policy.
995 *nextWakeupTime = LONG_LONG_MIN;
996 return INPUT_EVENT_INJECTION_PENDING;
998 // Force poll loop to wake up when timeout is due.
999 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1000 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1002 return INPUT_EVENT_INJECTION_PENDING;
1006 void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1007 const sp<InputChannel>& inputChannel) {
1008 if (newTimeout > 0) {
1009 // Extend the timeout.
1010 mInputTargetWaitTimeoutTime = now() + newTimeout;
1013 mInputTargetWaitTimeoutExpired = true;
1015 // Input state will not be realistic. Mark it out of sync.
1016 if (inputChannel.get()) {
1017 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1018 if (connectionIndex >= 0) {
1019 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1020 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1022 if (windowHandle != NULL) {
1023 const InputWindowInfo* info = windowHandle->getInfo();
1025 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId);
1026 if (stateIndex >= 0) {
1027 mTouchStatesByDisplay.editValueAt(stateIndex).removeWindow(
1033 if (connection->status == Connection::STATUS_NORMAL) {
1034 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1035 "application not responding");
1036 synthesizeCancelationEventsForConnectionLocked(connection, options);
1043 nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1044 nsecs_t currentTime) {
1045 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1046 return currentTime - mInputTargetWaitStartTime;
1051 void InputDispatcher::resetANRTimeoutsLocked() {
1053 ALOGD("Resetting ANR timeouts.");
1056 // Reset input target wait timeout.
1057 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1058 mInputTargetWaitApplicationHandle.clear();
1061 int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1062 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1063 int32_t injectionResult;
1065 // If there is no currently focused window and no focused application
1066 // then drop the event.
1067 if (mFocusedWindowHandle == NULL) {
1068 if (mFocusedApplicationHandle != NULL) {
1069 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1070 mFocusedApplicationHandle, NULL, nextWakeupTime,
1071 "Waiting because no window has focus but there is a "
1072 "focused application that may eventually add a window "
1073 "when it finishes starting up.");
1077 ALOGI("Dropping event because there is no focused window or focused application.");
1078 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1082 // Check permissions.
1083 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
1084 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1088 // If the currently focused window is paused then keep waiting.
1089 if (mFocusedWindowHandle->getInfo()->paused) {
1090 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1091 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1092 "Waiting because the focused window is paused.");
1096 // If the currently focused window is still working on previous events then keep waiting.
1097 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
1098 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1099 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1100 "Waiting because the focused window has not finished "
1101 "processing the input events that were previously delivered to it.");
1105 // Success! Output targets.
1106 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1107 addWindowTargetLocked(mFocusedWindowHandle,
1108 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1114 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1115 updateDispatchStatisticsLocked(currentTime, entry,
1116 injectionResult, timeSpentWaitingForApplication);
1118 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1119 "timeSpentWaitingForApplication=%0.1fms",
1120 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1122 return injectionResult;
1125 int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1126 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1127 bool* outConflictingPointerActions) {
1128 enum InjectionPermission {
1129 INJECTION_PERMISSION_UNKNOWN,
1130 INJECTION_PERMISSION_GRANTED,
1131 INJECTION_PERMISSION_DENIED
1134 nsecs_t startTime = now();
1136 // For security reasons, we defer updating the touch state until we are sure that
1137 // event injection will be allowed.
1138 int32_t displayId = entry->displayId;
1139 int32_t action = entry->action;
1140 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1142 // Update the touch state as needed based on the properties of the touch event.
1143 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1144 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1145 sp<InputWindowHandle> newHoverWindowHandle;
1147 // Copy current touch state into mTempTouchState.
1148 // This state is always reset at the end of this function, so if we don't find state
1149 // for the specified display then our initial state will be empty.
1150 const TouchState* oldState = NULL;
1151 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1152 if (oldStateIndex >= 0) {
1153 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1154 mTempTouchState.copyFrom(*oldState);
1157 bool isSplit = mTempTouchState.split;
1158 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1159 && (mTempTouchState.deviceId != entry->deviceId
1160 || mTempTouchState.source != entry->source
1161 || mTempTouchState.displayId != displayId);
1162 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1163 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1164 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1165 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1166 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1168 bool wrongDevice = false;
1170 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1171 if (switchedDevice && mTempTouchState.down && !down) {
1173 ALOGD("Dropping event because a pointer for a different device is already down.");
1175 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1176 switchedDevice = false;
1180 mTempTouchState.reset();
1181 mTempTouchState.down = down;
1182 mTempTouchState.deviceId = entry->deviceId;
1183 mTempTouchState.source = entry->source;
1184 mTempTouchState.displayId = displayId;
1188 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1189 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1191 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1192 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1193 getAxisValue(AMOTION_EVENT_AXIS_X));
1194 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1195 getAxisValue(AMOTION_EVENT_AXIS_Y));
1196 sp<InputWindowHandle> newTouchedWindowHandle;
1197 sp<InputWindowHandle> topErrorWindowHandle;
1198 bool isTouchModal = false;
1200 // Traverse windows from front to back to find touched window and outside targets.
1201 size_t numWindows = mWindowHandles.size();
1202 for (size_t i = 0; i < numWindows; i++) {
1203 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1204 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1205 if (windowInfo->displayId != displayId) {
1206 continue; // wrong display
1209 int32_t privateFlags = windowInfo->layoutParamsPrivateFlags;
1210 if (privateFlags & InputWindowInfo::PRIVATE_FLAG_SYSTEM_ERROR) {
1211 if (topErrorWindowHandle == NULL) {
1212 topErrorWindowHandle = windowHandle;
1216 int32_t flags = windowInfo->layoutParamsFlags;
1217 if (windowInfo->visible) {
1218 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1219 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1220 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1221 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1222 newTouchedWindowHandle = windowHandle;
1223 break; // found touched window, exit window loop
1227 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1228 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
1230 mTempTouchState.addOrUpdateWindow(
1231 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE,
1237 // If there is an error window but it is not taking focus (typically because
1238 // it is invisible) then wait for it. Any other focused window may in
1239 // fact be in ANR state.
1240 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
1241 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1242 NULL, NULL, nextWakeupTime,
1243 "Waiting because a system error window is about to be displayed.");
1244 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1248 // Figure out whether splitting will be allowed for this window.
1249 if (newTouchedWindowHandle != NULL
1250 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1251 // New window supports splitting.
1253 } else if (isSplit) {
1254 // New window does not support splitting but we have already split events.
1255 // Ignore the new window.
1256 newTouchedWindowHandle = NULL;
1259 // Handle the case where we did not find a window.
1260 if (newTouchedWindowHandle == NULL) {
1261 // Try to assign the pointer to the first foreground window we find, if there is one.
1262 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1263 if (newTouchedWindowHandle == NULL) {
1264 ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y);
1265 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1270 // Set target flags.
1271 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1273 targetFlags |= InputTarget::FLAG_SPLIT;
1275 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1276 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1279 // Update hover state.
1280 if (isHoverAction) {
1281 newHoverWindowHandle = newTouchedWindowHandle;
1282 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1283 newHoverWindowHandle = mLastHoverWindowHandle;
1286 // Update the temporary touch state.
1287 BitSet32 pointerIds;
1289 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1290 pointerIds.markBit(pointerId);
1292 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1294 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1296 // If the pointer is not currently down, then ignore the event.
1297 if (! mTempTouchState.down) {
1299 ALOGD("Dropping event because the pointer is not down or we previously "
1300 "dropped the pointer down event.");
1302 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1306 // Check whether touches should slip outside of the current foreground window.
1307 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1308 && entry->pointerCount == 1
1309 && mTempTouchState.isSlippery()) {
1310 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1311 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1313 sp<InputWindowHandle> oldTouchedWindowHandle =
1314 mTempTouchState.getFirstForegroundWindowHandle();
1315 sp<InputWindowHandle> newTouchedWindowHandle =
1316 findTouchedWindowAtLocked(displayId, x, y);
1317 if (oldTouchedWindowHandle != newTouchedWindowHandle
1318 && newTouchedWindowHandle != NULL) {
1320 ALOGD("Touch is slipping out of window %s into window %s.",
1321 oldTouchedWindowHandle->getName().string(),
1322 newTouchedWindowHandle->getName().string());
1324 // Make a slippery exit from the old window.
1325 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1326 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1328 // Make a slippery entrance into the new window.
1329 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1333 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1334 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1336 targetFlags |= InputTarget::FLAG_SPLIT;
1338 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1339 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1342 BitSet32 pointerIds;
1344 pointerIds.markBit(entry->pointerProperties[0].id);
1346 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1351 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1352 // Let the previous window know that the hover sequence is over.
1353 if (mLastHoverWindowHandle != NULL) {
1355 ALOGD("Sending hover exit event to window %s.",
1356 mLastHoverWindowHandle->getName().string());
1358 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1359 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1362 // Let the new window know that the hover sequence is starting.
1363 if (newHoverWindowHandle != NULL) {
1365 ALOGD("Sending hover enter event to window %s.",
1366 newHoverWindowHandle->getName().string());
1368 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1369 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1373 // Check permission to inject into all touched foreground windows and ensure there
1374 // is at least one touched foreground window.
1376 bool haveForegroundWindow = false;
1377 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1378 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1379 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1380 haveForegroundWindow = true;
1381 if (! checkInjectionPermission(touchedWindow.windowHandle,
1382 entry->injectionState)) {
1383 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1384 injectionPermission = INJECTION_PERMISSION_DENIED;
1389 if (! haveForegroundWindow) {
1391 ALOGD("Dropping event because there is no touched foreground window to receive it.");
1393 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1397 // Permission granted to injection into all touched foreground windows.
1398 injectionPermission = INJECTION_PERMISSION_GRANTED;
1401 // Check whether windows listening for outside touches are owned by the same UID. If it is
1402 // set the policy flag that we will not reveal coordinate information to this window.
1403 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1404 sp<InputWindowHandle> foregroundWindowHandle =
1405 mTempTouchState.getFirstForegroundWindowHandle();
1406 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1407 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1408 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1409 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1410 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1411 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1412 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1413 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1419 // Ensure all touched foreground windows are ready for new input.
1420 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1421 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1422 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1423 // If the touched window is paused then keep waiting.
1424 if (touchedWindow.windowHandle->getInfo()->paused) {
1425 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1426 NULL, touchedWindow.windowHandle, nextWakeupTime,
1427 "Waiting because the touched window is paused.");
1431 // If the touched window is still working on previous events then keep waiting.
1432 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
1433 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1434 NULL, touchedWindow.windowHandle, nextWakeupTime,
1435 "Waiting because the touched window has not finished "
1436 "processing the input events that were previously delivered to it.");
1442 // If this is the first pointer going down and the touched window has a wallpaper
1443 // then also add the touched wallpaper windows so they are locked in for the duration
1444 // of the touch gesture.
1445 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1446 // engine only supports touch events. We would need to add a mechanism similar
1447 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1448 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1449 sp<InputWindowHandle> foregroundWindowHandle =
1450 mTempTouchState.getFirstForegroundWindowHandle();
1451 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
1452 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1453 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1454 const InputWindowInfo* info = windowHandle->getInfo();
1455 if (info->displayId == displayId
1456 && windowHandle->getInfo()->layoutParamsType
1457 == InputWindowInfo::TYPE_WALLPAPER) {
1458 mTempTouchState.addOrUpdateWindow(windowHandle,
1459 InputTarget::FLAG_WINDOW_IS_OBSCURED
1460 | InputTarget::FLAG_DISPATCH_AS_IS,
1467 // Success! Output targets.
1468 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1470 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1471 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1472 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1473 touchedWindow.pointerIds, inputTargets);
1476 // Drop the outside or hover touch windows since we will not care about them
1477 // in the next iteration.
1478 mTempTouchState.filterNonAsIsTouchWindows();
1481 // Check injection permission once and for all.
1482 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
1483 if (checkInjectionPermission(NULL, entry->injectionState)) {
1484 injectionPermission = INJECTION_PERMISSION_GRANTED;
1486 injectionPermission = INJECTION_PERMISSION_DENIED;
1490 // Update final pieces of touch state if the injector had permission.
1491 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1493 if (switchedDevice) {
1495 ALOGD("Conflicting pointer actions: Switched to a different device.");
1497 *outConflictingPointerActions = true;
1500 if (isHoverAction) {
1501 // Started hovering, therefore no longer down.
1502 if (oldState && oldState->down) {
1504 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1506 *outConflictingPointerActions = true;
1508 mTempTouchState.reset();
1509 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1510 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1511 mTempTouchState.deviceId = entry->deviceId;
1512 mTempTouchState.source = entry->source;
1513 mTempTouchState.displayId = displayId;
1515 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1516 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1517 // All pointers up or canceled.
1518 mTempTouchState.reset();
1519 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1520 // First pointer went down.
1521 if (oldState && oldState->down) {
1523 ALOGD("Conflicting pointer actions: Down received while already down.");
1525 *outConflictingPointerActions = true;
1527 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1528 // One pointer went up.
1530 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1531 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1533 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1534 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1535 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1536 touchedWindow.pointerIds.clearBit(pointerId);
1537 if (touchedWindow.pointerIds.isEmpty()) {
1538 mTempTouchState.windows.removeAt(i);
1547 // Save changes unless the action was scroll in which case the temporary touch
1548 // state was only valid for this one action.
1549 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1550 if (mTempTouchState.displayId >= 0) {
1551 if (oldStateIndex >= 0) {
1552 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1554 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1556 } else if (oldStateIndex >= 0) {
1557 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1561 // Update hover state.
1562 mLastHoverWindowHandle = newHoverWindowHandle;
1566 ALOGD("Not updating touch focus because injection was denied.");
1571 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1572 mTempTouchState.reset();
1574 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1575 updateDispatchStatisticsLocked(currentTime, entry,
1576 injectionResult, timeSpentWaitingForApplication);
1578 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1579 "timeSpentWaitingForApplication=%0.1fms",
1580 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1582 return injectionResult;
1585 void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1586 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1587 inputTargets.push();
1589 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1590 InputTarget& target = inputTargets.editTop();
1591 target.inputChannel = windowInfo->inputChannel;
1592 target.flags = targetFlags;
1593 target.xOffset = - windowInfo->frameLeft;
1594 target.yOffset = - windowInfo->frameTop;
1595 target.scaleFactor = windowInfo->scaleFactor;
1596 target.pointerIds = pointerIds;
1599 void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
1600 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1601 inputTargets.push();
1603 InputTarget& target = inputTargets.editTop();
1604 target.inputChannel = mMonitoringChannels[i];
1605 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1608 target.pointerIds.clear();
1609 target.scaleFactor = 1.0f;
1613 bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1614 const InjectionState* injectionState) {
1616 && (windowHandle == NULL
1617 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1618 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1619 if (windowHandle != NULL) {
1620 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1622 injectionState->injectorPid, injectionState->injectorUid,
1623 windowHandle->getName().string(),
1624 windowHandle->getInfo()->ownerUid);
1626 ALOGW("Permission denied: injecting event from pid %d uid %d",
1627 injectionState->injectorPid, injectionState->injectorUid);
1634 bool InputDispatcher::isWindowObscuredAtPointLocked(
1635 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1636 int32_t displayId = windowHandle->getInfo()->displayId;
1637 size_t numWindows = mWindowHandles.size();
1638 for (size_t i = 0; i < numWindows; i++) {
1639 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1640 if (otherHandle == windowHandle) {
1644 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1645 if (otherInfo->displayId == displayId
1646 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1647 && otherInfo->frameContainsPoint(x, y)) {
1654 bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
1655 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
1656 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
1657 if (connectionIndex >= 0) {
1658 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1659 if (connection->inputPublisherBlocked) {
1662 if (eventEntry->type == EventEntry::TYPE_KEY) {
1663 // If the event is a key event, then we must wait for all previous events to
1664 // complete before delivering it because previous events may have the
1665 // side-effect of transferring focus to a different window and we want to
1666 // ensure that the following keys are sent to the new window.
1668 // Suppose the user touches a button in a window then immediately presses "A".
1669 // If the button causes a pop-up window to appear then we want to ensure that
1670 // the "A" key is delivered to the new pop-up window. This is because users
1671 // often anticipate pending UI changes when typing on a keyboard.
1672 // To obtain this behavior, we must serialize key events with respect to all
1673 // prior input events.
1674 return connection->outboundQueue.isEmpty()
1675 && connection->waitQueue.isEmpty();
1677 // Touch events can always be sent to a window immediately because the user intended
1678 // to touch whatever was visible at the time. Even if focus changes or a new
1679 // window appears moments later, the touch event was meant to be delivered to
1680 // whatever window happened to be on screen at the time.
1682 // Generic motion events, such as trackball or joystick events are a little trickier.
1683 // Like key events, generic motion events are delivered to the focused window.
1684 // Unlike key events, generic motion events don't tend to transfer focus to other
1685 // windows and it is not important for them to be serialized. So we prefer to deliver
1686 // generic motion events as soon as possible to improve efficiency and reduce lag
1687 // through batching.
1689 // The one case where we pause input event delivery is when the wait queue is piling
1690 // up with lots of events because the application is not responding.
1691 // This condition ensures that ANRs are detected reliably.
1692 if (!connection->waitQueue.isEmpty()
1693 && currentTime >= connection->waitQueue.head->deliveryTime
1694 + STREAM_AHEAD_EVENT_TIMEOUT) {
1701 String8 InputDispatcher::getApplicationWindowLabelLocked(
1702 const sp<InputApplicationHandle>& applicationHandle,
1703 const sp<InputWindowHandle>& windowHandle) {
1704 if (applicationHandle != NULL) {
1705 if (windowHandle != NULL) {
1706 String8 label(applicationHandle->getName());
1707 label.append(" - ");
1708 label.append(windowHandle->getName());
1711 return applicationHandle->getName();
1713 } else if (windowHandle != NULL) {
1714 return windowHandle->getName();
1716 return String8("<unknown application or window>");
1720 void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
1721 if (mFocusedWindowHandle != NULL) {
1722 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1723 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1724 #if DEBUG_DISPATCH_CYCLE
1725 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.string());
1731 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1732 switch (eventEntry->type) {
1733 case EventEntry::TYPE_MOTION: {
1734 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1735 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1739 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1740 eventType = USER_ACTIVITY_EVENT_TOUCH;
1744 case EventEntry::TYPE_KEY: {
1745 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1746 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1749 eventType = USER_ACTIVITY_EVENT_BUTTON;
1754 CommandEntry* commandEntry = postCommandLocked(
1755 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1756 commandEntry->eventTime = eventEntry->eventTime;
1757 commandEntry->userActivityEventType = eventType;
1760 void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1761 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1762 #if DEBUG_DISPATCH_CYCLE
1763 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1764 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1766 connection->getInputChannelName(), inputTarget->flags,
1767 inputTarget->xOffset, inputTarget->yOffset,
1768 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1771 // Skip this event if the connection status is not normal.
1772 // We don't want to enqueue additional outbound events if the connection is broken.
1773 if (connection->status != Connection::STATUS_NORMAL) {
1774 #if DEBUG_DISPATCH_CYCLE
1775 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
1776 connection->getInputChannelName(), connection->getStatusLabel());
1781 // Split a motion event if needed.
1782 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1783 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1785 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1786 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1787 MotionEntry* splitMotionEntry = splitMotionEvent(
1788 originalMotionEntry, inputTarget->pointerIds);
1789 if (!splitMotionEntry) {
1790 return; // split event was dropped
1793 ALOGD("channel '%s' ~ Split motion event.",
1794 connection->getInputChannelName());
1795 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1797 enqueueDispatchEntriesLocked(currentTime, connection,
1798 splitMotionEntry, inputTarget);
1799 splitMotionEntry->release();
1804 // Not splitting. Enqueue dispatch entries for the event as is.
1805 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1808 void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1809 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1810 bool wasEmpty = connection->outboundQueue.isEmpty();
1812 // Enqueue dispatch entries for the requested modes.
1813 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1814 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1815 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1816 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1817 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1818 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1819 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1820 InputTarget::FLAG_DISPATCH_AS_IS);
1821 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1822 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1823 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1824 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1826 // If the outbound queue was previously empty, start the dispatch cycle going.
1827 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1828 startDispatchCycleLocked(currentTime, connection);
1832 void InputDispatcher::enqueueDispatchEntryLocked(
1833 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1834 int32_t dispatchMode) {
1835 int32_t inputTargetFlags = inputTarget->flags;
1836 if (!(inputTargetFlags & dispatchMode)) {
1839 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1841 // This is a new event.
1842 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1843 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1844 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1845 inputTarget->scaleFactor);
1847 // Apply target flags and update the connection's input state.
1848 switch (eventEntry->type) {
1849 case EventEntry::TYPE_KEY: {
1850 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1851 dispatchEntry->resolvedAction = keyEntry->action;
1852 dispatchEntry->resolvedFlags = keyEntry->flags;
1854 if (!connection->inputState.trackKey(keyEntry,
1855 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1856 #if DEBUG_DISPATCH_CYCLE
1857 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
1858 connection->getInputChannelName());
1860 delete dispatchEntry;
1861 return; // skip the inconsistent event
1866 case EventEntry::TYPE_MOTION: {
1867 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1868 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1869 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1870 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1871 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1872 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1873 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1874 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1875 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1876 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1877 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1879 dispatchEntry->resolvedAction = motionEntry->action;
1881 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1882 && !connection->inputState.isHovering(
1883 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
1884 #if DEBUG_DISPATCH_CYCLE
1885 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
1886 connection->getInputChannelName());
1888 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1891 dispatchEntry->resolvedFlags = motionEntry->flags;
1892 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1893 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1896 if (!connection->inputState.trackMotion(motionEntry,
1897 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1898 #if DEBUG_DISPATCH_CYCLE
1899 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
1900 connection->getInputChannelName());
1902 delete dispatchEntry;
1903 return; // skip the inconsistent event
1909 // Remember that we are waiting for this dispatch to complete.
1910 if (dispatchEntry->hasForegroundTarget()) {
1911 incrementPendingForegroundDispatchesLocked(eventEntry);
1914 // Enqueue the dispatch entry.
1915 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1916 traceOutboundQueueLengthLocked(connection);
1919 void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
1920 const sp<Connection>& connection) {
1921 #if DEBUG_DISPATCH_CYCLE
1922 ALOGD("channel '%s' ~ startDispatchCycle",
1923 connection->getInputChannelName());
1926 while (connection->status == Connection::STATUS_NORMAL
1927 && !connection->outboundQueue.isEmpty()) {
1928 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
1929 dispatchEntry->deliveryTime = currentTime;
1931 // Publish the event.
1933 EventEntry* eventEntry = dispatchEntry->eventEntry;
1934 switch (eventEntry->type) {
1935 case EventEntry::TYPE_KEY: {
1936 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1938 // Publish the key event.
1939 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
1940 keyEntry->deviceId, keyEntry->source,
1941 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1942 keyEntry->keyCode, keyEntry->scanCode,
1943 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1944 keyEntry->eventTime);
1948 case EventEntry::TYPE_MOTION: {
1949 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1951 PointerCoords scaledCoords[MAX_POINTERS];
1952 const PointerCoords* usingCoords = motionEntry->pointerCoords;
1954 // Set the X and Y offset depending on the input source.
1955 float xOffset, yOffset, scaleFactor;
1956 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1957 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1958 scaleFactor = dispatchEntry->scaleFactor;
1959 xOffset = dispatchEntry->xOffset * scaleFactor;
1960 yOffset = dispatchEntry->yOffset * scaleFactor;
1961 if (scaleFactor != 1.0f) {
1962 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1963 scaledCoords[i] = motionEntry->pointerCoords[i];
1964 scaledCoords[i].scale(scaleFactor);
1966 usingCoords = scaledCoords;
1973 // We don't want the dispatch target to know.
1974 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1975 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1976 scaledCoords[i].clear();
1978 usingCoords = scaledCoords;
1982 // Publish the motion event.
1983 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
1984 motionEntry->deviceId, motionEntry->source,
1985 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1986 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
1988 motionEntry->xPrecision, motionEntry->yPrecision,
1989 motionEntry->downTime, motionEntry->eventTime,
1990 motionEntry->pointerCount, motionEntry->pointerProperties,
2000 // Check the result.
2002 if (status == WOULD_BLOCK) {
2003 if (connection->waitQueue.isEmpty()) {
2004 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2005 "This is unexpected because the wait queue is empty, so the pipe "
2006 "should be empty and we shouldn't have any problems writing an "
2007 "event to it, status=%d", connection->getInputChannelName(), status);
2008 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2010 // Pipe is full and we are waiting for the app to finish process some events
2011 // before sending more events to it.
2012 #if DEBUG_DISPATCH_CYCLE
2013 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2014 "waiting for the application to catch up",
2015 connection->getInputChannelName());
2017 connection->inputPublisherBlocked = true;
2020 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2021 "status=%d", connection->getInputChannelName(), status);
2022 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2027 // Re-enqueue the event on the wait queue.
2028 connection->outboundQueue.dequeue(dispatchEntry);
2029 traceOutboundQueueLengthLocked(connection);
2030 connection->waitQueue.enqueueAtTail(dispatchEntry);
2031 traceWaitQueueLengthLocked(connection);
2035 void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2036 const sp<Connection>& connection, uint32_t seq, bool handled) {
2037 #if DEBUG_DISPATCH_CYCLE
2038 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2039 connection->getInputChannelName(), seq, toString(handled));
2042 connection->inputPublisherBlocked = false;
2044 if (connection->status == Connection::STATUS_BROKEN
2045 || connection->status == Connection::STATUS_ZOMBIE) {
2049 // Notify other system components and prepare to start the next dispatch cycle.
2050 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2053 void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2054 const sp<Connection>& connection, bool notify) {
2055 #if DEBUG_DISPATCH_CYCLE
2056 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
2057 connection->getInputChannelName(), toString(notify));
2060 // Clear the dispatch queues.
2061 drainDispatchQueueLocked(&connection->outboundQueue);
2062 traceOutboundQueueLengthLocked(connection);
2063 drainDispatchQueueLocked(&connection->waitQueue);
2064 traceWaitQueueLengthLocked(connection);
2066 // The connection appears to be unrecoverably broken.
2067 // Ignore already broken or zombie connections.
2068 if (connection->status == Connection::STATUS_NORMAL) {
2069 connection->status = Connection::STATUS_BROKEN;
2072 // Notify other system components.
2073 onDispatchCycleBrokenLocked(currentTime, connection);
2078 void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2079 while (!queue->isEmpty()) {
2080 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2081 releaseDispatchEntryLocked(dispatchEntry);
2085 void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2086 if (dispatchEntry->hasForegroundTarget()) {
2087 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2089 delete dispatchEntry;
2092 int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2093 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2096 AutoMutex _l(d->mLock);
2098 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2099 if (connectionIndex < 0) {
2100 ALOGE("Received spurious receive callback for unknown input channel. "
2101 "fd=%d, events=0x%x", fd, events);
2102 return 0; // remove the callback
2106 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2107 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2108 if (!(events & ALOOPER_EVENT_INPUT)) {
2109 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2110 "events=0x%x", connection->getInputChannelName(), events);
2114 nsecs_t currentTime = now();
2115 bool gotOne = false;
2120 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2124 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2128 d->runCommandsLockedInterruptible();
2129 if (status == WOULD_BLOCK) {
2134 notify = status != DEAD_OBJECT || !connection->monitor;
2136 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2137 connection->getInputChannelName(), status);
2140 // Monitor channels are never explicitly unregistered.
2141 // We do it automatically when the remote endpoint is closed so don't warn
2143 notify = !connection->monitor;
2145 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
2146 "events=0x%x", connection->getInputChannelName(), events);
2150 // Unregister the channel.
2151 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2152 return 0; // remove the callback
2156 void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2157 const CancelationOptions& options) {
2158 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2159 synthesizeCancelationEventsForConnectionLocked(
2160 mConnectionsByFd.valueAt(i), options);
2164 void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2165 const sp<InputChannel>& channel, const CancelationOptions& options) {
2166 ssize_t index = getConnectionIndexLocked(channel);
2168 synthesizeCancelationEventsForConnectionLocked(
2169 mConnectionsByFd.valueAt(index), options);
2173 void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2174 const sp<Connection>& connection, const CancelationOptions& options) {
2175 if (connection->status == Connection::STATUS_BROKEN) {
2179 nsecs_t currentTime = now();
2181 Vector<EventEntry*> cancelationEvents;
2182 connection->inputState.synthesizeCancelationEvents(currentTime,
2183 cancelationEvents, options);
2185 if (!cancelationEvents.isEmpty()) {
2186 #if DEBUG_OUTBOUND_EVENT_DETAILS
2187 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
2188 "with reality: %s, mode=%d.",
2189 connection->getInputChannelName(), cancelationEvents.size(),
2190 options.reason, options.mode);
2192 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2193 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2194 switch (cancelationEventEntry->type) {
2195 case EventEntry::TYPE_KEY:
2196 logOutboundKeyDetailsLocked("cancel - ",
2197 static_cast<KeyEntry*>(cancelationEventEntry));
2199 case EventEntry::TYPE_MOTION:
2200 logOutboundMotionDetailsLocked("cancel - ",
2201 static_cast<MotionEntry*>(cancelationEventEntry));
2206 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2207 if (windowHandle != NULL) {
2208 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2209 target.xOffset = -windowInfo->frameLeft;
2210 target.yOffset = -windowInfo->frameTop;
2211 target.scaleFactor = windowInfo->scaleFactor;
2215 target.scaleFactor = 1.0f;
2217 target.inputChannel = connection->inputChannel;
2218 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2220 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2221 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2223 cancelationEventEntry->release();
2226 startDispatchCycleLocked(currentTime, connection);
2230 InputDispatcher::MotionEntry*
2231 InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2232 ALOG_ASSERT(pointerIds.value != 0);
2234 uint32_t splitPointerIndexMap[MAX_POINTERS];
2235 PointerProperties splitPointerProperties[MAX_POINTERS];
2236 PointerCoords splitPointerCoords[MAX_POINTERS];
2238 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2239 uint32_t splitPointerCount = 0;
2241 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2242 originalPointerIndex++) {
2243 const PointerProperties& pointerProperties =
2244 originalMotionEntry->pointerProperties[originalPointerIndex];
2245 uint32_t pointerId = uint32_t(pointerProperties.id);
2246 if (pointerIds.hasBit(pointerId)) {
2247 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2248 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2249 splitPointerCoords[splitPointerCount].copyFrom(
2250 originalMotionEntry->pointerCoords[originalPointerIndex]);
2251 splitPointerCount += 1;
2255 if (splitPointerCount != pointerIds.count()) {
2256 // This is bad. We are missing some of the pointers that we expected to deliver.
2257 // Most likely this indicates that we received an ACTION_MOVE events that has
2258 // different pointer ids than we expected based on the previous ACTION_DOWN
2259 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2261 ALOGW("Dropping split motion event because the pointer count is %d but "
2262 "we expected there to be %d pointers. This probably means we received "
2263 "a broken sequence of pointer ids from the input device.",
2264 splitPointerCount, pointerIds.count());
2268 int32_t action = originalMotionEntry->action;
2269 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2270 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2271 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2272 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2273 const PointerProperties& pointerProperties =
2274 originalMotionEntry->pointerProperties[originalPointerIndex];
2275 uint32_t pointerId = uint32_t(pointerProperties.id);
2276 if (pointerIds.hasBit(pointerId)) {
2277 if (pointerIds.count() == 1) {
2278 // The first/last pointer went down/up.
2279 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2280 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2282 // A secondary pointer went down/up.
2283 uint32_t splitPointerIndex = 0;
2284 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2285 splitPointerIndex += 1;
2287 action = maskedAction | (splitPointerIndex
2288 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2291 // An unrelated pointer changed.
2292 action = AMOTION_EVENT_ACTION_MOVE;
2296 MotionEntry* splitMotionEntry = new MotionEntry(
2297 originalMotionEntry->eventTime,
2298 originalMotionEntry->deviceId,
2299 originalMotionEntry->source,
2300 originalMotionEntry->policyFlags,
2302 originalMotionEntry->flags,
2303 originalMotionEntry->metaState,
2304 originalMotionEntry->buttonState,
2305 originalMotionEntry->edgeFlags,
2306 originalMotionEntry->xPrecision,
2307 originalMotionEntry->yPrecision,
2308 originalMotionEntry->downTime,
2309 originalMotionEntry->displayId,
2310 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
2312 if (originalMotionEntry->injectionState) {
2313 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2314 splitMotionEntry->injectionState->refCount += 1;
2317 return splitMotionEntry;
2320 void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2321 #if DEBUG_INBOUND_EVENT_DETAILS
2322 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
2327 AutoMutex _l(mLock);
2329 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2330 needWake = enqueueInboundEventLocked(newEntry);
2338 void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2339 #if DEBUG_INBOUND_EVENT_DETAILS
2340 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
2341 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
2342 args->eventTime, args->deviceId, args->source, args->policyFlags,
2343 args->action, args->flags, args->keyCode, args->scanCode,
2344 args->metaState, args->downTime);
2346 if (!validateKeyEvent(args->action)) {
2350 uint32_t policyFlags = args->policyFlags;
2351 int32_t flags = args->flags;
2352 int32_t metaState = args->metaState;
2353 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2354 policyFlags |= POLICY_FLAG_VIRTUAL;
2355 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2357 if (policyFlags & POLICY_FLAG_ALT) {
2358 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2360 if (policyFlags & POLICY_FLAG_ALT_GR) {
2361 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2363 if (policyFlags & POLICY_FLAG_SHIFT) {
2364 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2366 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2367 metaState |= AMETA_CAPS_LOCK_ON;
2369 if (policyFlags & POLICY_FLAG_FUNCTION) {
2370 metaState |= AMETA_FUNCTION_ON;
2373 policyFlags |= POLICY_FLAG_TRUSTED;
2376 event.initialize(args->deviceId, args->source, args->action,
2377 flags, args->keyCode, args->scanCode, metaState, 0,
2378 args->downTime, args->eventTime);
2380 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2386 if (shouldSendKeyToInputFilterLocked(args)) {
2389 policyFlags |= POLICY_FLAG_FILTERED;
2390 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2391 return; // event was consumed by the filter
2397 int32_t repeatCount = 0;
2398 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2399 args->deviceId, args->source, policyFlags,
2400 args->action, flags, args->keyCode, args->scanCode,
2401 metaState, repeatCount, args->downTime);
2403 needWake = enqueueInboundEventLocked(newEntry);
2412 bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2413 return mInputFilterEnabled;
2416 void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2417 #if DEBUG_INBOUND_EVENT_DETAILS
2418 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
2419 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
2420 "xPrecision=%f, yPrecision=%f, downTime=%lld",
2421 args->eventTime, args->deviceId, args->source, args->policyFlags,
2422 args->action, args->flags, args->metaState, args->buttonState,
2423 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2424 for (uint32_t i = 0; i < args->pointerCount; i++) {
2425 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2426 "x=%f, y=%f, pressure=%f, size=%f, "
2427 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2429 i, args->pointerProperties[i].id,
2430 args->pointerProperties[i].toolType,
2431 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2432 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2433 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2434 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2435 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2436 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2437 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2438 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2439 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2442 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
2446 uint32_t policyFlags = args->policyFlags;
2447 policyFlags |= POLICY_FLAG_TRUSTED;
2448 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
2454 if (shouldSendMotionToInputFilterLocked(args)) {
2458 event.initialize(args->deviceId, args->source, args->action, args->flags,
2459 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2460 args->xPrecision, args->yPrecision,
2461 args->downTime, args->eventTime,
2462 args->pointerCount, args->pointerProperties, args->pointerCoords);
2464 policyFlags |= POLICY_FLAG_FILTERED;
2465 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2466 return; // event was consumed by the filter
2472 // Just enqueue a new motion event.
2473 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2474 args->deviceId, args->source, policyFlags,
2475 args->action, args->flags, args->metaState, args->buttonState,
2476 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2478 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
2480 needWake = enqueueInboundEventLocked(newEntry);
2489 bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2490 // TODO: support sending secondary display events to input filter
2491 return mInputFilterEnabled && isMainDisplay(args->displayId);
2494 void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2495 #if DEBUG_INBOUND_EVENT_DETAILS
2496 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x",
2497 args->eventTime, args->policyFlags,
2498 args->switchValues, args->switchMask);
2501 uint32_t policyFlags = args->policyFlags;
2502 policyFlags |= POLICY_FLAG_TRUSTED;
2503 mPolicy->notifySwitch(args->eventTime,
2504 args->switchValues, args->switchMask, policyFlags);
2507 void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2508 #if DEBUG_INBOUND_EVENT_DETAILS
2509 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
2510 args->eventTime, args->deviceId);
2515 AutoMutex _l(mLock);
2517 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2518 needWake = enqueueInboundEventLocked(newEntry);
2526 int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t displayId,
2527 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2528 uint32_t policyFlags) {
2529 #if DEBUG_INBOUND_EVENT_DETAILS
2530 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
2531 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2532 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
2535 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2537 policyFlags |= POLICY_FLAG_INJECTED;
2538 if (hasInjectionPermission(injectorPid, injectorUid)) {
2539 policyFlags |= POLICY_FLAG_TRUSTED;
2542 EventEntry* firstInjectedEntry;
2543 EventEntry* lastInjectedEntry;
2544 switch (event->getType()) {
2545 case AINPUT_EVENT_TYPE_KEY: {
2546 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2547 int32_t action = keyEvent->getAction();
2548 if (! validateKeyEvent(action)) {
2549 return INPUT_EVENT_INJECTION_FAILED;
2552 int32_t flags = keyEvent->getFlags();
2553 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2554 policyFlags |= POLICY_FLAG_VIRTUAL;
2557 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2558 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2562 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
2563 keyEvent->getDeviceId(), keyEvent->getSource(),
2564 policyFlags, action, flags,
2565 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
2566 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2567 lastInjectedEntry = firstInjectedEntry;
2571 case AINPUT_EVENT_TYPE_MOTION: {
2572 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2573 int32_t action = motionEvent->getAction();
2574 size_t pointerCount = motionEvent->getPointerCount();
2575 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2576 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
2577 return INPUT_EVENT_INJECTION_FAILED;
2580 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2581 nsecs_t eventTime = motionEvent->getEventTime();
2582 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2586 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2587 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2588 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
2589 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2590 action, motionEvent->getFlags(),
2591 motionEvent->getMetaState(), motionEvent->getButtonState(),
2592 motionEvent->getEdgeFlags(),
2593 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2594 motionEvent->getDownTime(), displayId,
2595 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2596 motionEvent->getXOffset(), motionEvent->getYOffset());
2597 lastInjectedEntry = firstInjectedEntry;
2598 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2599 sampleEventTimes += 1;
2600 samplePointerCoords += pointerCount;
2601 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2602 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2603 action, motionEvent->getFlags(),
2604 motionEvent->getMetaState(), motionEvent->getButtonState(),
2605 motionEvent->getEdgeFlags(),
2606 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2607 motionEvent->getDownTime(), displayId,
2608 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2609 motionEvent->getXOffset(), motionEvent->getYOffset());
2610 lastInjectedEntry->next = nextInjectedEntry;
2611 lastInjectedEntry = nextInjectedEntry;
2617 ALOGW("Cannot inject event of type %d", event->getType());
2618 return INPUT_EVENT_INJECTION_FAILED;
2621 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2622 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2623 injectionState->injectionIsAsync = true;
2626 injectionState->refCount += 1;
2627 lastInjectedEntry->injectionState = injectionState;
2629 bool needWake = false;
2630 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2631 EventEntry* nextEntry = entry->next;
2632 needWake |= enqueueInboundEventLocked(entry);
2642 int32_t injectionResult;
2644 AutoMutex _l(mLock);
2646 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2647 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2650 injectionResult = injectionState->injectionResult;
2651 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2655 nsecs_t remainingTimeout = endTime - now();
2656 if (remainingTimeout <= 0) {
2658 ALOGD("injectInputEvent - Timed out waiting for injection result "
2659 "to become available.");
2661 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2665 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2668 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2669 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2670 while (injectionState->pendingForegroundDispatches != 0) {
2672 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2673 injectionState->pendingForegroundDispatches);
2675 nsecs_t remainingTimeout = endTime - now();
2676 if (remainingTimeout <= 0) {
2678 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2679 "dispatches to finish.");
2681 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2685 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2690 injectionState->release();
2694 ALOGD("injectInputEvent - Finished with result %d. "
2695 "injectorPid=%d, injectorUid=%d",
2696 injectionResult, injectorPid, injectorUid);
2699 return injectionResult;
2702 bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2703 return injectorUid == 0
2704 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2707 void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2708 InjectionState* injectionState = entry->injectionState;
2709 if (injectionState) {
2711 ALOGD("Setting input event injection result to %d. "
2712 "injectorPid=%d, injectorUid=%d",
2713 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2716 if (injectionState->injectionIsAsync
2717 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2718 // Log the outcome since the injector did not wait for the injection result.
2719 switch (injectionResult) {
2720 case INPUT_EVENT_INJECTION_SUCCEEDED:
2721 ALOGV("Asynchronous input event injection succeeded.");
2723 case INPUT_EVENT_INJECTION_FAILED:
2724 ALOGW("Asynchronous input event injection failed.");
2726 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2727 ALOGW("Asynchronous input event injection permission denied.");
2729 case INPUT_EVENT_INJECTION_TIMED_OUT:
2730 ALOGW("Asynchronous input event injection timed out.");
2735 injectionState->injectionResult = injectionResult;
2736 mInjectionResultAvailableCondition.broadcast();
2740 void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2741 InjectionState* injectionState = entry->injectionState;
2742 if (injectionState) {
2743 injectionState->pendingForegroundDispatches += 1;
2747 void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2748 InjectionState* injectionState = entry->injectionState;
2749 if (injectionState) {
2750 injectionState->pendingForegroundDispatches -= 1;
2752 if (injectionState->pendingForegroundDispatches == 0) {
2753 mInjectionSyncFinishedCondition.broadcast();
2758 sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2759 const sp<InputChannel>& inputChannel) const {
2760 size_t numWindows = mWindowHandles.size();
2761 for (size_t i = 0; i < numWindows; i++) {
2762 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2763 if (windowHandle->getInputChannel() == inputChannel) {
2764 return windowHandle;
2770 bool InputDispatcher::hasWindowHandleLocked(
2771 const sp<InputWindowHandle>& windowHandle) const {
2772 size_t numWindows = mWindowHandles.size();
2773 for (size_t i = 0; i < numWindows; i++) {
2774 if (mWindowHandles.itemAt(i) == windowHandle) {
2781 void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
2783 ALOGD("setInputWindows");
2786 AutoMutex _l(mLock);
2788 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
2789 mWindowHandles = inputWindowHandles;
2791 sp<InputWindowHandle> newFocusedWindowHandle;
2792 bool foundHoveredWindow = false;
2793 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2794 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2795 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
2796 mWindowHandles.removeAt(i--);
2799 if (windowHandle->getInfo()->hasFocus) {
2800 newFocusedWindowHandle = windowHandle;
2802 if (windowHandle == mLastHoverWindowHandle) {
2803 foundHoveredWindow = true;
2807 if (!foundHoveredWindow) {
2808 mLastHoverWindowHandle = NULL;
2811 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2812 if (mFocusedWindowHandle != NULL) {
2814 ALOGD("Focus left window: %s",
2815 mFocusedWindowHandle->getName().string());
2817 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2818 if (focusedInputChannel != NULL) {
2819 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2820 "focus left window");
2821 synthesizeCancelationEventsForInputChannelLocked(
2822 focusedInputChannel, options);
2825 if (newFocusedWindowHandle != NULL) {
2827 ALOGD("Focus entered window: %s",
2828 newFocusedWindowHandle->getName().string());
2831 mFocusedWindowHandle = newFocusedWindowHandle;
2834 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
2835 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
2836 for (size_t i = 0; i < state.windows.size(); i++) {
2837 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
2838 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
2840 ALOGD("Touched window was removed: %s",
2841 touchedWindow.windowHandle->getName().string());
2843 sp<InputChannel> touchedInputChannel =
2844 touchedWindow.windowHandle->getInputChannel();
2845 if (touchedInputChannel != NULL) {
2846 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2847 "touched window was removed");
2848 synthesizeCancelationEventsForInputChannelLocked(
2849 touchedInputChannel, options);
2851 state.windows.removeAt(i--);
2856 // Release information for windows that are no longer present.
2857 // This ensures that unused input channels are released promptly.
2858 // Otherwise, they might stick around until the window handle is destroyed
2859 // which might not happen until the next GC.
2860 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2861 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2862 if (!hasWindowHandleLocked(oldWindowHandle)) {
2864 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
2866 oldWindowHandle->releaseInfo();
2871 // Wake up poll loop since it may need to make new input dispatching choices.
2875 void InputDispatcher::setFocusedApplication(
2876 const sp<InputApplicationHandle>& inputApplicationHandle) {
2878 ALOGD("setFocusedApplication");
2881 AutoMutex _l(mLock);
2883 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
2884 if (mFocusedApplicationHandle != inputApplicationHandle) {
2885 if (mFocusedApplicationHandle != NULL) {
2886 resetANRTimeoutsLocked();
2887 mFocusedApplicationHandle->releaseInfo();
2889 mFocusedApplicationHandle = inputApplicationHandle;
2891 } else if (mFocusedApplicationHandle != NULL) {
2892 resetANRTimeoutsLocked();
2893 mFocusedApplicationHandle->releaseInfo();
2894 mFocusedApplicationHandle.clear();
2898 //logDispatchStateLocked();
2902 // Wake up poll loop since it may need to make new input dispatching choices.
2906 void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2908 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2913 AutoMutex _l(mLock);
2915 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
2916 if (mDispatchFrozen && !frozen) {
2917 resetANRTimeoutsLocked();
2920 if (mDispatchEnabled && !enabled) {
2921 resetAndDropEverythingLocked("dispatcher is being disabled");
2924 mDispatchEnabled = enabled;
2925 mDispatchFrozen = frozen;
2932 //logDispatchStateLocked();
2937 // Wake up poll loop since it may need to make new input dispatching choices.
2942 void InputDispatcher::setInputFilterEnabled(bool enabled) {
2944 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
2948 AutoMutex _l(mLock);
2950 if (mInputFilterEnabled == enabled) {
2954 mInputFilterEnabled = enabled;
2955 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2958 // Wake up poll loop since there might be work to do to drop everything.
2962 bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2963 const sp<InputChannel>& toChannel) {
2965 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
2966 fromChannel->getName().string(), toChannel->getName().string());
2969 AutoMutex _l(mLock);
2971 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2972 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2973 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
2975 ALOGD("Cannot transfer focus because from or to window not found.");
2979 if (fromWindowHandle == toWindowHandle) {
2981 ALOGD("Trivial transfer to same window.");
2985 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
2987 ALOGD("Cannot transfer focus because windows are on different displays.");
2993 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
2994 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
2995 for (size_t i = 0; i < state.windows.size(); i++) {
2996 const TouchedWindow& touchedWindow = state.windows[i];
2997 if (touchedWindow.windowHandle == fromWindowHandle) {
2998 int32_t oldTargetFlags = touchedWindow.targetFlags;
2999 BitSet32 pointerIds = touchedWindow.pointerIds;
3001 state.windows.removeAt(i);
3003 int32_t newTargetFlags = oldTargetFlags
3004 & (InputTarget::FLAG_FOREGROUND
3005 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3006 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
3017 ALOGD("Focus transfer failed because from window did not have focus.");
3022 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3023 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3024 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3025 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3026 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3028 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3029 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3030 "transferring touch focus from this window to another window");
3031 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3035 logDispatchStateLocked();
3039 // Wake up poll loop since it may need to make new input dispatching choices.
3044 void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3046 ALOGD("Resetting and dropping all events (%s).", reason);
3049 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3050 synthesizeCancelationEventsForAllConnectionsLocked(options);
3052 resetKeyRepeatLocked();
3053 releasePendingEventLocked();
3054 drainInboundQueueLocked();
3055 resetANRTimeoutsLocked();
3057 mTouchStatesByDisplay.clear();
3058 mLastHoverWindowHandle.clear();
3061 void InputDispatcher::logDispatchStateLocked() {
3063 dumpDispatchStateLocked(dump);
3065 char* text = dump.lockBuffer(dump.size());
3067 while (*start != '\0') {
3068 char* end = strchr(start, '\n');
3077 void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
3078 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3079 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
3081 if (mFocusedApplicationHandle != NULL) {
3082 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
3083 mFocusedApplicationHandle->getName().string(),
3084 mFocusedApplicationHandle->getDispatchingTimeout(
3085 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3087 dump.append(INDENT "FocusedApplication: <null>\n");
3089 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
3090 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
3092 if (!mTouchStatesByDisplay.isEmpty()) {
3093 dump.appendFormat(INDENT "TouchStatesByDisplay:\n");
3094 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3095 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
3096 dump.appendFormat(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
3097 state.displayId, toString(state.down), toString(state.split),
3098 state.deviceId, state.source);
3099 if (!state.windows.isEmpty()) {
3100 dump.append(INDENT3 "Windows:\n");
3101 for (size_t i = 0; i < state.windows.size(); i++) {
3102 const TouchedWindow& touchedWindow = state.windows[i];
3103 dump.appendFormat(INDENT4 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3104 i, touchedWindow.windowHandle->getName().string(),
3105 touchedWindow.pointerIds.value,
3106 touchedWindow.targetFlags);
3109 dump.append(INDENT3 "Windows: <none>\n");
3113 dump.append(INDENT "TouchStates: <no displays touched>\n");
3116 if (!mWindowHandles.isEmpty()) {
3117 dump.append(INDENT "Windows:\n");
3118 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3119 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3120 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3122 dump.appendFormat(INDENT2 "%d: name='%s', displayId=%d, "
3123 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3124 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3125 "frame=[%d,%d][%d,%d], scale=%f, "
3127 i, windowInfo->name.string(), windowInfo->displayId,
3128 toString(windowInfo->paused),
3129 toString(windowInfo->hasFocus),
3130 toString(windowInfo->hasWallpaper),
3131 toString(windowInfo->visible),
3132 toString(windowInfo->canReceiveKeys),
3133 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3135 windowInfo->frameLeft, windowInfo->frameTop,
3136 windowInfo->frameRight, windowInfo->frameBottom,
3137 windowInfo->scaleFactor);
3138 dumpRegion(dump, windowInfo->touchableRegion);
3139 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3140 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3141 windowInfo->ownerPid, windowInfo->ownerUid,
3142 windowInfo->dispatchingTimeout / 1000000.0);
3145 dump.append(INDENT "Windows: <none>\n");
3148 if (!mMonitoringChannels.isEmpty()) {
3149 dump.append(INDENT "MonitoringChannels:\n");
3150 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3151 const sp<InputChannel>& channel = mMonitoringChannels[i];
3152 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3155 dump.append(INDENT "MonitoringChannels: <none>\n");
3158 nsecs_t currentTime = now();
3160 // Dump recently dispatched or dropped events from oldest to newest.
3161 if (!mRecentQueue.isEmpty()) {
3162 dump.appendFormat(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
3163 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
3164 dump.append(INDENT2);
3165 entry->appendDescription(dump);
3166 dump.appendFormat(", age=%0.1fms\n",
3167 (currentTime - entry->eventTime) * 0.000001f);
3170 dump.append(INDENT "RecentQueue: <empty>\n");
3173 // Dump event currently being dispatched.
3174 if (mPendingEvent) {
3175 dump.append(INDENT "PendingEvent:\n");
3176 dump.append(INDENT2);
3177 mPendingEvent->appendDescription(dump);
3178 dump.appendFormat(", age=%0.1fms\n",
3179 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3181 dump.append(INDENT "PendingEvent: <none>\n");
3184 // Dump inbound events from oldest to newest.
3185 if (!mInboundQueue.isEmpty()) {
3186 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3187 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3188 dump.append(INDENT2);
3189 entry->appendDescription(dump);
3190 dump.appendFormat(", age=%0.1fms\n",
3191 (currentTime - entry->eventTime) * 0.000001f);
3194 dump.append(INDENT "InboundQueue: <empty>\n");
3197 if (!mConnectionsByFd.isEmpty()) {
3198 dump.append(INDENT "Connections:\n");
3199 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3200 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
3201 dump.appendFormat(INDENT2 "%d: channelName='%s', windowName='%s', "
3202 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3203 i, connection->getInputChannelName(), connection->getWindowName(),
3204 connection->getStatusLabel(), toString(connection->monitor),
3205 toString(connection->inputPublisherBlocked));
3207 if (!connection->outboundQueue.isEmpty()) {
3208 dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
3209 connection->outboundQueue.count());
3210 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3211 entry = entry->next) {
3212 dump.append(INDENT4);
3213 entry->eventEntry->appendDescription(dump);
3214 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
3215 entry->targetFlags, entry->resolvedAction,
3216 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3219 dump.append(INDENT3 "OutboundQueue: <empty>\n");
3222 if (!connection->waitQueue.isEmpty()) {
3223 dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
3224 connection->waitQueue.count());
3225 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3226 entry = entry->next) {
3227 dump.append(INDENT4);
3228 entry->eventEntry->appendDescription(dump);
3229 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
3230 "age=%0.1fms, wait=%0.1fms\n",
3231 entry->targetFlags, entry->resolvedAction,
3232 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3233 (currentTime - entry->deliveryTime) * 0.000001f);
3236 dump.append(INDENT3 "WaitQueue: <empty>\n");
3240 dump.append(INDENT "Connections: <none>\n");
3243 if (isAppSwitchPendingLocked()) {
3244 dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
3245 (mAppSwitchDueTime - now()) / 1000000.0);
3247 dump.append(INDENT "AppSwitch: not pending\n");
3250 dump.append(INDENT "Configuration:\n");
3251 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
3252 mConfig.keyRepeatDelay * 0.000001f);
3253 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3254 mConfig.keyRepeatTimeout * 0.000001f);
3257 status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3258 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
3259 #if DEBUG_REGISTRATION
3260 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3265 AutoMutex _l(mLock);
3267 if (getConnectionIndexLocked(inputChannel) >= 0) {
3268 ALOGW("Attempted to register already registered input channel '%s'",
3269 inputChannel->getName().string());
3273 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3275 int fd = inputChannel->getFd();
3276 mConnectionsByFd.add(fd, connection);
3279 mMonitoringChannels.push(inputChannel);
3282 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3285 // Wake the looper because some connections have changed.
3290 status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3291 #if DEBUG_REGISTRATION
3292 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
3296 AutoMutex _l(mLock);
3298 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3304 // Wake the poll loop because removing the connection may have changed the current
3305 // synchronization state.
3310 status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3312 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3313 if (connectionIndex < 0) {
3314 ALOGW("Attempted to unregister already unregistered input channel '%s'",
3315 inputChannel->getName().string());
3319 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3320 mConnectionsByFd.removeItemsAt(connectionIndex);
3322 if (connection->monitor) {
3323 removeMonitorChannelLocked(inputChannel);
3326 mLooper->removeFd(inputChannel->getFd());
3328 nsecs_t currentTime = now();
3329 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3331 connection->status = Connection::STATUS_ZOMBIE;
3335 void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3336 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3337 if (mMonitoringChannels[i] == inputChannel) {
3338 mMonitoringChannels.removeAt(i);
3344 ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
3345 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3346 if (connectionIndex >= 0) {
3347 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3348 if (connection->inputChannel.get() == inputChannel.get()) {
3349 return connectionIndex;
3356 void InputDispatcher::onDispatchCycleFinishedLocked(
3357 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3358 CommandEntry* commandEntry = postCommandLocked(
3359 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3360 commandEntry->connection = connection;
3361 commandEntry->eventTime = currentTime;
3362 commandEntry->seq = seq;
3363 commandEntry->handled = handled;
3366 void InputDispatcher::onDispatchCycleBrokenLocked(
3367 nsecs_t currentTime, const sp<Connection>& connection) {
3368 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3369 connection->getInputChannelName());
3371 CommandEntry* commandEntry = postCommandLocked(
3372 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3373 commandEntry->connection = connection;
3376 void InputDispatcher::onANRLocked(
3377 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3378 const sp<InputWindowHandle>& windowHandle,
3379 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3380 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3381 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3382 ALOGI("Application is not responding: %s. "
3383 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
3384 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
3385 dispatchLatency, waitDuration, reason);
3387 // Capture a record of the InputDispatcher state at the time of the ANR.
3388 time_t t = time(NULL);
3390 localtime_r(&t, &tm);
3392 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3393 mLastANRState.clear();
3394 mLastANRState.append(INDENT "ANR:\n");
3395 mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
3396 mLastANRState.appendFormat(INDENT2 "Window: %s\n",
3397 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
3398 mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3399 mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3400 mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
3401 dumpDispatchStateLocked(mLastANRState);
3403 CommandEntry* commandEntry = postCommandLocked(
3404 & InputDispatcher::doNotifyANRLockedInterruptible);
3405 commandEntry->inputApplicationHandle = applicationHandle;
3406 commandEntry->inputWindowHandle = windowHandle;
3407 commandEntry->reason = reason;
3410 void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3411 CommandEntry* commandEntry) {
3414 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3419 void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3420 CommandEntry* commandEntry) {
3421 sp<Connection> connection = commandEntry->connection;
3423 if (connection->status != Connection::STATUS_ZOMBIE) {
3426 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3432 void InputDispatcher::doNotifyANRLockedInterruptible(
3433 CommandEntry* commandEntry) {
3436 nsecs_t newTimeout = mPolicy->notifyANR(
3437 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3438 commandEntry->reason);
3442 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3443 commandEntry->inputWindowHandle != NULL
3444 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
3447 void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3448 CommandEntry* commandEntry) {
3449 KeyEntry* entry = commandEntry->keyEntry;
3452 initializeKeyEvent(&event, entry);
3456 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3457 &event, entry->policyFlags);
3462 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3463 } else if (!delay) {
3464 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3466 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3467 entry->interceptKeyWakeupTime = now() + delay;
3472 void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3473 CommandEntry* commandEntry) {
3474 sp<Connection> connection = commandEntry->connection;
3475 nsecs_t finishTime = commandEntry->eventTime;
3476 uint32_t seq = commandEntry->seq;
3477 bool handled = commandEntry->handled;
3479 // Handle post-event policy actions.
3480 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3481 if (dispatchEntry) {
3482 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3483 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
3485 msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
3486 connection->getWindowName(), eventDuration * 0.000001f);
3487 dispatchEntry->eventEntry->appendDescription(msg);
3488 ALOGI("%s", msg.string());
3492 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3493 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3494 restartEvent = afterKeyEventLockedInterruptible(connection,
3495 dispatchEntry, keyEntry, handled);
3496 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3497 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3498 restartEvent = afterMotionEventLockedInterruptible(connection,
3499 dispatchEntry, motionEntry, handled);
3501 restartEvent = false;
3504 // Dequeue the event and start the next cycle.
3505 // Note that because the lock might have been released, it is possible that the
3506 // contents of the wait queue to have been drained, so we need to double-check
3508 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3509 connection->waitQueue.dequeue(dispatchEntry);
3510 traceWaitQueueLengthLocked(connection);
3511 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3512 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3513 traceOutboundQueueLengthLocked(connection);
3515 releaseDispatchEntryLocked(dispatchEntry);
3519 // Start the next dispatch cycle for this connection.
3520 startDispatchCycleLocked(now(), connection);
3524 bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3525 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3526 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3527 // Get the fallback key state.
3528 // Clear it out after dispatching the UP.
3529 int32_t originalKeyCode = keyEntry->keyCode;
3530 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3531 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3532 connection->inputState.removeFallbackKey(originalKeyCode);
3535 if (handled || !dispatchEntry->hasForegroundTarget()) {
3536 // If the application handles the original key for which we previously
3537 // generated a fallback or if the window is not a foreground window,
3538 // then cancel the associated fallback key, if any.
3539 if (fallbackKeyCode != -1) {
3540 // Dispatch the unhandled key to the policy with the cancel flag.
3541 #if DEBUG_OUTBOUND_EVENT_DETAILS
3542 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3543 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3544 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3545 keyEntry->policyFlags);
3548 initializeKeyEvent(&event, keyEntry);
3549 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3553 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3554 &event, keyEntry->policyFlags, &event);
3558 // Cancel the fallback key.
3559 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3560 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3561 "application handled the original non-fallback key "
3562 "or is no longer a foreground target, "
3563 "canceling previously dispatched fallback key");
3564 options.keyCode = fallbackKeyCode;
3565 synthesizeCancelationEventsForConnectionLocked(connection, options);
3567 connection->inputState.removeFallbackKey(originalKeyCode);
3570 // If the application did not handle a non-fallback key, first check
3571 // that we are in a good state to perform unhandled key event processing
3572 // Then ask the policy what to do with it.
3573 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3574 && keyEntry->repeatCount == 0;
3575 if (fallbackKeyCode == -1 && !initialDown) {
3576 #if DEBUG_OUTBOUND_EVENT_DETAILS
3577 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3578 "since this is not an initial down. "
3579 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3580 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3581 keyEntry->policyFlags);
3586 // Dispatch the unhandled key to the policy.
3587 #if DEBUG_OUTBOUND_EVENT_DETAILS
3588 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
3589 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3590 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3591 keyEntry->policyFlags);
3594 initializeKeyEvent(&event, keyEntry);
3598 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3599 &event, keyEntry->policyFlags, &event);
3603 if (connection->status != Connection::STATUS_NORMAL) {
3604 connection->inputState.removeFallbackKey(originalKeyCode);
3608 // Latch the fallback keycode for this key on an initial down.
3609 // The fallback keycode cannot change at any other point in the lifecycle.
3612 fallbackKeyCode = event.getKeyCode();
3614 fallbackKeyCode = AKEYCODE_UNKNOWN;
3616 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3619 ALOG_ASSERT(fallbackKeyCode != -1);
3621 // Cancel the fallback key if the policy decides not to send it anymore.
3622 // We will continue to dispatch the key to the policy but we will no
3623 // longer dispatch a fallback key to the application.
3624 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3625 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3626 #if DEBUG_OUTBOUND_EVENT_DETAILS
3628 ALOGD("Unhandled key event: Policy requested to send key %d"
3629 "as a fallback for %d, but on the DOWN it had requested "
3630 "to send %d instead. Fallback canceled.",
3631 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3633 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
3634 "but on the DOWN it had requested to send %d. "
3635 "Fallback canceled.",
3636 originalKeyCode, fallbackKeyCode);
3640 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3641 "canceling fallback, policy no longer desires it");
3642 options.keyCode = fallbackKeyCode;
3643 synthesizeCancelationEventsForConnectionLocked(connection, options);
3646 fallbackKeyCode = AKEYCODE_UNKNOWN;
3647 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3648 connection->inputState.setFallbackKey(originalKeyCode,
3653 #if DEBUG_OUTBOUND_EVENT_DETAILS
3656 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3657 connection->inputState.getFallbackKeys();
3658 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3659 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3660 fallbackKeys.valueAt(i));
3662 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3663 fallbackKeys.size(), msg.string());
3668 // Restart the dispatch cycle using the fallback key.
3669 keyEntry->eventTime = event.getEventTime();
3670 keyEntry->deviceId = event.getDeviceId();
3671 keyEntry->source = event.getSource();
3672 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3673 keyEntry->keyCode = fallbackKeyCode;
3674 keyEntry->scanCode = event.getScanCode();
3675 keyEntry->metaState = event.getMetaState();
3676 keyEntry->repeatCount = event.getRepeatCount();
3677 keyEntry->downTime = event.getDownTime();
3678 keyEntry->syntheticRepeat = false;
3680 #if DEBUG_OUTBOUND_EVENT_DETAILS
3681 ALOGD("Unhandled key event: Dispatching fallback key. "
3682 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3683 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3685 return true; // restart the event
3687 #if DEBUG_OUTBOUND_EVENT_DETAILS
3688 ALOGD("Unhandled key event: No fallback key.");
3696 bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3697 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3701 void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3704 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
3709 void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3710 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3711 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3712 entry->downTime, entry->eventTime);
3715 void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3716 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3717 // TODO Write some statistics about how long we spend waiting.
3720 void InputDispatcher::traceInboundQueueLengthLocked() {
3721 if (ATRACE_ENABLED()) {
3722 ATRACE_INT("iq", mInboundQueue.count());
3726 void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3727 if (ATRACE_ENABLED()) {
3728 char counterName[40];
3729 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3730 ATRACE_INT(counterName, connection->outboundQueue.count());
3734 void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3735 if (ATRACE_ENABLED()) {
3736 char counterName[40];
3737 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3738 ATRACE_INT(counterName, connection->waitQueue.count());
3742 void InputDispatcher::dump(String8& dump) {
3743 AutoMutex _l(mLock);
3745 dump.append("Input Dispatcher State:\n");
3746 dumpDispatchStateLocked(dump);
3748 if (!mLastANRState.isEmpty()) {
3749 dump.append("\nInput Dispatcher State at time of last ANR:\n");
3750 dump.append(mLastANRState);
3754 void InputDispatcher::monitor() {
3755 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3758 mDispatcherIsAliveCondition.wait(mLock);
3763 // --- InputDispatcher::Queue ---
3765 template <typename T>
3766 uint32_t InputDispatcher::Queue<T>::count() const {
3767 uint32_t result = 0;
3768 for (const T* entry = head; entry; entry = entry->next) {
3775 // --- InputDispatcher::InjectionState ---
3777 InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3779 injectorPid(injectorPid), injectorUid(injectorUid),
3780 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3781 pendingForegroundDispatches(0) {
3784 InputDispatcher::InjectionState::~InjectionState() {
3787 void InputDispatcher::InjectionState::release() {
3789 if (refCount == 0) {
3792 ALOG_ASSERT(refCount > 0);
3797 // --- InputDispatcher::EventEntry ---
3799 InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3800 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3801 injectionState(NULL), dispatchInProgress(false) {
3804 InputDispatcher::EventEntry::~EventEntry() {
3805 releaseInjectionState();
3808 void InputDispatcher::EventEntry::release() {
3810 if (refCount == 0) {
3813 ALOG_ASSERT(refCount > 0);
3817 void InputDispatcher::EventEntry::releaseInjectionState() {
3818 if (injectionState) {
3819 injectionState->release();
3820 injectionState = NULL;
3825 // --- InputDispatcher::ConfigurationChangedEntry ---
3827 InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3828 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3831 InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3834 void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
3835 msg.append("ConfigurationChangedEvent(), policyFlags=0x%08x",
3840 // --- InputDispatcher::DeviceResetEntry ---
3842 InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3843 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3844 deviceId(deviceId) {
3847 InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3850 void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
3851 msg.appendFormat("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
3852 deviceId, policyFlags);
3856 // --- InputDispatcher::KeyEntry ---
3858 InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
3859 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
3860 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3861 int32_t repeatCount, nsecs_t downTime) :
3862 EventEntry(TYPE_KEY, eventTime, policyFlags),
3863 deviceId(deviceId), source(source), action(action), flags(flags),
3864 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3865 repeatCount(repeatCount), downTime(downTime),
3866 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3867 interceptKeyWakeupTime(0) {
3870 InputDispatcher::KeyEntry::~KeyEntry() {
3873 void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
3874 msg.appendFormat("KeyEvent(deviceId=%d, source=0x%08x, action=%d, "
3875 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
3876 "repeatCount=%d), policyFlags=0x%08x",
3877 deviceId, source, action, flags, keyCode, scanCode, metaState,
3878 repeatCount, policyFlags);
3881 void InputDispatcher::KeyEntry::recycle() {
3882 releaseInjectionState();
3884 dispatchInProgress = false;
3885 syntheticRepeat = false;
3886 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
3887 interceptKeyWakeupTime = 0;
3891 // --- InputDispatcher::MotionEntry ---
3893 InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3894 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3895 int32_t metaState, int32_t buttonState,
3896 int32_t edgeFlags, float xPrecision, float yPrecision,
3897 nsecs_t downTime, int32_t displayId, uint32_t pointerCount,
3898 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
3899 float xOffset, float yOffset) :
3900 EventEntry(TYPE_MOTION, eventTime, policyFlags),
3901 eventTime(eventTime),
3902 deviceId(deviceId), source(source), action(action), flags(flags),
3903 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3904 xPrecision(xPrecision), yPrecision(yPrecision),
3905 downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
3906 for (uint32_t i = 0; i < pointerCount; i++) {
3907 this->pointerProperties[i].copyFrom(pointerProperties[i]);
3908 this->pointerCoords[i].copyFrom(pointerCoords[i]);
3909 if (xOffset || yOffset) {
3910 this->pointerCoords[i].applyOffset(xOffset, yOffset);
3915 InputDispatcher::MotionEntry::~MotionEntry() {
3918 void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
3919 msg.appendFormat("MotionEvent(deviceId=%d, source=0x%08x, action=%d, "
3920 "flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, edgeFlags=0x%08x, "
3921 "xPrecision=%.1f, yPrecision=%.1f, displayId=%d, pointers=[",
3922 deviceId, source, action, flags, metaState, buttonState, edgeFlags,
3923 xPrecision, yPrecision, displayId);
3924 for (uint32_t i = 0; i < pointerCount; i++) {
3928 msg.appendFormat("%d: (%.1f, %.1f)", pointerProperties[i].id,
3929 pointerCoords[i].getX(), pointerCoords[i].getY());
3931 msg.appendFormat("]), policyFlags=0x%08x", policyFlags);
3935 // --- InputDispatcher::DispatchEntry ---
3937 volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3939 InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3940 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
3942 eventEntry(eventEntry), targetFlags(targetFlags),
3943 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
3944 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
3945 eventEntry->refCount += 1;
3948 InputDispatcher::DispatchEntry::~DispatchEntry() {
3949 eventEntry->release();
3952 uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3953 // Sequence number 0 is reserved and will never be returned.
3956 seq = android_atomic_inc(&sNextSeqAtomic);
3962 // --- InputDispatcher::InputState ---
3964 InputDispatcher::InputState::InputState() {
3967 InputDispatcher::InputState::~InputState() {
3970 bool InputDispatcher::InputState::isNeutral() const {
3971 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3974 bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
3975 int32_t displayId) const {
3976 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3977 const MotionMemento& memento = mMotionMementos.itemAt(i);
3978 if (memento.deviceId == deviceId
3979 && memento.source == source
3980 && memento.displayId == displayId
3981 && memento.hovering) {
3988 bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3989 int32_t action, int32_t flags) {
3991 case AKEY_EVENT_ACTION_UP: {
3992 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
3993 for (size_t i = 0; i < mFallbackKeys.size(); ) {
3994 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
3995 mFallbackKeys.removeItemsAt(i);
4001 ssize_t index = findKeyMemento(entry);
4003 mKeyMementos.removeAt(index);
4006 /* FIXME: We can't just drop the key up event because that prevents creating
4007 * popup windows that are automatically shown when a key is held and then
4008 * dismissed when the key is released. The problem is that the popup will
4009 * not have received the original key down, so the key up will be considered
4010 * to be inconsistent with its observed state. We could perhaps handle this
4011 * by synthesizing a key down but that will cause other problems.
4013 * So for now, allow inconsistent key up events to be dispatched.
4015 #if DEBUG_OUTBOUND_EVENT_DETAILS
4016 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4017 "keyCode=%d, scanCode=%d",
4018 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4025 case AKEY_EVENT_ACTION_DOWN: {
4026 ssize_t index = findKeyMemento(entry);
4028 mKeyMementos.removeAt(index);
4030 addKeyMemento(entry, flags);
4039 bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4040 int32_t action, int32_t flags) {
4041 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4042 switch (actionMasked) {
4043 case AMOTION_EVENT_ACTION_UP:
4044 case AMOTION_EVENT_ACTION_CANCEL: {
4045 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4047 mMotionMementos.removeAt(index);
4050 #if DEBUG_OUTBOUND_EVENT_DETAILS
4051 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4053 entry->deviceId, entry->source, actionMasked);
4058 case AMOTION_EVENT_ACTION_DOWN: {
4059 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4061 mMotionMementos.removeAt(index);
4063 addMotionMemento(entry, flags, false /*hovering*/);
4067 case AMOTION_EVENT_ACTION_POINTER_UP:
4068 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4069 case AMOTION_EVENT_ACTION_MOVE: {
4070 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4071 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4072 // generate cancellation events for these since they're based in relative rather than
4077 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4079 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4080 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4081 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4082 // other value and we need to track the motion so we can send cancellation events for
4083 // anything generating fallback events (e.g. DPad keys for joystick movements).
4085 if (entry->pointerCoords[0].isEmpty()) {
4086 mMotionMementos.removeAt(index);
4088 MotionMemento& memento = mMotionMementos.editItemAt(index);
4089 memento.setPointers(entry);
4091 } else if (!entry->pointerCoords[0].isEmpty()) {
4092 addMotionMemento(entry, flags, false /*hovering*/);
4095 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4099 MotionMemento& memento = mMotionMementos.editItemAt(index);
4100 memento.setPointers(entry);
4103 #if DEBUG_OUTBOUND_EVENT_DETAILS
4104 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
4105 "deviceId=%d, source=%08x, actionMasked=%d",
4106 entry->deviceId, entry->source, actionMasked);
4111 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4112 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4114 mMotionMementos.removeAt(index);
4117 #if DEBUG_OUTBOUND_EVENT_DETAILS
4118 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4119 entry->deviceId, entry->source);
4124 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4125 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4126 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4128 mMotionMementos.removeAt(index);
4130 addMotionMemento(entry, flags, true /*hovering*/);
4139 ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4140 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4141 const KeyMemento& memento = mKeyMementos.itemAt(i);
4142 if (memento.deviceId == entry->deviceId
4143 && memento.source == entry->source
4144 && memento.keyCode == entry->keyCode
4145 && memento.scanCode == entry->scanCode) {
4152 ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4153 bool hovering) const {
4154 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4155 const MotionMemento& memento = mMotionMementos.itemAt(i);
4156 if (memento.deviceId == entry->deviceId
4157 && memento.source == entry->source
4158 && memento.displayId == entry->displayId
4159 && memento.hovering == hovering) {
4166 void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4167 mKeyMementos.push();
4168 KeyMemento& memento = mKeyMementos.editTop();
4169 memento.deviceId = entry->deviceId;
4170 memento.source = entry->source;
4171 memento.keyCode = entry->keyCode;
4172 memento.scanCode = entry->scanCode;
4173 memento.metaState = entry->metaState;
4174 memento.flags = flags;
4175 memento.downTime = entry->downTime;
4176 memento.policyFlags = entry->policyFlags;
4179 void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4180 int32_t flags, bool hovering) {
4181 mMotionMementos.push();
4182 MotionMemento& memento = mMotionMementos.editTop();
4183 memento.deviceId = entry->deviceId;
4184 memento.source = entry->source;
4185 memento.flags = flags;
4186 memento.xPrecision = entry->xPrecision;
4187 memento.yPrecision = entry->yPrecision;
4188 memento.downTime = entry->downTime;
4189 memento.displayId = entry->displayId;
4190 memento.setPointers(entry);
4191 memento.hovering = hovering;
4192 memento.policyFlags = entry->policyFlags;
4195 void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4196 pointerCount = entry->pointerCount;
4197 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4198 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4199 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4203 void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4204 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4205 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4206 const KeyMemento& memento = mKeyMementos.itemAt(i);
4207 if (shouldCancelKey(memento, options)) {
4208 outEvents.push(new KeyEntry(currentTime,
4209 memento.deviceId, memento.source, memento.policyFlags,
4210 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4211 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4215 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4216 const MotionMemento& memento = mMotionMementos.itemAt(i);
4217 if (shouldCancelMotion(memento, options)) {
4218 outEvents.push(new MotionEntry(currentTime,
4219 memento.deviceId, memento.source, memento.policyFlags,
4221 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4222 : AMOTION_EVENT_ACTION_CANCEL,
4223 memento.flags, 0, 0, 0,
4224 memento.xPrecision, memento.yPrecision, memento.downTime,
4226 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4232 void InputDispatcher::InputState::clear() {
4233 mKeyMementos.clear();
4234 mMotionMementos.clear();
4235 mFallbackKeys.clear();
4238 void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4239 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4240 const MotionMemento& memento = mMotionMementos.itemAt(i);
4241 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4242 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4243 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4244 if (memento.deviceId == otherMemento.deviceId
4245 && memento.source == otherMemento.source
4246 && memento.displayId == otherMemento.displayId) {
4247 other.mMotionMementos.removeAt(j);
4252 other.mMotionMementos.push(memento);
4257 int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4258 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4259 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4262 void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4263 int32_t fallbackKeyCode) {
4264 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4266 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4268 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4272 void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4273 mFallbackKeys.removeItem(originalKeyCode);
4276 bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4277 const CancelationOptions& options) {
4278 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4282 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4286 switch (options.mode) {
4287 case CancelationOptions::CANCEL_ALL_EVENTS:
4288 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4290 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4291 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4297 bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4298 const CancelationOptions& options) {
4299 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4303 switch (options.mode) {
4304 case CancelationOptions::CANCEL_ALL_EVENTS:
4306 case CancelationOptions::CANCEL_POINTER_EVENTS:
4307 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4308 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4309 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4316 // --- InputDispatcher::Connection ---
4318 InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4319 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4320 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4322 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4325 InputDispatcher::Connection::~Connection() {
4328 const char* InputDispatcher::Connection::getWindowName() const {
4329 if (inputWindowHandle != NULL) {
4330 return inputWindowHandle->getName().string();
4338 const char* InputDispatcher::Connection::getStatusLabel() const {
4354 InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4355 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4356 if (entry->seq == seq) {
4364 // --- InputDispatcher::CommandEntry ---
4366 InputDispatcher::CommandEntry::CommandEntry(Command command) :
4367 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4368 seq(0), handled(false) {
4371 InputDispatcher::CommandEntry::~CommandEntry() {
4375 // --- InputDispatcher::TouchState ---
4377 InputDispatcher::TouchState::TouchState() :
4378 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
4381 InputDispatcher::TouchState::~TouchState() {
4384 void InputDispatcher::TouchState::reset() {
4393 void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4395 split = other.split;
4396 deviceId = other.deviceId;
4397 source = other.source;
4398 displayId = other.displayId;
4399 windows = other.windows;
4402 void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4403 int32_t targetFlags, BitSet32 pointerIds) {
4404 if (targetFlags & InputTarget::FLAG_SPLIT) {
4408 for (size_t i = 0; i < windows.size(); i++) {
4409 TouchedWindow& touchedWindow = windows.editItemAt(i);
4410 if (touchedWindow.windowHandle == windowHandle) {
4411 touchedWindow.targetFlags |= targetFlags;
4412 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4413 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4415 touchedWindow.pointerIds.value |= pointerIds.value;
4422 TouchedWindow& touchedWindow = windows.editTop();
4423 touchedWindow.windowHandle = windowHandle;
4424 touchedWindow.targetFlags = targetFlags;
4425 touchedWindow.pointerIds = pointerIds;
4428 void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4429 for (size_t i = 0; i < windows.size(); i++) {
4430 if (windows.itemAt(i).windowHandle == windowHandle) {
4431 windows.removeAt(i);
4437 void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4438 for (size_t i = 0 ; i < windows.size(); ) {
4439 TouchedWindow& window = windows.editItemAt(i);
4440 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4441 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4442 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4443 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4446 windows.removeAt(i);
4451 sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4452 for (size_t i = 0; i < windows.size(); i++) {
4453 const TouchedWindow& window = windows.itemAt(i);
4454 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4455 return window.windowHandle;
4461 bool InputDispatcher::TouchState::isSlippery() const {
4462 // Must have exactly one foreground window.
4463 bool haveSlipperyForegroundWindow = false;
4464 for (size_t i = 0; i < windows.size(); i++) {
4465 const TouchedWindow& window = windows.itemAt(i);
4466 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4467 if (haveSlipperyForegroundWindow
4468 || !(window.windowHandle->getInfo()->layoutParamsFlags
4469 & InputWindowInfo::FLAG_SLIPPERY)) {
4472 haveSlipperyForegroundWindow = true;
4475 return haveSlipperyForegroundWindow;
4479 // --- InputDispatcherThread ---
4481 InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4482 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4485 InputDispatcherThread::~InputDispatcherThread() {
4488 bool InputDispatcherThread::threadLoop() {
4489 mDispatcher->dispatchOnce();
4493 } // namespace android