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 we disallow key events, even if the next event
252 // is not a key. This is to ensure that we abort a key repeat if the device is just coming
254 if (!mPolicy->isKeyRepeatEnabled()) {
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;
478 if (windowInfo->visible) {
479 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
480 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
481 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
482 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
489 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
490 // Error window is on top but not visible, so touch is dropped.
498 void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
500 switch (dropReason) {
501 case DROP_REASON_POLICY:
502 #if DEBUG_INBOUND_EVENT_DETAILS
503 ALOGD("Dropped event because policy consumed it.");
505 reason = "inbound event was dropped because the policy consumed it";
507 case DROP_REASON_DISABLED:
508 ALOGI("Dropped event because input dispatch is disabled.");
509 reason = "inbound event was dropped because input dispatch is disabled";
511 case DROP_REASON_APP_SWITCH:
512 ALOGI("Dropped event because of pending overdue app switch.");
513 reason = "inbound event was dropped because of pending overdue app switch";
515 case DROP_REASON_BLOCKED:
516 ALOGI("Dropped event because the current application is not responding and the user "
517 "has started interacting with a different application.");
518 reason = "inbound event was dropped because the current application is not responding "
519 "and the user has started interacting with a different application";
521 case DROP_REASON_STALE:
522 ALOGI("Dropped event because it is stale.");
523 reason = "inbound event was dropped because it is stale";
530 switch (entry->type) {
531 case EventEntry::TYPE_KEY: {
532 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
533 synthesizeCancelationEventsForAllConnectionsLocked(options);
536 case EventEntry::TYPE_MOTION: {
537 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
538 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
539 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
540 synthesizeCancelationEventsForAllConnectionsLocked(options);
542 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
543 synthesizeCancelationEventsForAllConnectionsLocked(options);
550 bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
551 return keyCode == AKEYCODE_HOME
552 || keyCode == AKEYCODE_ENDCALL
553 || keyCode == AKEYCODE_APP_SWITCH;
556 bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
557 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
558 && isAppSwitchKeyCode(keyEntry->keyCode)
559 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
560 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
563 bool InputDispatcher::isAppSwitchPendingLocked() {
564 return mAppSwitchDueTime != LONG_LONG_MAX;
567 void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
568 mAppSwitchDueTime = LONG_LONG_MAX;
572 ALOGD("App switch has arrived.");
574 ALOGD("App switch was abandoned.");
579 bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
580 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
583 bool InputDispatcher::haveCommandsLocked() const {
584 return !mCommandQueue.isEmpty();
587 bool InputDispatcher::runCommandsLockedInterruptible() {
588 if (mCommandQueue.isEmpty()) {
593 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
595 Command command = commandEntry->command;
596 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
598 commandEntry->connection.clear();
600 } while (! mCommandQueue.isEmpty());
604 InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
605 CommandEntry* commandEntry = new CommandEntry(command);
606 mCommandQueue.enqueueAtTail(commandEntry);
610 void InputDispatcher::drainInboundQueueLocked() {
611 while (! mInboundQueue.isEmpty()) {
612 EventEntry* entry = mInboundQueue.dequeueAtHead();
613 releaseInboundEventLocked(entry);
615 traceInboundQueueLengthLocked();
618 void InputDispatcher::releasePendingEventLocked() {
620 resetANRTimeoutsLocked();
621 releaseInboundEventLocked(mPendingEvent);
622 mPendingEvent = NULL;
626 void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
627 InjectionState* injectionState = entry->injectionState;
628 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
629 #if DEBUG_DISPATCH_CYCLE
630 ALOGD("Injected inbound event was dropped.");
632 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
634 if (entry == mNextUnblockedEvent) {
635 mNextUnblockedEvent = NULL;
637 addRecentEventLocked(entry);
641 void InputDispatcher::resetKeyRepeatLocked() {
642 if (mKeyRepeatState.lastKeyEntry) {
643 mKeyRepeatState.lastKeyEntry->release();
644 mKeyRepeatState.lastKeyEntry = NULL;
648 InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
649 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
651 // Reuse the repeated key entry if it is otherwise unreferenced.
652 uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
653 | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
654 if (entry->refCount == 1) {
656 entry->eventTime = currentTime;
657 entry->policyFlags = policyFlags;
658 entry->repeatCount += 1;
660 KeyEntry* newEntry = new KeyEntry(currentTime,
661 entry->deviceId, entry->source, policyFlags,
662 entry->action, entry->flags, entry->keyCode, entry->scanCode,
663 entry->metaState, entry->repeatCount + 1, entry->downTime);
665 mKeyRepeatState.lastKeyEntry = newEntry;
670 entry->syntheticRepeat = true;
672 // Increment reference count since we keep a reference to the event in
673 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
674 entry->refCount += 1;
676 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
680 bool InputDispatcher::dispatchConfigurationChangedLocked(
681 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
682 #if DEBUG_OUTBOUND_EVENT_DETAILS
683 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
686 // Reset key repeating in case a keyboard device was added or removed or something.
687 resetKeyRepeatLocked();
689 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
690 CommandEntry* commandEntry = postCommandLocked(
691 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
692 commandEntry->eventTime = entry->eventTime;
696 bool InputDispatcher::dispatchDeviceResetLocked(
697 nsecs_t currentTime, DeviceResetEntry* entry) {
698 #if DEBUG_OUTBOUND_EVENT_DETAILS
699 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
702 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
704 options.deviceId = entry->deviceId;
705 synthesizeCancelationEventsForAllConnectionsLocked(options);
709 bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
710 DropReason* dropReason, nsecs_t* nextWakeupTime) {
712 if (! entry->dispatchInProgress) {
713 if (entry->repeatCount == 0
714 && entry->action == AKEY_EVENT_ACTION_DOWN
715 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
716 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
717 if (mKeyRepeatState.lastKeyEntry
718 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
719 // We have seen two identical key downs in a row which indicates that the device
720 // driver is automatically generating key repeats itself. We take note of the
721 // repeat here, but we disable our own next key repeat timer since it is clear that
722 // we will not need to synthesize key repeats ourselves.
723 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
724 resetKeyRepeatLocked();
725 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
727 // Not a repeat. Save key down state in case we do see a repeat later.
728 resetKeyRepeatLocked();
729 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
731 mKeyRepeatState.lastKeyEntry = entry;
732 entry->refCount += 1;
733 } else if (! entry->syntheticRepeat) {
734 resetKeyRepeatLocked();
737 if (entry->repeatCount == 1) {
738 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
740 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
743 entry->dispatchInProgress = true;
745 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
748 // Handle case where the policy asked us to try again later last time.
749 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
750 if (currentTime < entry->interceptKeyWakeupTime) {
751 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
752 *nextWakeupTime = entry->interceptKeyWakeupTime;
754 return false; // wait until next wakeup
756 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
757 entry->interceptKeyWakeupTime = 0;
760 // Give the policy a chance to intercept the key.
761 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
762 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
763 CommandEntry* commandEntry = postCommandLocked(
764 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
765 if (mFocusedWindowHandle != NULL) {
766 commandEntry->inputWindowHandle = mFocusedWindowHandle;
768 commandEntry->keyEntry = entry;
769 entry->refCount += 1;
770 return false; // wait for the command to run
772 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
774 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
775 if (*dropReason == DROP_REASON_NOT_DROPPED) {
776 *dropReason = DROP_REASON_POLICY;
780 // Clean up if dropping the event.
781 if (*dropReason != DROP_REASON_NOT_DROPPED) {
782 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
783 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
788 Vector<InputTarget> inputTargets;
789 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
790 entry, inputTargets, nextWakeupTime);
791 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
795 setInjectionResultLocked(entry, injectionResult);
796 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
800 addMonitoringTargetsLocked(inputTargets);
803 dispatchEventLocked(currentTime, entry, inputTargets);
807 void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
808 #if DEBUG_OUTBOUND_EVENT_DETAILS
809 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
810 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
811 "repeatCount=%d, downTime=%lld",
813 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
814 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
815 entry->repeatCount, entry->downTime);
819 bool InputDispatcher::dispatchMotionLocked(
820 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
822 if (! entry->dispatchInProgress) {
823 entry->dispatchInProgress = true;
825 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
828 // Clean up if dropping the event.
829 if (*dropReason != DROP_REASON_NOT_DROPPED) {
830 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
831 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
835 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
838 Vector<InputTarget> inputTargets;
840 bool conflictingPointerActions = false;
841 int32_t injectionResult;
842 if (isPointerEvent) {
843 // Pointer event. (eg. touchscreen)
844 injectionResult = findTouchedWindowTargetsLocked(currentTime,
845 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
847 // Non touch event. (eg. trackball)
848 injectionResult = findFocusedWindowTargetsLocked(currentTime,
849 entry, inputTargets, nextWakeupTime);
851 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
855 setInjectionResultLocked(entry, injectionResult);
856 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
860 // TODO: support sending secondary display events to input monitors
861 if (isMainDisplay(entry->displayId)) {
862 addMonitoringTargetsLocked(inputTargets);
865 // Dispatch the motion.
866 if (conflictingPointerActions) {
867 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
868 "conflicting pointer actions");
869 synthesizeCancelationEventsForAllConnectionsLocked(options);
871 dispatchEventLocked(currentTime, entry, inputTargets);
876 void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
877 #if DEBUG_OUTBOUND_EVENT_DETAILS
878 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
879 "action=0x%x, flags=0x%x, "
880 "metaState=0x%x, buttonState=0x%x, "
881 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
883 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
884 entry->action, entry->flags,
885 entry->metaState, entry->buttonState,
886 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
889 for (uint32_t i = 0; i < entry->pointerCount; i++) {
890 ALOGD(" Pointer %d: id=%d, toolType=%d, "
891 "x=%f, y=%f, pressure=%f, size=%f, "
892 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
894 i, entry->pointerProperties[i].id,
895 entry->pointerProperties[i].toolType,
896 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
897 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
898 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
899 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
900 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
901 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
902 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
903 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
904 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
909 void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
910 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
911 #if DEBUG_DISPATCH_CYCLE
912 ALOGD("dispatchEventToCurrentInputTargets");
915 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
917 pokeUserActivityLocked(eventEntry);
919 for (size_t i = 0; i < inputTargets.size(); i++) {
920 const InputTarget& inputTarget = inputTargets.itemAt(i);
922 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
923 if (connectionIndex >= 0) {
924 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
925 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
928 ALOGD("Dropping event delivery to target with channel '%s' because it "
929 "is no longer registered with the input dispatcher.",
930 inputTarget.inputChannel->getName().string());
936 int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
937 const EventEntry* entry,
938 const sp<InputApplicationHandle>& applicationHandle,
939 const sp<InputWindowHandle>& windowHandle,
940 nsecs_t* nextWakeupTime, const char* reason) {
941 if (applicationHandle == NULL && windowHandle == NULL) {
942 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
944 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
946 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
947 mInputTargetWaitStartTime = currentTime;
948 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
949 mInputTargetWaitTimeoutExpired = false;
950 mInputTargetWaitApplicationHandle.clear();
953 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
955 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
956 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
960 if (windowHandle != NULL) {
961 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
962 } else if (applicationHandle != NULL) {
963 timeout = applicationHandle->getDispatchingTimeout(
964 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
966 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
969 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
970 mInputTargetWaitStartTime = currentTime;
971 mInputTargetWaitTimeoutTime = currentTime + timeout;
972 mInputTargetWaitTimeoutExpired = false;
973 mInputTargetWaitApplicationHandle.clear();
975 if (windowHandle != NULL) {
976 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
978 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
979 mInputTargetWaitApplicationHandle = applicationHandle;
984 if (mInputTargetWaitTimeoutExpired) {
985 return INPUT_EVENT_INJECTION_TIMED_OUT;
988 if (currentTime >= mInputTargetWaitTimeoutTime) {
989 onANRLocked(currentTime, applicationHandle, windowHandle,
990 entry->eventTime, mInputTargetWaitStartTime, reason);
992 // Force poll loop to wake up immediately on next iteration once we get the
993 // ANR response back from the policy.
994 *nextWakeupTime = LONG_LONG_MIN;
995 return INPUT_EVENT_INJECTION_PENDING;
997 // Force poll loop to wake up when timeout is due.
998 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
999 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1001 return INPUT_EVENT_INJECTION_PENDING;
1005 void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1006 const sp<InputChannel>& inputChannel) {
1007 if (newTimeout > 0) {
1008 // Extend the timeout.
1009 mInputTargetWaitTimeoutTime = now() + newTimeout;
1012 mInputTargetWaitTimeoutExpired = true;
1014 // Input state will not be realistic. Mark it out of sync.
1015 if (inputChannel.get()) {
1016 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1017 if (connectionIndex >= 0) {
1018 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1019 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1021 if (windowHandle != NULL) {
1022 mTouchState.removeWindow(windowHandle);
1025 if (connection->status == Connection::STATUS_NORMAL) {
1026 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1027 "application not responding");
1028 synthesizeCancelationEventsForConnectionLocked(connection, options);
1035 nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1036 nsecs_t currentTime) {
1037 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1038 return currentTime - mInputTargetWaitStartTime;
1043 void InputDispatcher::resetANRTimeoutsLocked() {
1045 ALOGD("Resetting ANR timeouts.");
1048 // Reset input target wait timeout.
1049 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1050 mInputTargetWaitApplicationHandle.clear();
1053 int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1054 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1055 int32_t injectionResult;
1057 // If there is no currently focused window and no focused application
1058 // then drop the event.
1059 if (mFocusedWindowHandle == NULL) {
1060 if (mFocusedApplicationHandle != NULL) {
1061 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1062 mFocusedApplicationHandle, NULL, nextWakeupTime,
1063 "Waiting because no window has focus but there is a "
1064 "focused application that may eventually add a window "
1065 "when it finishes starting up.");
1069 ALOGI("Dropping event because there is no focused window or focused application.");
1070 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1074 // Check permissions.
1075 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
1076 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1080 // If the currently focused window is paused then keep waiting.
1081 if (mFocusedWindowHandle->getInfo()->paused) {
1082 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1083 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1084 "Waiting because the focused window is paused.");
1088 // If the currently focused window is still working on previous events then keep waiting.
1089 if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
1090 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1091 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
1092 "Waiting because the focused window has not finished "
1093 "processing the input events that were previously delivered to it.");
1097 // Success! Output targets.
1098 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1099 addWindowTargetLocked(mFocusedWindowHandle,
1100 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1106 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1107 updateDispatchStatisticsLocked(currentTime, entry,
1108 injectionResult, timeSpentWaitingForApplication);
1110 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1111 "timeSpentWaitingForApplication=%0.1fms",
1112 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1114 return injectionResult;
1117 int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1118 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1119 bool* outConflictingPointerActions) {
1120 enum InjectionPermission {
1121 INJECTION_PERMISSION_UNKNOWN,
1122 INJECTION_PERMISSION_GRANTED,
1123 INJECTION_PERMISSION_DENIED
1126 nsecs_t startTime = now();
1128 // For security reasons, we defer updating the touch state until we are sure that
1129 // event injection will be allowed.
1131 // FIXME In the original code, screenWasOff could never be set to true.
1132 // The reason is that the POLICY_FLAG_WOKE_HERE
1133 // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
1134 // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
1135 // actually enqueued using the policyFlags that appeared in the final EV_SYN
1136 // events upon which no preprocessing took place. So policyFlags was always 0.
1137 // In the new native input dispatcher we're a bit more careful about event
1138 // preprocessing so the touches we receive can actually have non-zero policyFlags.
1139 // Unfortunately we obtain undesirable behavior.
1141 // Here's what happens:
1143 // When the device dims in anticipation of going to sleep, touches
1144 // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
1145 // the device to brighten and reset the user activity timer.
1146 // Touches on other windows (such as the launcher window)
1147 // are dropped. Then after a moment, the device goes to sleep. Oops.
1149 // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1150 // instead of POLICY_FLAG_WOKE_HERE...
1152 bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1154 int32_t displayId = entry->displayId;
1155 int32_t action = entry->action;
1156 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1158 // Update the touch state as needed based on the properties of the touch event.
1159 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1160 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1161 sp<InputWindowHandle> newHoverWindowHandle;
1163 bool isSplit = mTouchState.split;
1164 bool switchedDevice = mTouchState.deviceId >= 0 && mTouchState.displayId >= 0
1165 && (mTouchState.deviceId != entry->deviceId
1166 || mTouchState.source != entry->source
1167 || mTouchState.displayId != displayId);
1168 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1169 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1170 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1171 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1172 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1174 bool wrongDevice = false;
1176 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1177 if (switchedDevice && mTouchState.down && !down) {
1179 ALOGD("Dropping event because a pointer for a different device is already down.");
1181 mTempTouchState.copyFrom(mTouchState);
1182 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1183 switchedDevice = false;
1187 mTempTouchState.reset();
1188 mTempTouchState.down = down;
1189 mTempTouchState.deviceId = entry->deviceId;
1190 mTempTouchState.source = entry->source;
1191 mTempTouchState.displayId = displayId;
1194 mTempTouchState.copyFrom(mTouchState);
1197 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1198 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1200 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1201 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1202 getAxisValue(AMOTION_EVENT_AXIS_X));
1203 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1204 getAxisValue(AMOTION_EVENT_AXIS_Y));
1205 sp<InputWindowHandle> newTouchedWindowHandle;
1206 sp<InputWindowHandle> topErrorWindowHandle;
1207 bool isTouchModal = false;
1209 // Traverse windows from front to back to find touched window and outside targets.
1210 size_t numWindows = mWindowHandles.size();
1211 for (size_t i = 0; i < numWindows; i++) {
1212 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1213 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1214 if (windowInfo->displayId != displayId) {
1215 continue; // wrong display
1218 int32_t flags = windowInfo->layoutParamsFlags;
1219 if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
1220 if (topErrorWindowHandle == NULL) {
1221 topErrorWindowHandle = windowHandle;
1225 if (windowInfo->visible) {
1226 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1227 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1228 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1229 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
1231 || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
1232 newTouchedWindowHandle = windowHandle;
1234 break; // found touched window, exit window loop
1238 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1239 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
1240 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
1241 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
1242 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1245 mTempTouchState.addOrUpdateWindow(
1246 windowHandle, outsideTargetFlags, BitSet32(0));
1251 // If there is an error window but it is not taking focus (typically because
1252 // it is invisible) then wait for it. Any other focused window may in
1253 // fact be in ANR state.
1254 if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
1255 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1256 NULL, NULL, nextWakeupTime,
1257 "Waiting because a system error window is about to be displayed.");
1258 injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1262 // Figure out whether splitting will be allowed for this window.
1263 if (newTouchedWindowHandle != NULL
1264 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1265 // New window supports splitting.
1267 } else if (isSplit) {
1268 // New window does not support splitting but we have already split events.
1269 // Ignore the new window.
1270 newTouchedWindowHandle = NULL;
1273 // Handle the case where we did not find a window.
1274 if (newTouchedWindowHandle == NULL) {
1275 // Try to assign the pointer to the first foreground window we find, if there is one.
1276 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1277 if (newTouchedWindowHandle == NULL) {
1278 // There is no touched window. If this is an initial down event
1279 // then wait for a window to appear that will handle the touch. This is
1280 // to ensure that we report an ANR in the case where an application has started
1281 // but not yet put up a window and the user is starting to get impatient.
1282 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1283 && mFocusedApplicationHandle != NULL) {
1284 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1285 mFocusedApplicationHandle, NULL, nextWakeupTime,
1286 "Waiting because there is no touchable window that can "
1287 "handle the event but there is focused application that may "
1288 "eventually add a new window when it finishes starting up.");
1292 ALOGI("Dropping event because there is no touched window.");
1293 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1298 // Set target flags.
1299 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1301 targetFlags |= InputTarget::FLAG_SPLIT;
1303 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1304 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1307 // Update hover state.
1308 if (isHoverAction) {
1309 newHoverWindowHandle = newTouchedWindowHandle;
1310 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1311 newHoverWindowHandle = mLastHoverWindowHandle;
1314 // Update the temporary touch state.
1315 BitSet32 pointerIds;
1317 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1318 pointerIds.markBit(pointerId);
1320 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1322 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1324 // If the pointer is not currently down, then ignore the event.
1325 if (! mTempTouchState.down) {
1327 ALOGD("Dropping event because the pointer is not down or we previously "
1328 "dropped the pointer down event.");
1330 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1334 // Check whether touches should slip outside of the current foreground window.
1335 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1336 && entry->pointerCount == 1
1337 && mTempTouchState.isSlippery()) {
1338 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1339 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1341 sp<InputWindowHandle> oldTouchedWindowHandle =
1342 mTempTouchState.getFirstForegroundWindowHandle();
1343 sp<InputWindowHandle> newTouchedWindowHandle =
1344 findTouchedWindowAtLocked(displayId, x, y);
1345 if (oldTouchedWindowHandle != newTouchedWindowHandle
1346 && newTouchedWindowHandle != NULL) {
1348 ALOGD("Touch is slipping out of window %s into window %s.",
1349 oldTouchedWindowHandle->getName().string(),
1350 newTouchedWindowHandle->getName().string());
1352 // Make a slippery exit from the old window.
1353 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1354 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1356 // Make a slippery entrance into the new window.
1357 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1361 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1362 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1364 targetFlags |= InputTarget::FLAG_SPLIT;
1366 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1367 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1370 BitSet32 pointerIds;
1372 pointerIds.markBit(entry->pointerProperties[0].id);
1374 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1379 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1380 // Let the previous window know that the hover sequence is over.
1381 if (mLastHoverWindowHandle != NULL) {
1383 ALOGD("Sending hover exit event to window %s.",
1384 mLastHoverWindowHandle->getName().string());
1386 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1387 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1390 // Let the new window know that the hover sequence is starting.
1391 if (newHoverWindowHandle != NULL) {
1393 ALOGD("Sending hover enter event to window %s.",
1394 newHoverWindowHandle->getName().string());
1396 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1397 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1401 // Check permission to inject into all touched foreground windows and ensure there
1402 // is at least one touched foreground window.
1404 bool haveForegroundWindow = false;
1405 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1406 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1407 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1408 haveForegroundWindow = true;
1409 if (! checkInjectionPermission(touchedWindow.windowHandle,
1410 entry->injectionState)) {
1411 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1412 injectionPermission = INJECTION_PERMISSION_DENIED;
1417 if (! haveForegroundWindow) {
1419 ALOGD("Dropping event because there is no touched foreground window to receive it.");
1421 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1425 // Permission granted to injection into all touched foreground windows.
1426 injectionPermission = INJECTION_PERMISSION_GRANTED;
1429 // Check whether windows listening for outside touches are owned by the same UID. If it is
1430 // set the policy flag that we will not reveal coordinate information to this window.
1431 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1432 sp<InputWindowHandle> foregroundWindowHandle =
1433 mTempTouchState.getFirstForegroundWindowHandle();
1434 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1435 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1436 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1437 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1438 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1439 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1440 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1441 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1447 // Ensure all touched foreground windows are ready for new input.
1448 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1449 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1450 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1451 // If the touched window is paused then keep waiting.
1452 if (touchedWindow.windowHandle->getInfo()->paused) {
1453 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1454 NULL, touchedWindow.windowHandle, nextWakeupTime,
1455 "Waiting because the touched window is paused.");
1459 // If the touched window is still working on previous events then keep waiting.
1460 if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
1461 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1462 NULL, touchedWindow.windowHandle, nextWakeupTime,
1463 "Waiting because the touched window has not finished "
1464 "processing the input events that were previously delivered to it.");
1470 // If this is the first pointer going down and the touched window has a wallpaper
1471 // then also add the touched wallpaper windows so they are locked in for the duration
1472 // of the touch gesture.
1473 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1474 // engine only supports touch events. We would need to add a mechanism similar
1475 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1476 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1477 sp<InputWindowHandle> foregroundWindowHandle =
1478 mTempTouchState.getFirstForegroundWindowHandle();
1479 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
1480 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1481 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1482 const InputWindowInfo* info = windowHandle->getInfo();
1483 if (info->displayId == displayId
1484 && windowHandle->getInfo()->layoutParamsType
1485 == InputWindowInfo::TYPE_WALLPAPER) {
1486 mTempTouchState.addOrUpdateWindow(windowHandle,
1487 InputTarget::FLAG_WINDOW_IS_OBSCURED
1488 | InputTarget::FLAG_DISPATCH_AS_IS,
1495 // Success! Output targets.
1496 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1498 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1499 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1500 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1501 touchedWindow.pointerIds, inputTargets);
1504 // Drop the outside or hover touch windows since we will not care about them
1505 // in the next iteration.
1506 mTempTouchState.filterNonAsIsTouchWindows();
1509 // Check injection permission once and for all.
1510 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
1511 if (checkInjectionPermission(NULL, entry->injectionState)) {
1512 injectionPermission = INJECTION_PERMISSION_GRANTED;
1514 injectionPermission = INJECTION_PERMISSION_DENIED;
1518 // Update final pieces of touch state if the injector had permission.
1519 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1521 if (switchedDevice) {
1523 ALOGD("Conflicting pointer actions: Switched to a different device.");
1525 *outConflictingPointerActions = true;
1528 if (isHoverAction) {
1529 // Started hovering, therefore no longer down.
1530 if (mTouchState.down) {
1532 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1534 *outConflictingPointerActions = true;
1536 mTouchState.reset();
1537 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1538 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
1539 mTouchState.deviceId = entry->deviceId;
1540 mTouchState.source = entry->source;
1541 mTouchState.displayId = displayId;
1543 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1544 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1545 // All pointers up or canceled.
1546 mTouchState.reset();
1547 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1548 // First pointer went down.
1549 if (mTouchState.down) {
1551 ALOGD("Conflicting pointer actions: Down received while already down.");
1553 *outConflictingPointerActions = true;
1555 mTouchState.copyFrom(mTempTouchState);
1556 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1557 // One pointer went up.
1559 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1560 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1562 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1563 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1564 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1565 touchedWindow.pointerIds.clearBit(pointerId);
1566 if (touchedWindow.pointerIds.isEmpty()) {
1567 mTempTouchState.windows.removeAt(i);
1574 mTouchState.copyFrom(mTempTouchState);
1575 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1576 // Discard temporary touch state since it was only valid for this action.
1578 // Save changes to touch state as-is for all other actions.
1579 mTouchState.copyFrom(mTempTouchState);
1582 // Update hover state.
1583 mLastHoverWindowHandle = newHoverWindowHandle;
1587 ALOGD("Not updating touch focus because injection was denied.");
1592 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1593 mTempTouchState.reset();
1595 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1596 updateDispatchStatisticsLocked(currentTime, entry,
1597 injectionResult, timeSpentWaitingForApplication);
1599 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1600 "timeSpentWaitingForApplication=%0.1fms",
1601 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1603 return injectionResult;
1606 void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1607 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1608 inputTargets.push();
1610 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1611 InputTarget& target = inputTargets.editTop();
1612 target.inputChannel = windowInfo->inputChannel;
1613 target.flags = targetFlags;
1614 target.xOffset = - windowInfo->frameLeft;
1615 target.yOffset = - windowInfo->frameTop;
1616 target.scaleFactor = windowInfo->scaleFactor;
1617 target.pointerIds = pointerIds;
1620 void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
1621 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1622 inputTargets.push();
1624 InputTarget& target = inputTargets.editTop();
1625 target.inputChannel = mMonitoringChannels[i];
1626 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1629 target.pointerIds.clear();
1630 target.scaleFactor = 1.0f;
1634 bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1635 const InjectionState* injectionState) {
1637 && (windowHandle == NULL
1638 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1639 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1640 if (windowHandle != NULL) {
1641 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1643 injectionState->injectorPid, injectionState->injectorUid,
1644 windowHandle->getName().string(),
1645 windowHandle->getInfo()->ownerUid);
1647 ALOGW("Permission denied: injecting event from pid %d uid %d",
1648 injectionState->injectorPid, injectionState->injectorUid);
1655 bool InputDispatcher::isWindowObscuredAtPointLocked(
1656 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1657 int32_t displayId = windowHandle->getInfo()->displayId;
1658 size_t numWindows = mWindowHandles.size();
1659 for (size_t i = 0; i < numWindows; i++) {
1660 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1661 if (otherHandle == windowHandle) {
1665 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1666 if (otherInfo->displayId == displayId
1667 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1668 && otherInfo->frameContainsPoint(x, y)) {
1675 bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
1676 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
1677 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
1678 if (connectionIndex >= 0) {
1679 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1680 if (connection->inputPublisherBlocked) {
1683 if (eventEntry->type == EventEntry::TYPE_KEY) {
1684 // If the event is a key event, then we must wait for all previous events to
1685 // complete before delivering it because previous events may have the
1686 // side-effect of transferring focus to a different window and we want to
1687 // ensure that the following keys are sent to the new window.
1689 // Suppose the user touches a button in a window then immediately presses "A".
1690 // If the button causes a pop-up window to appear then we want to ensure that
1691 // the "A" key is delivered to the new pop-up window. This is because users
1692 // often anticipate pending UI changes when typing on a keyboard.
1693 // To obtain this behavior, we must serialize key events with respect to all
1694 // prior input events.
1695 return connection->outboundQueue.isEmpty()
1696 && connection->waitQueue.isEmpty();
1698 // Touch events can always be sent to a window immediately because the user intended
1699 // to touch whatever was visible at the time. Even if focus changes or a new
1700 // window appears moments later, the touch event was meant to be delivered to
1701 // whatever window happened to be on screen at the time.
1703 // Generic motion events, such as trackball or joystick events are a little trickier.
1704 // Like key events, generic motion events are delivered to the focused window.
1705 // Unlike key events, generic motion events don't tend to transfer focus to other
1706 // windows and it is not important for them to be serialized. So we prefer to deliver
1707 // generic motion events as soon as possible to improve efficiency and reduce lag
1708 // through batching.
1710 // The one case where we pause input event delivery is when the wait queue is piling
1711 // up with lots of events because the application is not responding.
1712 // This condition ensures that ANRs are detected reliably.
1713 if (!connection->waitQueue.isEmpty()
1714 && currentTime >= connection->waitQueue.head->eventEntry->eventTime
1715 + STREAM_AHEAD_EVENT_TIMEOUT) {
1722 String8 InputDispatcher::getApplicationWindowLabelLocked(
1723 const sp<InputApplicationHandle>& applicationHandle,
1724 const sp<InputWindowHandle>& windowHandle) {
1725 if (applicationHandle != NULL) {
1726 if (windowHandle != NULL) {
1727 String8 label(applicationHandle->getName());
1728 label.append(" - ");
1729 label.append(windowHandle->getName());
1732 return applicationHandle->getName();
1734 } else if (windowHandle != NULL) {
1735 return windowHandle->getName();
1737 return String8("<unknown application or window>");
1741 void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
1742 if (mFocusedWindowHandle != NULL) {
1743 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1744 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1745 #if DEBUG_DISPATCH_CYCLE
1746 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.string());
1752 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1753 switch (eventEntry->type) {
1754 case EventEntry::TYPE_MOTION: {
1755 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1756 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1760 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1761 eventType = USER_ACTIVITY_EVENT_TOUCH;
1765 case EventEntry::TYPE_KEY: {
1766 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1767 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1770 eventType = USER_ACTIVITY_EVENT_BUTTON;
1775 CommandEntry* commandEntry = postCommandLocked(
1776 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1777 commandEntry->eventTime = eventEntry->eventTime;
1778 commandEntry->userActivityEventType = eventType;
1781 void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1782 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1783 #if DEBUG_DISPATCH_CYCLE
1784 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1785 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1787 connection->getInputChannelName(), inputTarget->flags,
1788 inputTarget->xOffset, inputTarget->yOffset,
1789 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1792 // Skip this event if the connection status is not normal.
1793 // We don't want to enqueue additional outbound events if the connection is broken.
1794 if (connection->status != Connection::STATUS_NORMAL) {
1795 #if DEBUG_DISPATCH_CYCLE
1796 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
1797 connection->getInputChannelName(), connection->getStatusLabel());
1802 // Split a motion event if needed.
1803 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1804 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1806 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1807 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1808 MotionEntry* splitMotionEntry = splitMotionEvent(
1809 originalMotionEntry, inputTarget->pointerIds);
1810 if (!splitMotionEntry) {
1811 return; // split event was dropped
1814 ALOGD("channel '%s' ~ Split motion event.",
1815 connection->getInputChannelName());
1816 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1818 enqueueDispatchEntriesLocked(currentTime, connection,
1819 splitMotionEntry, inputTarget);
1820 splitMotionEntry->release();
1825 // Not splitting. Enqueue dispatch entries for the event as is.
1826 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1829 void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1830 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1831 bool wasEmpty = connection->outboundQueue.isEmpty();
1833 // Enqueue dispatch entries for the requested modes.
1834 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1835 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1836 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1837 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1838 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1839 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1840 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1841 InputTarget::FLAG_DISPATCH_AS_IS);
1842 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1843 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1844 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1845 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1847 // If the outbound queue was previously empty, start the dispatch cycle going.
1848 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1849 startDispatchCycleLocked(currentTime, connection);
1853 void InputDispatcher::enqueueDispatchEntryLocked(
1854 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1855 int32_t dispatchMode) {
1856 int32_t inputTargetFlags = inputTarget->flags;
1857 if (!(inputTargetFlags & dispatchMode)) {
1860 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1862 // This is a new event.
1863 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1864 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1865 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1866 inputTarget->scaleFactor);
1868 // Apply target flags and update the connection's input state.
1869 switch (eventEntry->type) {
1870 case EventEntry::TYPE_KEY: {
1871 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1872 dispatchEntry->resolvedAction = keyEntry->action;
1873 dispatchEntry->resolvedFlags = keyEntry->flags;
1875 if (!connection->inputState.trackKey(keyEntry,
1876 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1877 #if DEBUG_DISPATCH_CYCLE
1878 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
1879 connection->getInputChannelName());
1881 delete dispatchEntry;
1882 return; // skip the inconsistent event
1887 case EventEntry::TYPE_MOTION: {
1888 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1889 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1890 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1891 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1892 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1893 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1894 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1895 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1896 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1897 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1898 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1900 dispatchEntry->resolvedAction = motionEntry->action;
1902 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1903 && !connection->inputState.isHovering(
1904 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
1905 #if DEBUG_DISPATCH_CYCLE
1906 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
1907 connection->getInputChannelName());
1909 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1912 dispatchEntry->resolvedFlags = motionEntry->flags;
1913 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1914 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1917 if (!connection->inputState.trackMotion(motionEntry,
1918 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1919 #if DEBUG_DISPATCH_CYCLE
1920 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
1921 connection->getInputChannelName());
1923 delete dispatchEntry;
1924 return; // skip the inconsistent event
1930 // Remember that we are waiting for this dispatch to complete.
1931 if (dispatchEntry->hasForegroundTarget()) {
1932 incrementPendingForegroundDispatchesLocked(eventEntry);
1935 // Enqueue the dispatch entry.
1936 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1937 traceOutboundQueueLengthLocked(connection);
1940 void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
1941 const sp<Connection>& connection) {
1942 #if DEBUG_DISPATCH_CYCLE
1943 ALOGD("channel '%s' ~ startDispatchCycle",
1944 connection->getInputChannelName());
1947 while (connection->status == Connection::STATUS_NORMAL
1948 && !connection->outboundQueue.isEmpty()) {
1949 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
1950 dispatchEntry->deliveryTime = currentTime;
1952 // Publish the event.
1954 EventEntry* eventEntry = dispatchEntry->eventEntry;
1955 switch (eventEntry->type) {
1956 case EventEntry::TYPE_KEY: {
1957 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1959 // Publish the key event.
1960 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
1961 keyEntry->deviceId, keyEntry->source,
1962 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1963 keyEntry->keyCode, keyEntry->scanCode,
1964 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1965 keyEntry->eventTime);
1969 case EventEntry::TYPE_MOTION: {
1970 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1972 PointerCoords scaledCoords[MAX_POINTERS];
1973 const PointerCoords* usingCoords = motionEntry->pointerCoords;
1975 // Set the X and Y offset depending on the input source.
1976 float xOffset, yOffset, scaleFactor;
1977 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1978 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1979 scaleFactor = dispatchEntry->scaleFactor;
1980 xOffset = dispatchEntry->xOffset * scaleFactor;
1981 yOffset = dispatchEntry->yOffset * scaleFactor;
1982 if (scaleFactor != 1.0f) {
1983 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1984 scaledCoords[i] = motionEntry->pointerCoords[i];
1985 scaledCoords[i].scale(scaleFactor);
1987 usingCoords = scaledCoords;
1994 // We don't want the dispatch target to know.
1995 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
1996 for (size_t i = 0; i < motionEntry->pointerCount; i++) {
1997 scaledCoords[i].clear();
1999 usingCoords = scaledCoords;
2003 // Publish the motion event.
2004 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
2005 motionEntry->deviceId, motionEntry->source,
2006 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2007 motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
2009 motionEntry->xPrecision, motionEntry->yPrecision,
2010 motionEntry->downTime, motionEntry->eventTime,
2011 motionEntry->pointerCount, motionEntry->pointerProperties,
2021 // Check the result.
2023 if (status == WOULD_BLOCK) {
2024 if (connection->waitQueue.isEmpty()) {
2025 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2026 "This is unexpected because the wait queue is empty, so the pipe "
2027 "should be empty and we shouldn't have any problems writing an "
2028 "event to it, status=%d", connection->getInputChannelName(), status);
2029 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2031 // Pipe is full and we are waiting for the app to finish process some events
2032 // before sending more events to it.
2033 #if DEBUG_DISPATCH_CYCLE
2034 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2035 "waiting for the application to catch up",
2036 connection->getInputChannelName());
2038 connection->inputPublisherBlocked = true;
2041 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2042 "status=%d", connection->getInputChannelName(), status);
2043 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2048 // Re-enqueue the event on the wait queue.
2049 connection->outboundQueue.dequeue(dispatchEntry);
2050 traceOutboundQueueLengthLocked(connection);
2051 connection->waitQueue.enqueueAtTail(dispatchEntry);
2052 traceWaitQueueLengthLocked(connection);
2056 void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2057 const sp<Connection>& connection, uint32_t seq, bool handled) {
2058 #if DEBUG_DISPATCH_CYCLE
2059 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2060 connection->getInputChannelName(), seq, toString(handled));
2063 connection->inputPublisherBlocked = false;
2065 if (connection->status == Connection::STATUS_BROKEN
2066 || connection->status == Connection::STATUS_ZOMBIE) {
2070 // Notify other system components and prepare to start the next dispatch cycle.
2071 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2074 void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2075 const sp<Connection>& connection, bool notify) {
2076 #if DEBUG_DISPATCH_CYCLE
2077 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
2078 connection->getInputChannelName(), toString(notify));
2081 // Clear the dispatch queues.
2082 drainDispatchQueueLocked(&connection->outboundQueue);
2083 traceOutboundQueueLengthLocked(connection);
2084 drainDispatchQueueLocked(&connection->waitQueue);
2085 traceWaitQueueLengthLocked(connection);
2087 // The connection appears to be unrecoverably broken.
2088 // Ignore already broken or zombie connections.
2089 if (connection->status == Connection::STATUS_NORMAL) {
2090 connection->status = Connection::STATUS_BROKEN;
2093 // Notify other system components.
2094 onDispatchCycleBrokenLocked(currentTime, connection);
2099 void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2100 while (!queue->isEmpty()) {
2101 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2102 releaseDispatchEntryLocked(dispatchEntry);
2106 void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2107 if (dispatchEntry->hasForegroundTarget()) {
2108 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2110 delete dispatchEntry;
2113 int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2114 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2117 AutoMutex _l(d->mLock);
2119 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2120 if (connectionIndex < 0) {
2121 ALOGE("Received spurious receive callback for unknown input channel. "
2122 "fd=%d, events=0x%x", fd, events);
2123 return 0; // remove the callback
2127 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2128 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2129 if (!(events & ALOOPER_EVENT_INPUT)) {
2130 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2131 "events=0x%x", connection->getInputChannelName(), events);
2135 nsecs_t currentTime = now();
2136 bool gotOne = false;
2141 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2145 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2149 d->runCommandsLockedInterruptible();
2150 if (status == WOULD_BLOCK) {
2155 notify = status != DEAD_OBJECT || !connection->monitor;
2157 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2158 connection->getInputChannelName(), status);
2161 // Monitor channels are never explicitly unregistered.
2162 // We do it automatically when the remote endpoint is closed so don't warn
2164 notify = !connection->monitor;
2166 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
2167 "events=0x%x", connection->getInputChannelName(), events);
2171 // Unregister the channel.
2172 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2173 return 0; // remove the callback
2177 void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2178 const CancelationOptions& options) {
2179 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2180 synthesizeCancelationEventsForConnectionLocked(
2181 mConnectionsByFd.valueAt(i), options);
2185 void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2186 const sp<InputChannel>& channel, const CancelationOptions& options) {
2187 ssize_t index = getConnectionIndexLocked(channel);
2189 synthesizeCancelationEventsForConnectionLocked(
2190 mConnectionsByFd.valueAt(index), options);
2194 void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2195 const sp<Connection>& connection, const CancelationOptions& options) {
2196 if (connection->status == Connection::STATUS_BROKEN) {
2200 nsecs_t currentTime = now();
2202 Vector<EventEntry*> cancelationEvents;
2203 connection->inputState.synthesizeCancelationEvents(currentTime,
2204 cancelationEvents, options);
2206 if (!cancelationEvents.isEmpty()) {
2207 #if DEBUG_OUTBOUND_EVENT_DETAILS
2208 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
2209 "with reality: %s, mode=%d.",
2210 connection->getInputChannelName(), cancelationEvents.size(),
2211 options.reason, options.mode);
2213 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2214 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2215 switch (cancelationEventEntry->type) {
2216 case EventEntry::TYPE_KEY:
2217 logOutboundKeyDetailsLocked("cancel - ",
2218 static_cast<KeyEntry*>(cancelationEventEntry));
2220 case EventEntry::TYPE_MOTION:
2221 logOutboundMotionDetailsLocked("cancel - ",
2222 static_cast<MotionEntry*>(cancelationEventEntry));
2227 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2228 if (windowHandle != NULL) {
2229 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2230 target.xOffset = -windowInfo->frameLeft;
2231 target.yOffset = -windowInfo->frameTop;
2232 target.scaleFactor = windowInfo->scaleFactor;
2236 target.scaleFactor = 1.0f;
2238 target.inputChannel = connection->inputChannel;
2239 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2241 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2242 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2244 cancelationEventEntry->release();
2247 startDispatchCycleLocked(currentTime, connection);
2251 InputDispatcher::MotionEntry*
2252 InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2253 ALOG_ASSERT(pointerIds.value != 0);
2255 uint32_t splitPointerIndexMap[MAX_POINTERS];
2256 PointerProperties splitPointerProperties[MAX_POINTERS];
2257 PointerCoords splitPointerCoords[MAX_POINTERS];
2259 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2260 uint32_t splitPointerCount = 0;
2262 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2263 originalPointerIndex++) {
2264 const PointerProperties& pointerProperties =
2265 originalMotionEntry->pointerProperties[originalPointerIndex];
2266 uint32_t pointerId = uint32_t(pointerProperties.id);
2267 if (pointerIds.hasBit(pointerId)) {
2268 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2269 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2270 splitPointerCoords[splitPointerCount].copyFrom(
2271 originalMotionEntry->pointerCoords[originalPointerIndex]);
2272 splitPointerCount += 1;
2276 if (splitPointerCount != pointerIds.count()) {
2277 // This is bad. We are missing some of the pointers that we expected to deliver.
2278 // Most likely this indicates that we received an ACTION_MOVE events that has
2279 // different pointer ids than we expected based on the previous ACTION_DOWN
2280 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2282 ALOGW("Dropping split motion event because the pointer count is %d but "
2283 "we expected there to be %d pointers. This probably means we received "
2284 "a broken sequence of pointer ids from the input device.",
2285 splitPointerCount, pointerIds.count());
2289 int32_t action = originalMotionEntry->action;
2290 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2291 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2292 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2293 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2294 const PointerProperties& pointerProperties =
2295 originalMotionEntry->pointerProperties[originalPointerIndex];
2296 uint32_t pointerId = uint32_t(pointerProperties.id);
2297 if (pointerIds.hasBit(pointerId)) {
2298 if (pointerIds.count() == 1) {
2299 // The first/last pointer went down/up.
2300 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2301 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2303 // A secondary pointer went down/up.
2304 uint32_t splitPointerIndex = 0;
2305 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2306 splitPointerIndex += 1;
2308 action = maskedAction | (splitPointerIndex
2309 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2312 // An unrelated pointer changed.
2313 action = AMOTION_EVENT_ACTION_MOVE;
2317 MotionEntry* splitMotionEntry = new MotionEntry(
2318 originalMotionEntry->eventTime,
2319 originalMotionEntry->deviceId,
2320 originalMotionEntry->source,
2321 originalMotionEntry->policyFlags,
2323 originalMotionEntry->flags,
2324 originalMotionEntry->metaState,
2325 originalMotionEntry->buttonState,
2326 originalMotionEntry->edgeFlags,
2327 originalMotionEntry->xPrecision,
2328 originalMotionEntry->yPrecision,
2329 originalMotionEntry->downTime,
2330 originalMotionEntry->displayId,
2331 splitPointerCount, splitPointerProperties, splitPointerCoords);
2333 if (originalMotionEntry->injectionState) {
2334 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2335 splitMotionEntry->injectionState->refCount += 1;
2338 return splitMotionEntry;
2341 void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2342 #if DEBUG_INBOUND_EVENT_DETAILS
2343 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
2348 AutoMutex _l(mLock);
2350 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2351 needWake = enqueueInboundEventLocked(newEntry);
2359 void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2360 #if DEBUG_INBOUND_EVENT_DETAILS
2361 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
2362 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
2363 args->eventTime, args->deviceId, args->source, args->policyFlags,
2364 args->action, args->flags, args->keyCode, args->scanCode,
2365 args->metaState, args->downTime);
2367 if (!validateKeyEvent(args->action)) {
2371 uint32_t policyFlags = args->policyFlags;
2372 int32_t flags = args->flags;
2373 int32_t metaState = args->metaState;
2374 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2375 policyFlags |= POLICY_FLAG_VIRTUAL;
2376 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2378 if (policyFlags & POLICY_FLAG_ALT) {
2379 metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2381 if (policyFlags & POLICY_FLAG_ALT_GR) {
2382 metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2384 if (policyFlags & POLICY_FLAG_SHIFT) {
2385 metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2387 if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2388 metaState |= AMETA_CAPS_LOCK_ON;
2390 if (policyFlags & POLICY_FLAG_FUNCTION) {
2391 metaState |= AMETA_FUNCTION_ON;
2394 policyFlags |= POLICY_FLAG_TRUSTED;
2397 event.initialize(args->deviceId, args->source, args->action,
2398 flags, args->keyCode, args->scanCode, metaState, 0,
2399 args->downTime, args->eventTime);
2401 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2403 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2404 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2411 if (shouldSendKeyToInputFilterLocked(args)) {
2414 policyFlags |= POLICY_FLAG_FILTERED;
2415 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2416 return; // event was consumed by the filter
2422 int32_t repeatCount = 0;
2423 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2424 args->deviceId, args->source, policyFlags,
2425 args->action, flags, args->keyCode, args->scanCode,
2426 metaState, repeatCount, args->downTime);
2428 needWake = enqueueInboundEventLocked(newEntry);
2437 bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2438 return mInputFilterEnabled;
2441 void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2442 #if DEBUG_INBOUND_EVENT_DETAILS
2443 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
2444 "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
2445 "xPrecision=%f, yPrecision=%f, downTime=%lld",
2446 args->eventTime, args->deviceId, args->source, args->policyFlags,
2447 args->action, args->flags, args->metaState, args->buttonState,
2448 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2449 for (uint32_t i = 0; i < args->pointerCount; i++) {
2450 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2451 "x=%f, y=%f, pressure=%f, size=%f, "
2452 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2454 i, args->pointerProperties[i].id,
2455 args->pointerProperties[i].toolType,
2456 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2457 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2458 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2459 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2460 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2461 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2462 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2463 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2464 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2467 if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
2471 uint32_t policyFlags = args->policyFlags;
2472 policyFlags |= POLICY_FLAG_TRUSTED;
2473 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
2479 if (shouldSendMotionToInputFilterLocked(args)) {
2483 event.initialize(args->deviceId, args->source, args->action, args->flags,
2484 args->edgeFlags, args->metaState, args->buttonState, 0, 0,
2485 args->xPrecision, args->yPrecision,
2486 args->downTime, args->eventTime,
2487 args->pointerCount, args->pointerProperties, args->pointerCoords);
2489 policyFlags |= POLICY_FLAG_FILTERED;
2490 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2491 return; // event was consumed by the filter
2497 // Just enqueue a new motion event.
2498 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2499 args->deviceId, args->source, policyFlags,
2500 args->action, args->flags, args->metaState, args->buttonState,
2501 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2503 args->pointerCount, args->pointerProperties, args->pointerCoords);
2505 needWake = enqueueInboundEventLocked(newEntry);
2514 bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2515 // TODO: support sending secondary display events to input filter
2516 return mInputFilterEnabled && isMainDisplay(args->displayId);
2519 void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2520 #if DEBUG_INBOUND_EVENT_DETAILS
2521 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x",
2522 args->eventTime, args->policyFlags,
2523 args->switchValues, args->switchMask);
2526 uint32_t policyFlags = args->policyFlags;
2527 policyFlags |= POLICY_FLAG_TRUSTED;
2528 mPolicy->notifySwitch(args->eventTime,
2529 args->switchValues, args->switchMask, policyFlags);
2532 void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2533 #if DEBUG_INBOUND_EVENT_DETAILS
2534 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
2535 args->eventTime, args->deviceId);
2540 AutoMutex _l(mLock);
2542 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2543 needWake = enqueueInboundEventLocked(newEntry);
2551 int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
2552 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2553 uint32_t policyFlags) {
2554 #if DEBUG_INBOUND_EVENT_DETAILS
2555 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
2556 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2557 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
2560 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2562 policyFlags |= POLICY_FLAG_INJECTED;
2563 if (hasInjectionPermission(injectorPid, injectorUid)) {
2564 policyFlags |= POLICY_FLAG_TRUSTED;
2567 EventEntry* firstInjectedEntry;
2568 EventEntry* lastInjectedEntry;
2569 switch (event->getType()) {
2570 case AINPUT_EVENT_TYPE_KEY: {
2571 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2572 int32_t action = keyEvent->getAction();
2573 if (! validateKeyEvent(action)) {
2574 return INPUT_EVENT_INJECTION_FAILED;
2577 int32_t flags = keyEvent->getFlags();
2578 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2579 policyFlags |= POLICY_FLAG_VIRTUAL;
2582 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2583 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2586 if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2587 flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2591 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
2592 keyEvent->getDeviceId(), keyEvent->getSource(),
2593 policyFlags, action, flags,
2594 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
2595 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2596 lastInjectedEntry = firstInjectedEntry;
2600 case AINPUT_EVENT_TYPE_MOTION: {
2601 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
2602 int32_t displayId = ADISPLAY_ID_DEFAULT;
2603 int32_t action = motionEvent->getAction();
2604 size_t pointerCount = motionEvent->getPointerCount();
2605 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
2606 if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
2607 return INPUT_EVENT_INJECTION_FAILED;
2610 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2611 nsecs_t eventTime = motionEvent->getEventTime();
2612 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2616 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2617 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2618 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
2619 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2620 action, motionEvent->getFlags(),
2621 motionEvent->getMetaState(), motionEvent->getButtonState(),
2622 motionEvent->getEdgeFlags(),
2623 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2624 motionEvent->getDownTime(), displayId,
2625 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
2626 lastInjectedEntry = firstInjectedEntry;
2627 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2628 sampleEventTimes += 1;
2629 samplePointerCoords += pointerCount;
2630 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2631 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
2632 action, motionEvent->getFlags(),
2633 motionEvent->getMetaState(), motionEvent->getButtonState(),
2634 motionEvent->getEdgeFlags(),
2635 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2636 motionEvent->getDownTime(), displayId,
2637 uint32_t(pointerCount), pointerProperties, samplePointerCoords);
2638 lastInjectedEntry->next = nextInjectedEntry;
2639 lastInjectedEntry = nextInjectedEntry;
2645 ALOGW("Cannot inject event of type %d", event->getType());
2646 return INPUT_EVENT_INJECTION_FAILED;
2649 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2650 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2651 injectionState->injectionIsAsync = true;
2654 injectionState->refCount += 1;
2655 lastInjectedEntry->injectionState = injectionState;
2657 bool needWake = false;
2658 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2659 EventEntry* nextEntry = entry->next;
2660 needWake |= enqueueInboundEventLocked(entry);
2670 int32_t injectionResult;
2672 AutoMutex _l(mLock);
2674 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2675 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2678 injectionResult = injectionState->injectionResult;
2679 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2683 nsecs_t remainingTimeout = endTime - now();
2684 if (remainingTimeout <= 0) {
2686 ALOGD("injectInputEvent - Timed out waiting for injection result "
2687 "to become available.");
2689 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2693 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2696 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2697 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2698 while (injectionState->pendingForegroundDispatches != 0) {
2700 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2701 injectionState->pendingForegroundDispatches);
2703 nsecs_t remainingTimeout = endTime - now();
2704 if (remainingTimeout <= 0) {
2706 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2707 "dispatches to finish.");
2709 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2713 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2718 injectionState->release();
2722 ALOGD("injectInputEvent - Finished with result %d. "
2723 "injectorPid=%d, injectorUid=%d",
2724 injectionResult, injectorPid, injectorUid);
2727 return injectionResult;
2730 bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2731 return injectorUid == 0
2732 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2735 void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2736 InjectionState* injectionState = entry->injectionState;
2737 if (injectionState) {
2739 ALOGD("Setting input event injection result to %d. "
2740 "injectorPid=%d, injectorUid=%d",
2741 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2744 if (injectionState->injectionIsAsync
2745 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2746 // Log the outcome since the injector did not wait for the injection result.
2747 switch (injectionResult) {
2748 case INPUT_EVENT_INJECTION_SUCCEEDED:
2749 ALOGV("Asynchronous input event injection succeeded.");
2751 case INPUT_EVENT_INJECTION_FAILED:
2752 ALOGW("Asynchronous input event injection failed.");
2754 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2755 ALOGW("Asynchronous input event injection permission denied.");
2757 case INPUT_EVENT_INJECTION_TIMED_OUT:
2758 ALOGW("Asynchronous input event injection timed out.");
2763 injectionState->injectionResult = injectionResult;
2764 mInjectionResultAvailableCondition.broadcast();
2768 void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2769 InjectionState* injectionState = entry->injectionState;
2770 if (injectionState) {
2771 injectionState->pendingForegroundDispatches += 1;
2775 void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2776 InjectionState* injectionState = entry->injectionState;
2777 if (injectionState) {
2778 injectionState->pendingForegroundDispatches -= 1;
2780 if (injectionState->pendingForegroundDispatches == 0) {
2781 mInjectionSyncFinishedCondition.broadcast();
2786 sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2787 const sp<InputChannel>& inputChannel) const {
2788 size_t numWindows = mWindowHandles.size();
2789 for (size_t i = 0; i < numWindows; i++) {
2790 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2791 if (windowHandle->getInputChannel() == inputChannel) {
2792 return windowHandle;
2798 bool InputDispatcher::hasWindowHandleLocked(
2799 const sp<InputWindowHandle>& windowHandle) const {
2800 size_t numWindows = mWindowHandles.size();
2801 for (size_t i = 0; i < numWindows; i++) {
2802 if (mWindowHandles.itemAt(i) == windowHandle) {
2809 void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
2811 ALOGD("setInputWindows");
2814 AutoMutex _l(mLock);
2816 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
2817 mWindowHandles = inputWindowHandles;
2819 sp<InputWindowHandle> newFocusedWindowHandle;
2820 bool foundHoveredWindow = false;
2821 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2822 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2823 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
2824 mWindowHandles.removeAt(i--);
2827 if (windowHandle->getInfo()->hasFocus) {
2828 newFocusedWindowHandle = windowHandle;
2830 if (windowHandle == mLastHoverWindowHandle) {
2831 foundHoveredWindow = true;
2835 if (!foundHoveredWindow) {
2836 mLastHoverWindowHandle = NULL;
2839 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2840 if (mFocusedWindowHandle != NULL) {
2842 ALOGD("Focus left window: %s",
2843 mFocusedWindowHandle->getName().string());
2845 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2846 if (focusedInputChannel != NULL) {
2847 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2848 "focus left window");
2849 synthesizeCancelationEventsForInputChannelLocked(
2850 focusedInputChannel, options);
2853 if (newFocusedWindowHandle != NULL) {
2855 ALOGD("Focus entered window: %s",
2856 newFocusedWindowHandle->getName().string());
2859 mFocusedWindowHandle = newFocusedWindowHandle;
2862 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2863 TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2864 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
2866 ALOGD("Touched window was removed: %s",
2867 touchedWindow.windowHandle->getName().string());
2869 sp<InputChannel> touchedInputChannel =
2870 touchedWindow.windowHandle->getInputChannel();
2871 if (touchedInputChannel != NULL) {
2872 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2873 "touched window was removed");
2874 synthesizeCancelationEventsForInputChannelLocked(
2875 touchedInputChannel, options);
2877 mTouchState.windows.removeAt(i--);
2881 // Release information for windows that are no longer present.
2882 // This ensures that unused input channels are released promptly.
2883 // Otherwise, they might stick around until the window handle is destroyed
2884 // which might not happen until the next GC.
2885 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2886 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2887 if (!hasWindowHandleLocked(oldWindowHandle)) {
2889 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
2891 oldWindowHandle->releaseInfo();
2896 // Wake up poll loop since it may need to make new input dispatching choices.
2900 void InputDispatcher::setFocusedApplication(
2901 const sp<InputApplicationHandle>& inputApplicationHandle) {
2903 ALOGD("setFocusedApplication");
2906 AutoMutex _l(mLock);
2908 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
2909 if (mFocusedApplicationHandle != inputApplicationHandle) {
2910 if (mFocusedApplicationHandle != NULL) {
2911 resetANRTimeoutsLocked();
2912 mFocusedApplicationHandle->releaseInfo();
2914 mFocusedApplicationHandle = inputApplicationHandle;
2916 } else if (mFocusedApplicationHandle != NULL) {
2917 resetANRTimeoutsLocked();
2918 mFocusedApplicationHandle->releaseInfo();
2919 mFocusedApplicationHandle.clear();
2923 //logDispatchStateLocked();
2927 // Wake up poll loop since it may need to make new input dispatching choices.
2931 void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2933 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2938 AutoMutex _l(mLock);
2940 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
2941 if (mDispatchFrozen && !frozen) {
2942 resetANRTimeoutsLocked();
2945 if (mDispatchEnabled && !enabled) {
2946 resetAndDropEverythingLocked("dispatcher is being disabled");
2949 mDispatchEnabled = enabled;
2950 mDispatchFrozen = frozen;
2957 //logDispatchStateLocked();
2962 // Wake up poll loop since it may need to make new input dispatching choices.
2967 void InputDispatcher::setInputFilterEnabled(bool enabled) {
2969 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
2973 AutoMutex _l(mLock);
2975 if (mInputFilterEnabled == enabled) {
2979 mInputFilterEnabled = enabled;
2980 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2983 // Wake up poll loop since there might be work to do to drop everything.
2987 bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2988 const sp<InputChannel>& toChannel) {
2990 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
2991 fromChannel->getName().string(), toChannel->getName().string());
2994 AutoMutex _l(mLock);
2996 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2997 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2998 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
3000 ALOGD("Cannot transfer focus because from or to window not found.");
3004 if (fromWindowHandle == toWindowHandle) {
3006 ALOGD("Trivial transfer to same window.");
3010 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3012 ALOGD("Cannot transfer focus because windows are on different displays.");
3018 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3019 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3020 if (touchedWindow.windowHandle == fromWindowHandle) {
3021 int32_t oldTargetFlags = touchedWindow.targetFlags;
3022 BitSet32 pointerIds = touchedWindow.pointerIds;
3024 mTouchState.windows.removeAt(i);
3026 int32_t newTargetFlags = oldTargetFlags
3027 & (InputTarget::FLAG_FOREGROUND
3028 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3029 mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
3038 ALOGD("Focus transfer failed because from window did not have focus.");
3043 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3044 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3045 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3046 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3047 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3049 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3050 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3051 "transferring touch focus from this window to another window");
3052 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3056 logDispatchStateLocked();
3060 // Wake up poll loop since it may need to make new input dispatching choices.
3065 void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3067 ALOGD("Resetting and dropping all events (%s).", reason);
3070 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3071 synthesizeCancelationEventsForAllConnectionsLocked(options);
3073 resetKeyRepeatLocked();
3074 releasePendingEventLocked();
3075 drainInboundQueueLocked();
3076 resetANRTimeoutsLocked();
3078 mTouchState.reset();
3079 mLastHoverWindowHandle.clear();
3082 void InputDispatcher::logDispatchStateLocked() {
3084 dumpDispatchStateLocked(dump);
3086 char* text = dump.lockBuffer(dump.size());
3088 while (*start != '\0') {
3089 char* end = strchr(start, '\n');
3098 void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
3099 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3100 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
3102 if (mFocusedApplicationHandle != NULL) {
3103 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
3104 mFocusedApplicationHandle->getName().string(),
3105 mFocusedApplicationHandle->getDispatchingTimeout(
3106 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3108 dump.append(INDENT "FocusedApplication: <null>\n");
3110 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
3111 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
3113 dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
3114 dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
3115 dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
3116 dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
3117 dump.appendFormat(INDENT "TouchDisplayId: %d\n", mTouchState.displayId);
3118 if (!mTouchState.windows.isEmpty()) {
3119 dump.append(INDENT "TouchedWindows:\n");
3120 for (size_t i = 0; i < mTouchState.windows.size(); i++) {
3121 const TouchedWindow& touchedWindow = mTouchState.windows[i];
3122 dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3123 i, touchedWindow.windowHandle->getName().string(),
3124 touchedWindow.pointerIds.value,
3125 touchedWindow.targetFlags);
3128 dump.append(INDENT "TouchedWindows: <none>\n");
3131 if (!mWindowHandles.isEmpty()) {
3132 dump.append(INDENT "Windows:\n");
3133 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3134 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3135 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3137 dump.appendFormat(INDENT2 "%d: name='%s', displayId=%d, "
3138 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3139 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3140 "frame=[%d,%d][%d,%d], scale=%f, "
3142 i, windowInfo->name.string(), windowInfo->displayId,
3143 toString(windowInfo->paused),
3144 toString(windowInfo->hasFocus),
3145 toString(windowInfo->hasWallpaper),
3146 toString(windowInfo->visible),
3147 toString(windowInfo->canReceiveKeys),
3148 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3150 windowInfo->frameLeft, windowInfo->frameTop,
3151 windowInfo->frameRight, windowInfo->frameBottom,
3152 windowInfo->scaleFactor);
3153 dumpRegion(dump, windowInfo->touchableRegion);
3154 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3155 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3156 windowInfo->ownerPid, windowInfo->ownerUid,
3157 windowInfo->dispatchingTimeout / 1000000.0);
3160 dump.append(INDENT "Windows: <none>\n");
3163 if (!mMonitoringChannels.isEmpty()) {
3164 dump.append(INDENT "MonitoringChannels:\n");
3165 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3166 const sp<InputChannel>& channel = mMonitoringChannels[i];
3167 dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
3170 dump.append(INDENT "MonitoringChannels: <none>\n");
3173 nsecs_t currentTime = now();
3175 // Dump recently dispatched or dropped events from oldest to newest.
3176 if (!mRecentQueue.isEmpty()) {
3177 dump.appendFormat(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
3178 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
3179 dump.append(INDENT2);
3180 entry->appendDescription(dump);
3181 dump.appendFormat(", age=%0.1fms\n",
3182 (currentTime - entry->eventTime) * 0.000001f);
3185 dump.append(INDENT "RecentQueue: <empty>\n");
3188 // Dump event currently being dispatched.
3189 if (mPendingEvent) {
3190 dump.append(INDENT "PendingEvent:\n");
3191 dump.append(INDENT2);
3192 mPendingEvent->appendDescription(dump);
3193 dump.appendFormat(", age=%0.1fms\n",
3194 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3196 dump.append(INDENT "PendingEvent: <none>\n");
3199 // Dump inbound events from oldest to newest.
3200 if (!mInboundQueue.isEmpty()) {
3201 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3202 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3203 dump.append(INDENT2);
3204 entry->appendDescription(dump);
3205 dump.appendFormat(", age=%0.1fms\n",
3206 (currentTime - entry->eventTime) * 0.000001f);
3209 dump.append(INDENT "InboundQueue: <empty>\n");
3212 if (!mConnectionsByFd.isEmpty()) {
3213 dump.append(INDENT "Connections:\n");
3214 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3215 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
3216 dump.appendFormat(INDENT2 "%d: channelName='%s', windowName='%s', "
3217 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3218 i, connection->getInputChannelName(), connection->getWindowName(),
3219 connection->getStatusLabel(), toString(connection->monitor),
3220 toString(connection->inputPublisherBlocked));
3222 if (!connection->outboundQueue.isEmpty()) {
3223 dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
3224 connection->outboundQueue.count());
3225 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3226 entry = entry->next) {
3227 dump.append(INDENT4);
3228 entry->eventEntry->appendDescription(dump);
3229 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
3230 entry->targetFlags, entry->resolvedAction,
3231 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3234 dump.append(INDENT3 "OutboundQueue: <empty>\n");
3237 if (!connection->waitQueue.isEmpty()) {
3238 dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
3239 connection->waitQueue.count());
3240 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3241 entry = entry->next) {
3242 dump.append(INDENT4);
3243 entry->eventEntry->appendDescription(dump);
3244 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
3245 "age=%0.1fms, wait=%0.1fms\n",
3246 entry->targetFlags, entry->resolvedAction,
3247 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3248 (currentTime - entry->deliveryTime) * 0.000001f);
3251 dump.append(INDENT3 "WaitQueue: <empty>\n");
3255 dump.append(INDENT "Connections: <none>\n");
3258 if (isAppSwitchPendingLocked()) {
3259 dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
3260 (mAppSwitchDueTime - now()) / 1000000.0);
3262 dump.append(INDENT "AppSwitch: not pending\n");
3265 dump.append(INDENT "Configuration:\n");
3266 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
3267 mConfig.keyRepeatDelay * 0.000001f);
3268 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3269 mConfig.keyRepeatTimeout * 0.000001f);
3272 status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3273 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
3274 #if DEBUG_REGISTRATION
3275 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3280 AutoMutex _l(mLock);
3282 if (getConnectionIndexLocked(inputChannel) >= 0) {
3283 ALOGW("Attempted to register already registered input channel '%s'",
3284 inputChannel->getName().string());
3288 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3290 int fd = inputChannel->getFd();
3291 mConnectionsByFd.add(fd, connection);
3294 mMonitoringChannels.push(inputChannel);
3297 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3300 // Wake the looper because some connections have changed.
3305 status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3306 #if DEBUG_REGISTRATION
3307 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
3311 AutoMutex _l(mLock);
3313 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3319 // Wake the poll loop because removing the connection may have changed the current
3320 // synchronization state.
3325 status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3327 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3328 if (connectionIndex < 0) {
3329 ALOGW("Attempted to unregister already unregistered input channel '%s'",
3330 inputChannel->getName().string());
3334 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3335 mConnectionsByFd.removeItemsAt(connectionIndex);
3337 if (connection->monitor) {
3338 removeMonitorChannelLocked(inputChannel);
3341 mLooper->removeFd(inputChannel->getFd());
3343 nsecs_t currentTime = now();
3344 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3346 connection->status = Connection::STATUS_ZOMBIE;
3350 void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3351 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3352 if (mMonitoringChannels[i] == inputChannel) {
3353 mMonitoringChannels.removeAt(i);
3359 ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
3360 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3361 if (connectionIndex >= 0) {
3362 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3363 if (connection->inputChannel.get() == inputChannel.get()) {
3364 return connectionIndex;
3371 void InputDispatcher::onDispatchCycleFinishedLocked(
3372 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3373 CommandEntry* commandEntry = postCommandLocked(
3374 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3375 commandEntry->connection = connection;
3376 commandEntry->eventTime = currentTime;
3377 commandEntry->seq = seq;
3378 commandEntry->handled = handled;
3381 void InputDispatcher::onDispatchCycleBrokenLocked(
3382 nsecs_t currentTime, const sp<Connection>& connection) {
3383 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3384 connection->getInputChannelName());
3386 CommandEntry* commandEntry = postCommandLocked(
3387 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3388 commandEntry->connection = connection;
3391 void InputDispatcher::onANRLocked(
3392 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3393 const sp<InputWindowHandle>& windowHandle,
3394 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3395 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3396 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3397 ALOGI("Application is not responding: %s. "
3398 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
3399 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
3400 dispatchLatency, waitDuration, reason);
3402 // Capture a record of the InputDispatcher state at the time of the ANR.
3403 time_t t = time(NULL);
3405 localtime_r(&t, &tm);
3407 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3408 mLastANRState.clear();
3409 mLastANRState.append(INDENT "ANR:\n");
3410 mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
3411 mLastANRState.appendFormat(INDENT2 "Window: %s\n",
3412 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
3413 mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3414 mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3415 mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
3416 dumpDispatchStateLocked(mLastANRState);
3418 CommandEntry* commandEntry = postCommandLocked(
3419 & InputDispatcher::doNotifyANRLockedInterruptible);
3420 commandEntry->inputApplicationHandle = applicationHandle;
3421 commandEntry->inputWindowHandle = windowHandle;
3424 void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3425 CommandEntry* commandEntry) {
3428 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3433 void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3434 CommandEntry* commandEntry) {
3435 sp<Connection> connection = commandEntry->connection;
3437 if (connection->status != Connection::STATUS_ZOMBIE) {
3440 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3446 void InputDispatcher::doNotifyANRLockedInterruptible(
3447 CommandEntry* commandEntry) {
3450 nsecs_t newTimeout = mPolicy->notifyANR(
3451 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
3455 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3456 commandEntry->inputWindowHandle != NULL
3457 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
3460 void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3461 CommandEntry* commandEntry) {
3462 KeyEntry* entry = commandEntry->keyEntry;
3465 initializeKeyEvent(&event, entry);
3469 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3470 &event, entry->policyFlags);
3475 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3476 } else if (!delay) {
3477 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3479 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3480 entry->interceptKeyWakeupTime = now() + delay;
3485 void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3486 CommandEntry* commandEntry) {
3487 sp<Connection> connection = commandEntry->connection;
3488 nsecs_t finishTime = commandEntry->eventTime;
3489 uint32_t seq = commandEntry->seq;
3490 bool handled = commandEntry->handled;
3492 // Handle post-event policy actions.
3493 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3494 if (dispatchEntry) {
3495 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3496 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
3498 msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
3499 connection->getWindowName(), eventDuration * 0.000001f);
3500 dispatchEntry->eventEntry->appendDescription(msg);
3501 ALOGI("%s", msg.string());
3505 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3506 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3507 restartEvent = afterKeyEventLockedInterruptible(connection,
3508 dispatchEntry, keyEntry, handled);
3509 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3510 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3511 restartEvent = afterMotionEventLockedInterruptible(connection,
3512 dispatchEntry, motionEntry, handled);
3514 restartEvent = false;
3517 // Dequeue the event and start the next cycle.
3518 // Note that because the lock might have been released, it is possible that the
3519 // contents of the wait queue to have been drained, so we need to double-check
3521 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3522 connection->waitQueue.dequeue(dispatchEntry);
3523 traceWaitQueueLengthLocked(connection);
3524 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3525 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3526 traceOutboundQueueLengthLocked(connection);
3528 releaseDispatchEntryLocked(dispatchEntry);
3532 // Start the next dispatch cycle for this connection.
3533 startDispatchCycleLocked(now(), connection);
3537 bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3538 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3539 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3540 // Get the fallback key state.
3541 // Clear it out after dispatching the UP.
3542 int32_t originalKeyCode = keyEntry->keyCode;
3543 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3544 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3545 connection->inputState.removeFallbackKey(originalKeyCode);
3548 if (handled || !dispatchEntry->hasForegroundTarget()) {
3549 // If the application handles the original key for which we previously
3550 // generated a fallback or if the window is not a foreground window,
3551 // then cancel the associated fallback key, if any.
3552 if (fallbackKeyCode != -1) {
3553 // Dispatch the unhandled key to the policy with the cancel flag.
3554 #if DEBUG_OUTBOUND_EVENT_DETAILS
3555 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3556 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3557 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3558 keyEntry->policyFlags);
3561 initializeKeyEvent(&event, keyEntry);
3562 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3566 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3567 &event, keyEntry->policyFlags, &event);
3571 // Cancel the fallback key.
3572 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3573 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3574 "application handled the original non-fallback key "
3575 "or is no longer a foreground target, "
3576 "canceling previously dispatched fallback key");
3577 options.keyCode = fallbackKeyCode;
3578 synthesizeCancelationEventsForConnectionLocked(connection, options);
3580 connection->inputState.removeFallbackKey(originalKeyCode);
3583 // If the application did not handle a non-fallback key, first check
3584 // that we are in a good state to perform unhandled key event processing
3585 // Then ask the policy what to do with it.
3586 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3587 && keyEntry->repeatCount == 0;
3588 if (fallbackKeyCode == -1 && !initialDown) {
3589 #if DEBUG_OUTBOUND_EVENT_DETAILS
3590 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3591 "since this is not an initial down. "
3592 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3593 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3594 keyEntry->policyFlags);
3599 // Dispatch the unhandled key to the policy.
3600 #if DEBUG_OUTBOUND_EVENT_DETAILS
3601 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
3602 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3603 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3604 keyEntry->policyFlags);
3607 initializeKeyEvent(&event, keyEntry);
3611 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3612 &event, keyEntry->policyFlags, &event);
3616 if (connection->status != Connection::STATUS_NORMAL) {
3617 connection->inputState.removeFallbackKey(originalKeyCode);
3621 // Latch the fallback keycode for this key on an initial down.
3622 // The fallback keycode cannot change at any other point in the lifecycle.
3625 fallbackKeyCode = event.getKeyCode();
3627 fallbackKeyCode = AKEYCODE_UNKNOWN;
3629 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3632 ALOG_ASSERT(fallbackKeyCode != -1);
3634 // Cancel the fallback key if the policy decides not to send it anymore.
3635 // We will continue to dispatch the key to the policy but we will no
3636 // longer dispatch a fallback key to the application.
3637 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3638 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3639 #if DEBUG_OUTBOUND_EVENT_DETAILS
3641 ALOGD("Unhandled key event: Policy requested to send key %d"
3642 "as a fallback for %d, but on the DOWN it had requested "
3643 "to send %d instead. Fallback canceled.",
3644 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3646 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
3647 "but on the DOWN it had requested to send %d. "
3648 "Fallback canceled.",
3649 originalKeyCode, fallbackKeyCode);
3653 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3654 "canceling fallback, policy no longer desires it");
3655 options.keyCode = fallbackKeyCode;
3656 synthesizeCancelationEventsForConnectionLocked(connection, options);
3659 fallbackKeyCode = AKEYCODE_UNKNOWN;
3660 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3661 connection->inputState.setFallbackKey(originalKeyCode,
3666 #if DEBUG_OUTBOUND_EVENT_DETAILS
3669 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3670 connection->inputState.getFallbackKeys();
3671 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3672 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3673 fallbackKeys.valueAt(i));
3675 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3676 fallbackKeys.size(), msg.string());
3681 // Restart the dispatch cycle using the fallback key.
3682 keyEntry->eventTime = event.getEventTime();
3683 keyEntry->deviceId = event.getDeviceId();
3684 keyEntry->source = event.getSource();
3685 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3686 keyEntry->keyCode = fallbackKeyCode;
3687 keyEntry->scanCode = event.getScanCode();
3688 keyEntry->metaState = event.getMetaState();
3689 keyEntry->repeatCount = event.getRepeatCount();
3690 keyEntry->downTime = event.getDownTime();
3691 keyEntry->syntheticRepeat = false;
3693 #if DEBUG_OUTBOUND_EVENT_DETAILS
3694 ALOGD("Unhandled key event: Dispatching fallback key. "
3695 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3696 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3698 return true; // restart the event
3700 #if DEBUG_OUTBOUND_EVENT_DETAILS
3701 ALOGD("Unhandled key event: No fallback key.");
3709 bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3710 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3714 void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3717 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
3722 void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3723 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3724 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3725 entry->downTime, entry->eventTime);
3728 void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3729 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3730 // TODO Write some statistics about how long we spend waiting.
3733 void InputDispatcher::traceInboundQueueLengthLocked() {
3734 if (ATRACE_ENABLED()) {
3735 ATRACE_INT("iq", mInboundQueue.count());
3739 void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3740 if (ATRACE_ENABLED()) {
3741 char counterName[40];
3742 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3743 ATRACE_INT(counterName, connection->outboundQueue.count());
3747 void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3748 if (ATRACE_ENABLED()) {
3749 char counterName[40];
3750 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3751 ATRACE_INT(counterName, connection->waitQueue.count());
3755 void InputDispatcher::dump(String8& dump) {
3756 AutoMutex _l(mLock);
3758 dump.append("Input Dispatcher State:\n");
3759 dumpDispatchStateLocked(dump);
3761 if (!mLastANRState.isEmpty()) {
3762 dump.append("\nInput Dispatcher State at time of last ANR:\n");
3763 dump.append(mLastANRState);
3767 void InputDispatcher::monitor() {
3768 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3771 mDispatcherIsAliveCondition.wait(mLock);
3776 // --- InputDispatcher::Queue ---
3778 template <typename T>
3779 uint32_t InputDispatcher::Queue<T>::count() const {
3780 uint32_t result = 0;
3781 for (const T* entry = head; entry; entry = entry->next) {
3788 // --- InputDispatcher::InjectionState ---
3790 InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3792 injectorPid(injectorPid), injectorUid(injectorUid),
3793 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3794 pendingForegroundDispatches(0) {
3797 InputDispatcher::InjectionState::~InjectionState() {
3800 void InputDispatcher::InjectionState::release() {
3802 if (refCount == 0) {
3805 ALOG_ASSERT(refCount > 0);
3810 // --- InputDispatcher::EventEntry ---
3812 InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3813 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3814 injectionState(NULL), dispatchInProgress(false) {
3817 InputDispatcher::EventEntry::~EventEntry() {
3818 releaseInjectionState();
3821 void InputDispatcher::EventEntry::release() {
3823 if (refCount == 0) {
3826 ALOG_ASSERT(refCount > 0);
3830 void InputDispatcher::EventEntry::releaseInjectionState() {
3831 if (injectionState) {
3832 injectionState->release();
3833 injectionState = NULL;
3838 // --- InputDispatcher::ConfigurationChangedEntry ---
3840 InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3841 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3844 InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3847 void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
3848 msg.append("ConfigurationChangedEvent(), policyFlags=0x%08x",
3853 // --- InputDispatcher::DeviceResetEntry ---
3855 InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3856 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3857 deviceId(deviceId) {
3860 InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3863 void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
3864 msg.appendFormat("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
3865 deviceId, policyFlags);
3869 // --- InputDispatcher::KeyEntry ---
3871 InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
3872 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
3873 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3874 int32_t repeatCount, nsecs_t downTime) :
3875 EventEntry(TYPE_KEY, eventTime, policyFlags),
3876 deviceId(deviceId), source(source), action(action), flags(flags),
3877 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3878 repeatCount(repeatCount), downTime(downTime),
3879 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3880 interceptKeyWakeupTime(0) {
3883 InputDispatcher::KeyEntry::~KeyEntry() {
3886 void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
3887 msg.appendFormat("KeyEvent(deviceId=%d, source=0x%08x, action=%d, "
3888 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
3889 "repeatCount=%d), policyFlags=0x%08x",
3890 deviceId, source, action, flags, keyCode, scanCode, metaState,
3891 repeatCount, policyFlags);
3894 void InputDispatcher::KeyEntry::recycle() {
3895 releaseInjectionState();
3897 dispatchInProgress = false;
3898 syntheticRepeat = false;
3899 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
3900 interceptKeyWakeupTime = 0;
3904 // --- InputDispatcher::MotionEntry ---
3906 InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
3907 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
3908 int32_t metaState, int32_t buttonState,
3909 int32_t edgeFlags, float xPrecision, float yPrecision,
3910 nsecs_t downTime, int32_t displayId, uint32_t pointerCount,
3911 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
3912 EventEntry(TYPE_MOTION, eventTime, policyFlags),
3913 eventTime(eventTime),
3914 deviceId(deviceId), source(source), action(action), flags(flags),
3915 metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
3916 xPrecision(xPrecision), yPrecision(yPrecision),
3917 downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
3918 for (uint32_t i = 0; i < pointerCount; i++) {
3919 this->pointerProperties[i].copyFrom(pointerProperties[i]);
3920 this->pointerCoords[i].copyFrom(pointerCoords[i]);
3924 InputDispatcher::MotionEntry::~MotionEntry() {
3927 void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
3928 msg.appendFormat("MotionEvent(deviceId=%d, source=0x%08x, action=%d, "
3929 "flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, edgeFlags=0x%08x, "
3930 "xPrecision=%.1f, yPrecision=%.1f, displayId=%d, pointers=[",
3931 deviceId, source, action, flags, metaState, buttonState, edgeFlags,
3932 xPrecision, yPrecision, displayId);
3933 for (uint32_t i = 0; i < pointerCount; i++) {
3937 msg.appendFormat("%d: (%.1f, %.1f)", pointerProperties[i].id,
3938 pointerCoords[i].getX(), pointerCoords[i].getY());
3940 msg.appendFormat("]), policyFlags=0x%08x", policyFlags);
3944 // --- InputDispatcher::DispatchEntry ---
3946 volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3948 InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3949 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
3951 eventEntry(eventEntry), targetFlags(targetFlags),
3952 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
3953 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
3954 eventEntry->refCount += 1;
3957 InputDispatcher::DispatchEntry::~DispatchEntry() {
3958 eventEntry->release();
3961 uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3962 // Sequence number 0 is reserved and will never be returned.
3965 seq = android_atomic_inc(&sNextSeqAtomic);
3971 // --- InputDispatcher::InputState ---
3973 InputDispatcher::InputState::InputState() {
3976 InputDispatcher::InputState::~InputState() {
3979 bool InputDispatcher::InputState::isNeutral() const {
3980 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
3983 bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
3984 int32_t displayId) const {
3985 for (size_t i = 0; i < mMotionMementos.size(); i++) {
3986 const MotionMemento& memento = mMotionMementos.itemAt(i);
3987 if (memento.deviceId == deviceId
3988 && memento.source == source
3989 && memento.displayId == displayId
3990 && memento.hovering) {
3997 bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3998 int32_t action, int32_t flags) {
4000 case AKEY_EVENT_ACTION_UP: {
4001 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4002 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4003 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4004 mFallbackKeys.removeItemsAt(i);
4010 ssize_t index = findKeyMemento(entry);
4012 mKeyMementos.removeAt(index);
4015 /* FIXME: We can't just drop the key up event because that prevents creating
4016 * popup windows that are automatically shown when a key is held and then
4017 * dismissed when the key is released. The problem is that the popup will
4018 * not have received the original key down, so the key up will be considered
4019 * to be inconsistent with its observed state. We could perhaps handle this
4020 * by synthesizing a key down but that will cause other problems.
4022 * So for now, allow inconsistent key up events to be dispatched.
4024 #if DEBUG_OUTBOUND_EVENT_DETAILS
4025 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4026 "keyCode=%d, scanCode=%d",
4027 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4034 case AKEY_EVENT_ACTION_DOWN: {
4035 ssize_t index = findKeyMemento(entry);
4037 mKeyMementos.removeAt(index);
4039 addKeyMemento(entry, flags);
4048 bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4049 int32_t action, int32_t flags) {
4050 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4051 switch (actionMasked) {
4052 case AMOTION_EVENT_ACTION_UP:
4053 case AMOTION_EVENT_ACTION_CANCEL: {
4054 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4056 mMotionMementos.removeAt(index);
4059 #if DEBUG_OUTBOUND_EVENT_DETAILS
4060 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4062 entry->deviceId, entry->source, actionMasked);
4067 case AMOTION_EVENT_ACTION_DOWN: {
4068 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4070 mMotionMementos.removeAt(index);
4072 addMotionMemento(entry, flags, false /*hovering*/);
4076 case AMOTION_EVENT_ACTION_POINTER_UP:
4077 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4078 case AMOTION_EVENT_ACTION_MOVE: {
4079 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4081 MotionMemento& memento = mMotionMementos.editItemAt(index);
4082 memento.setPointers(entry);
4085 if (actionMasked == AMOTION_EVENT_ACTION_MOVE
4086 && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
4087 | AINPUT_SOURCE_CLASS_NAVIGATION))) {
4088 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4091 #if DEBUG_OUTBOUND_EVENT_DETAILS
4092 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
4093 "deviceId=%d, source=%08x, actionMasked=%d",
4094 entry->deviceId, entry->source, actionMasked);
4099 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4100 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4102 mMotionMementos.removeAt(index);
4105 #if DEBUG_OUTBOUND_EVENT_DETAILS
4106 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4107 entry->deviceId, entry->source);
4112 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4113 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4114 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4116 mMotionMementos.removeAt(index);
4118 addMotionMemento(entry, flags, true /*hovering*/);
4127 ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4128 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4129 const KeyMemento& memento = mKeyMementos.itemAt(i);
4130 if (memento.deviceId == entry->deviceId
4131 && memento.source == entry->source
4132 && memento.keyCode == entry->keyCode
4133 && memento.scanCode == entry->scanCode) {
4140 ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4141 bool hovering) const {
4142 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4143 const MotionMemento& memento = mMotionMementos.itemAt(i);
4144 if (memento.deviceId == entry->deviceId
4145 && memento.source == entry->source
4146 && memento.displayId == entry->displayId
4147 && memento.hovering == hovering) {
4154 void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4155 mKeyMementos.push();
4156 KeyMemento& memento = mKeyMementos.editTop();
4157 memento.deviceId = entry->deviceId;
4158 memento.source = entry->source;
4159 memento.keyCode = entry->keyCode;
4160 memento.scanCode = entry->scanCode;
4161 memento.metaState = entry->metaState;
4162 memento.flags = flags;
4163 memento.downTime = entry->downTime;
4164 memento.policyFlags = entry->policyFlags;
4167 void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4168 int32_t flags, bool hovering) {
4169 mMotionMementos.push();
4170 MotionMemento& memento = mMotionMementos.editTop();
4171 memento.deviceId = entry->deviceId;
4172 memento.source = entry->source;
4173 memento.flags = flags;
4174 memento.xPrecision = entry->xPrecision;
4175 memento.yPrecision = entry->yPrecision;
4176 memento.downTime = entry->downTime;
4177 memento.displayId = entry->displayId;
4178 memento.setPointers(entry);
4179 memento.hovering = hovering;
4180 memento.policyFlags = entry->policyFlags;
4183 void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4184 pointerCount = entry->pointerCount;
4185 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4186 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4187 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4191 void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4192 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4193 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4194 const KeyMemento& memento = mKeyMementos.itemAt(i);
4195 if (shouldCancelKey(memento, options)) {
4196 outEvents.push(new KeyEntry(currentTime,
4197 memento.deviceId, memento.source, memento.policyFlags,
4198 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4199 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4203 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4204 const MotionMemento& memento = mMotionMementos.itemAt(i);
4205 if (shouldCancelMotion(memento, options)) {
4206 outEvents.push(new MotionEntry(currentTime,
4207 memento.deviceId, memento.source, memento.policyFlags,
4209 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4210 : AMOTION_EVENT_ACTION_CANCEL,
4211 memento.flags, 0, 0, 0,
4212 memento.xPrecision, memento.yPrecision, memento.downTime,
4214 memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
4219 void InputDispatcher::InputState::clear() {
4220 mKeyMementos.clear();
4221 mMotionMementos.clear();
4222 mFallbackKeys.clear();
4225 void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4226 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4227 const MotionMemento& memento = mMotionMementos.itemAt(i);
4228 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4229 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4230 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4231 if (memento.deviceId == otherMemento.deviceId
4232 && memento.source == otherMemento.source
4233 && memento.displayId == otherMemento.displayId) {
4234 other.mMotionMementos.removeAt(j);
4239 other.mMotionMementos.push(memento);
4244 int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4245 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4246 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4249 void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4250 int32_t fallbackKeyCode) {
4251 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4253 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4255 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4259 void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4260 mFallbackKeys.removeItem(originalKeyCode);
4263 bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4264 const CancelationOptions& options) {
4265 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4269 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4273 switch (options.mode) {
4274 case CancelationOptions::CANCEL_ALL_EVENTS:
4275 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4277 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4278 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4284 bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4285 const CancelationOptions& options) {
4286 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4290 switch (options.mode) {
4291 case CancelationOptions::CANCEL_ALL_EVENTS:
4293 case CancelationOptions::CANCEL_POINTER_EVENTS:
4294 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4295 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4296 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4303 // --- InputDispatcher::Connection ---
4305 InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4306 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4307 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4309 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4312 InputDispatcher::Connection::~Connection() {
4315 const char* InputDispatcher::Connection::getWindowName() const {
4316 if (inputWindowHandle != NULL) {
4317 return inputWindowHandle->getName().string();
4325 const char* InputDispatcher::Connection::getStatusLabel() const {
4341 InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4342 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4343 if (entry->seq == seq) {
4351 // --- InputDispatcher::CommandEntry ---
4353 InputDispatcher::CommandEntry::CommandEntry(Command command) :
4354 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4355 seq(0), handled(false) {
4358 InputDispatcher::CommandEntry::~CommandEntry() {
4362 // --- InputDispatcher::TouchState ---
4364 InputDispatcher::TouchState::TouchState() :
4365 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
4368 InputDispatcher::TouchState::~TouchState() {
4371 void InputDispatcher::TouchState::reset() {
4380 void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4382 split = other.split;
4383 deviceId = other.deviceId;
4384 source = other.source;
4385 displayId = other.displayId;
4386 windows = other.windows;
4389 void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4390 int32_t targetFlags, BitSet32 pointerIds) {
4391 if (targetFlags & InputTarget::FLAG_SPLIT) {
4395 for (size_t i = 0; i < windows.size(); i++) {
4396 TouchedWindow& touchedWindow = windows.editItemAt(i);
4397 if (touchedWindow.windowHandle == windowHandle) {
4398 touchedWindow.targetFlags |= targetFlags;
4399 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4400 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4402 touchedWindow.pointerIds.value |= pointerIds.value;
4409 TouchedWindow& touchedWindow = windows.editTop();
4410 touchedWindow.windowHandle = windowHandle;
4411 touchedWindow.targetFlags = targetFlags;
4412 touchedWindow.pointerIds = pointerIds;
4415 void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4416 for (size_t i = 0; i < windows.size(); i++) {
4417 if (windows.itemAt(i).windowHandle == windowHandle) {
4418 windows.removeAt(i);
4424 void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4425 for (size_t i = 0 ; i < windows.size(); ) {
4426 TouchedWindow& window = windows.editItemAt(i);
4427 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4428 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4429 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4430 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4433 windows.removeAt(i);
4438 sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4439 for (size_t i = 0; i < windows.size(); i++) {
4440 const TouchedWindow& window = windows.itemAt(i);
4441 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4442 return window.windowHandle;
4448 bool InputDispatcher::TouchState::isSlippery() const {
4449 // Must have exactly one foreground window.
4450 bool haveSlipperyForegroundWindow = false;
4451 for (size_t i = 0; i < windows.size(); i++) {
4452 const TouchedWindow& window = windows.itemAt(i);
4453 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4454 if (haveSlipperyForegroundWindow
4455 || !(window.windowHandle->getInfo()->layoutParamsFlags
4456 & InputWindowInfo::FLAG_SLIPPERY)) {
4459 haveSlipperyForegroundWindow = true;
4462 return haveSlipperyForegroundWindow;
4466 // --- InputDispatcherThread ---
4468 InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4469 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4472 InputDispatcherThread::~InputDispatcherThread() {
4475 bool InputDispatcherThread::threadLoop() {
4476 mDispatcher->dispatchOnce();
4480 } // namespace android