michael@0: /* michael@0: * Copyright (C) 2010 The Android Open Source Project michael@0: * michael@0: * Licensed under the Apache License, Version 2.0 (the "License"); michael@0: * you may not use this file except in compliance with the License. michael@0: * You may obtain a copy of the License at michael@0: * michael@0: * http://www.apache.org/licenses/LICENSE-2.0 michael@0: * michael@0: * Unless required by applicable law or agreed to in writing, software michael@0: * distributed under the License is distributed on an "AS IS" BASIS, michael@0: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. michael@0: * See the License for the specific language governing permissions and michael@0: * limitations under the License. michael@0: */ michael@0: michael@0: #define LOG_TAG "InputDispatcher" michael@0: #define ATRACE_TAG ATRACE_TAG_INPUT michael@0: michael@0: //#define LOG_NDEBUG 0 michael@0: #include "cutils_log.h" michael@0: michael@0: // Log detailed debug messages about each inbound event notification to the dispatcher. michael@0: #define DEBUG_INBOUND_EVENT_DETAILS 0 michael@0: michael@0: // Log detailed debug messages about each outbound event processed by the dispatcher. michael@0: #define DEBUG_OUTBOUND_EVENT_DETAILS 0 michael@0: michael@0: // Log debug messages about the dispatch cycle. michael@0: #define DEBUG_DISPATCH_CYCLE 0 michael@0: michael@0: // Log debug messages about registrations. michael@0: #define DEBUG_REGISTRATION 0 michael@0: michael@0: // Log debug messages about input event injection. michael@0: #define DEBUG_INJECTION 0 michael@0: michael@0: // Log debug messages about input focus tracking. michael@0: #define DEBUG_FOCUS 0 michael@0: michael@0: // Log debug messages about the app switch latency optimization. michael@0: #define DEBUG_APP_SWITCH 0 michael@0: michael@0: // Log debug messages about hover events. michael@0: #define DEBUG_HOVER 0 michael@0: michael@0: #include "InputDispatcher.h" michael@0: michael@0: #include "Trace.h" michael@0: #include "PowerManager.h" michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #define INDENT " " michael@0: #define INDENT2 " " michael@0: #define INDENT3 " " michael@0: #define INDENT4 " " michael@0: michael@0: namespace android { michael@0: michael@0: // Default input dispatching timeout if there is no focused application or paused window michael@0: // from which to determine an appropriate dispatching timeout. michael@0: const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec michael@0: michael@0: // Amount of time to allow for all pending events to be processed when an app switch michael@0: // key is on the way. This is used to preempt input dispatch and drop input events michael@0: // when an application takes too long to respond and the user has pressed an app switch key. michael@0: const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec michael@0: michael@0: // Amount of time to allow for an event to be dispatched (measured since its eventTime) michael@0: // before considering it stale and dropping it. michael@0: const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec michael@0: michael@0: // Amount of time to allow touch events to be streamed out to a connection before requiring michael@0: // that the first event be finished. This value extends the ANR timeout by the specified michael@0: // amount. For example, if streaming is allowed to get ahead by one second relative to the michael@0: // queue of waiting unfinished events, then ANRs will similarly be delayed by one second. michael@0: const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec michael@0: michael@0: // Log a warning when an event takes longer than this to process, even if an ANR does not occur. michael@0: const nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec michael@0: michael@0: michael@0: static inline nsecs_t now() { michael@0: return systemTime(SYSTEM_TIME_MONOTONIC); michael@0: } michael@0: michael@0: static inline const char* toString(bool value) { michael@0: return value ? "true" : "false"; michael@0: } michael@0: michael@0: static inline int32_t getMotionEventActionPointerIndex(int32_t action) { michael@0: return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) michael@0: >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; michael@0: } michael@0: michael@0: static bool isValidKeyAction(int32_t action) { michael@0: switch (action) { michael@0: case AKEY_EVENT_ACTION_DOWN: michael@0: case AKEY_EVENT_ACTION_UP: michael@0: return true; michael@0: default: michael@0: return false; michael@0: } michael@0: } michael@0: michael@0: static bool validateKeyEvent(int32_t action) { michael@0: if (! isValidKeyAction(action)) { michael@0: ALOGE("Key event has invalid action code 0x%x", action); michael@0: return false; michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: static bool isValidMotionAction(int32_t action, size_t pointerCount) { michael@0: switch (action & AMOTION_EVENT_ACTION_MASK) { michael@0: case AMOTION_EVENT_ACTION_DOWN: michael@0: case AMOTION_EVENT_ACTION_UP: michael@0: case AMOTION_EVENT_ACTION_CANCEL: michael@0: case AMOTION_EVENT_ACTION_MOVE: michael@0: case AMOTION_EVENT_ACTION_OUTSIDE: michael@0: case AMOTION_EVENT_ACTION_HOVER_ENTER: michael@0: case AMOTION_EVENT_ACTION_HOVER_MOVE: michael@0: case AMOTION_EVENT_ACTION_HOVER_EXIT: michael@0: case AMOTION_EVENT_ACTION_SCROLL: michael@0: return true; michael@0: case AMOTION_EVENT_ACTION_POINTER_DOWN: michael@0: case AMOTION_EVENT_ACTION_POINTER_UP: { michael@0: int32_t index = getMotionEventActionPointerIndex(action); michael@0: return index >= 0 && size_t(index) < pointerCount; michael@0: } michael@0: default: michael@0: return false; michael@0: } michael@0: } michael@0: michael@0: static bool validateMotionEvent(int32_t action, size_t pointerCount, michael@0: const PointerProperties* pointerProperties) { michael@0: if (! isValidMotionAction(action, pointerCount)) { michael@0: ALOGE("Motion event has invalid action code 0x%x", action); michael@0: return false; michael@0: } michael@0: if (pointerCount < 1 || pointerCount > MAX_POINTERS) { michael@0: ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.", michael@0: pointerCount, MAX_POINTERS); michael@0: return false; michael@0: } michael@0: BitSet32 pointerIdBits; michael@0: for (size_t i = 0; i < pointerCount; i++) { michael@0: int32_t id = pointerProperties[i].id; michael@0: if (id < 0 || id > MAX_POINTER_ID) { michael@0: ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d", michael@0: id, MAX_POINTER_ID); michael@0: return false; michael@0: } michael@0: if (pointerIdBits.hasBit(id)) { michael@0: ALOGE("Motion event has duplicate pointer id %d", id); michael@0: return false; michael@0: } michael@0: pointerIdBits.markBit(id); michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: static bool isMainDisplay(int32_t displayId) { michael@0: return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE; michael@0: } michael@0: michael@0: static void dumpRegion(String8& dump, const SkRegion& region) { michael@0: if (region.isEmpty()) { michael@0: dump.append(""); michael@0: return; michael@0: } michael@0: michael@0: bool first = true; michael@0: for (SkRegion::Iterator it(region); !it.done(); it.next()) { michael@0: if (first) { michael@0: first = false; michael@0: } else { michael@0: dump.append("|"); michael@0: } michael@0: const SkIRect& rect = it.rect(); michael@0: dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom); michael@0: } michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcher --- michael@0: michael@0: InputDispatcher::InputDispatcher(const sp& policy) : michael@0: mPolicy(policy), michael@0: mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX), michael@0: mNextUnblockedEvent(NULL), michael@0: mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false), michael@0: mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) { michael@0: mLooper = new Looper(false); michael@0: michael@0: mKeyRepeatState.lastKeyEntry = NULL; michael@0: michael@0: policy->getDispatcherConfiguration(&mConfig); michael@0: } michael@0: michael@0: InputDispatcher::~InputDispatcher() { michael@0: { // acquire lock michael@0: AutoMutex _l(mLock); michael@0: michael@0: resetKeyRepeatLocked(); michael@0: releasePendingEventLocked(); michael@0: drainInboundQueueLocked(); michael@0: } michael@0: michael@0: while (mConnectionsByFd.size() != 0) { michael@0: unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::dispatchOnce() { michael@0: nsecs_t nextWakeupTime = LONG_LONG_MAX; michael@0: { // acquire lock michael@0: AutoMutex _l(mLock); michael@0: mDispatcherIsAliveCondition.broadcast(); michael@0: michael@0: // Run a dispatch loop if there are no pending commands. michael@0: // The dispatch loop might enqueue commands to run afterwards. michael@0: if (!haveCommandsLocked()) { michael@0: dispatchOnceInnerLocked(&nextWakeupTime); michael@0: } michael@0: michael@0: // Run all pending commands if there are any. michael@0: // If any commands were run then force the next poll to wake up immediately. michael@0: if (runCommandsLockedInterruptible()) { michael@0: nextWakeupTime = LONG_LONG_MIN; michael@0: } michael@0: } // release lock michael@0: michael@0: // Wait for callback or timeout or wake. (make sure we round up, not down) michael@0: nsecs_t currentTime = now(); michael@0: int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime); michael@0: mLooper->pollOnce(timeoutMillis); michael@0: } michael@0: michael@0: void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) { michael@0: nsecs_t currentTime = now(); michael@0: michael@0: // Reset the key repeat timer whenever we disallow key events, even if the next event michael@0: // is not a key. This is to ensure that we abort a key repeat if the device is just coming michael@0: // out of sleep. michael@0: if (!mPolicy->isKeyRepeatEnabled()) { michael@0: resetKeyRepeatLocked(); michael@0: } michael@0: michael@0: // If dispatching is frozen, do not process timeouts or try to deliver any new events. michael@0: if (mDispatchFrozen) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Dispatch frozen. Waiting some more."); michael@0: #endif michael@0: return; michael@0: } michael@0: michael@0: // Optimize latency of app switches. michael@0: // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has michael@0: // been pressed. When it expires, we preempt dispatch and drop all other pending events. michael@0: bool isAppSwitchDue = mAppSwitchDueTime <= currentTime; michael@0: if (mAppSwitchDueTime < *nextWakeupTime) { michael@0: *nextWakeupTime = mAppSwitchDueTime; michael@0: } michael@0: michael@0: // Ready to start a new event. michael@0: // If we don't already have a pending event, go grab one. michael@0: if (! mPendingEvent) { michael@0: if (mInboundQueue.isEmpty()) { michael@0: if (isAppSwitchDue) { michael@0: // The inbound queue is empty so the app switch key we were waiting michael@0: // for will never arrive. Stop waiting for it. michael@0: resetPendingAppSwitchLocked(false); michael@0: isAppSwitchDue = false; michael@0: } michael@0: michael@0: // Synthesize a key repeat if appropriate. michael@0: if (mKeyRepeatState.lastKeyEntry) { michael@0: if (currentTime >= mKeyRepeatState.nextRepeatTime) { michael@0: mPendingEvent = synthesizeKeyRepeatLocked(currentTime); michael@0: } else { michael@0: if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) { michael@0: *nextWakeupTime = mKeyRepeatState.nextRepeatTime; michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Nothing to do if there is no pending event. michael@0: if (!mPendingEvent) { michael@0: return; michael@0: } michael@0: } else { michael@0: // Inbound queue has at least one entry. michael@0: mPendingEvent = mInboundQueue.dequeueAtHead(); michael@0: traceInboundQueueLengthLocked(); michael@0: } michael@0: michael@0: // Poke user activity for this event. michael@0: if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) { michael@0: pokeUserActivityLocked(mPendingEvent); michael@0: } michael@0: michael@0: // Get ready to dispatch the event. michael@0: resetANRTimeoutsLocked(); michael@0: } michael@0: michael@0: // Now we have an event to dispatch. michael@0: // All events are eventually dequeued and processed this way, even if we intend to drop them. michael@0: ALOG_ASSERT(mPendingEvent != NULL); michael@0: bool done = false; michael@0: DropReason dropReason = DROP_REASON_NOT_DROPPED; michael@0: if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) { michael@0: dropReason = DROP_REASON_POLICY; michael@0: } else if (!mDispatchEnabled) { michael@0: dropReason = DROP_REASON_DISABLED; michael@0: } michael@0: michael@0: if (mNextUnblockedEvent == mPendingEvent) { michael@0: mNextUnblockedEvent = NULL; michael@0: } michael@0: michael@0: switch (mPendingEvent->type) { michael@0: case EventEntry::TYPE_CONFIGURATION_CHANGED: { michael@0: ConfigurationChangedEntry* typedEntry = michael@0: static_cast(mPendingEvent); michael@0: done = dispatchConfigurationChangedLocked(currentTime, typedEntry); michael@0: dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped michael@0: break; michael@0: } michael@0: michael@0: case EventEntry::TYPE_DEVICE_RESET: { michael@0: DeviceResetEntry* typedEntry = michael@0: static_cast(mPendingEvent); michael@0: done = dispatchDeviceResetLocked(currentTime, typedEntry); michael@0: dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped michael@0: break; michael@0: } michael@0: michael@0: case EventEntry::TYPE_KEY: { michael@0: KeyEntry* typedEntry = static_cast(mPendingEvent); michael@0: if (isAppSwitchDue) { michael@0: if (isAppSwitchKeyEventLocked(typedEntry)) { michael@0: resetPendingAppSwitchLocked(true); michael@0: isAppSwitchDue = false; michael@0: } else if (dropReason == DROP_REASON_NOT_DROPPED) { michael@0: dropReason = DROP_REASON_APP_SWITCH; michael@0: } michael@0: } michael@0: if (dropReason == DROP_REASON_NOT_DROPPED michael@0: && isStaleEventLocked(currentTime, typedEntry)) { michael@0: dropReason = DROP_REASON_STALE; michael@0: } michael@0: if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) { michael@0: dropReason = DROP_REASON_BLOCKED; michael@0: } michael@0: done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime); michael@0: break; michael@0: } michael@0: michael@0: case EventEntry::TYPE_MOTION: { michael@0: MotionEntry* typedEntry = static_cast(mPendingEvent); michael@0: if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) { michael@0: dropReason = DROP_REASON_APP_SWITCH; michael@0: } michael@0: if (dropReason == DROP_REASON_NOT_DROPPED michael@0: && isStaleEventLocked(currentTime, typedEntry)) { michael@0: dropReason = DROP_REASON_STALE; michael@0: } michael@0: if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) { michael@0: dropReason = DROP_REASON_BLOCKED; michael@0: } michael@0: done = dispatchMotionLocked(currentTime, typedEntry, michael@0: &dropReason, nextWakeupTime); michael@0: break; michael@0: } michael@0: michael@0: default: michael@0: ALOG_ASSERT(false); michael@0: break; michael@0: } michael@0: michael@0: if (done) { michael@0: if (dropReason != DROP_REASON_NOT_DROPPED) { michael@0: dropInboundEventLocked(mPendingEvent, dropReason); michael@0: } michael@0: michael@0: releasePendingEventLocked(); michael@0: *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately michael@0: } michael@0: } michael@0: michael@0: bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) { michael@0: bool needWake = mInboundQueue.isEmpty(); michael@0: mInboundQueue.enqueueAtTail(entry); michael@0: traceInboundQueueLengthLocked(); michael@0: michael@0: switch (entry->type) { michael@0: case EventEntry::TYPE_KEY: { michael@0: // Optimize app switch latency. michael@0: // If the application takes too long to catch up then we drop all events preceding michael@0: // the app switch key. michael@0: KeyEntry* keyEntry = static_cast(entry); michael@0: if (isAppSwitchKeyEventLocked(keyEntry)) { michael@0: if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) { michael@0: mAppSwitchSawKeyDown = true; michael@0: } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) { michael@0: if (mAppSwitchSawKeyDown) { michael@0: #if DEBUG_APP_SWITCH michael@0: ALOGD("App switch is pending!"); michael@0: #endif michael@0: mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT; michael@0: mAppSwitchSawKeyDown = false; michael@0: needWake = true; michael@0: } michael@0: } michael@0: } michael@0: break; michael@0: } michael@0: michael@0: case EventEntry::TYPE_MOTION: { michael@0: // Optimize case where the current application is unresponsive and the user michael@0: // decides to touch a window in a different application. michael@0: // If the application takes too long to catch up then we drop all events preceding michael@0: // the touch into the other window. michael@0: MotionEntry* motionEntry = static_cast(entry); michael@0: if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN michael@0: && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) michael@0: && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY michael@0: && mInputTargetWaitApplicationHandle != NULL) { michael@0: int32_t displayId = motionEntry->displayId; michael@0: int32_t x = int32_t(motionEntry->pointerCoords[0]. michael@0: getAxisValue(AMOTION_EVENT_AXIS_X)); michael@0: int32_t y = int32_t(motionEntry->pointerCoords[0]. michael@0: getAxisValue(AMOTION_EVENT_AXIS_Y)); michael@0: sp touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y); michael@0: if (touchedWindowHandle != NULL michael@0: && touchedWindowHandle->inputApplicationHandle michael@0: != mInputTargetWaitApplicationHandle) { michael@0: // User touched a different application than the one we are waiting on. michael@0: // Flag the event, and start pruning the input queue. michael@0: mNextUnblockedEvent = motionEntry; michael@0: needWake = true; michael@0: } michael@0: } michael@0: break; michael@0: } michael@0: } michael@0: michael@0: return needWake; michael@0: } michael@0: michael@0: sp InputDispatcher::findTouchedWindowAtLocked(int32_t displayId, michael@0: int32_t x, int32_t y) { michael@0: // Traverse windows from front to back to find touched window. michael@0: size_t numWindows = mWindowHandles.size(); michael@0: for (size_t i = 0; i < numWindows; i++) { michael@0: sp windowHandle = mWindowHandles.itemAt(i); michael@0: const InputWindowInfo* windowInfo = windowHandle->getInfo(); michael@0: if (windowInfo->displayId == displayId) { michael@0: int32_t flags = windowInfo->layoutParamsFlags; michael@0: michael@0: if (windowInfo->visible) { michael@0: if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) { michael@0: bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE michael@0: | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0; michael@0: if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) { michael@0: // Found window. michael@0: return windowHandle; michael@0: } michael@0: } michael@0: } michael@0: michael@0: if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) { michael@0: // Error window is on top but not visible, so touch is dropped. michael@0: return NULL; michael@0: } michael@0: } michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) { michael@0: const char* reason; michael@0: switch (dropReason) { michael@0: case DROP_REASON_POLICY: michael@0: #if DEBUG_INBOUND_EVENT_DETAILS michael@0: ALOGD("Dropped event because policy consumed it."); michael@0: #endif michael@0: reason = "inbound event was dropped because the policy consumed it"; michael@0: break; michael@0: case DROP_REASON_DISABLED: michael@0: ALOGI("Dropped event because input dispatch is disabled."); michael@0: reason = "inbound event was dropped because input dispatch is disabled"; michael@0: break; michael@0: case DROP_REASON_APP_SWITCH: michael@0: ALOGI("Dropped event because of pending overdue app switch."); michael@0: reason = "inbound event was dropped because of pending overdue app switch"; michael@0: break; michael@0: case DROP_REASON_BLOCKED: michael@0: ALOGI("Dropped event because the current application is not responding and the user " michael@0: "has started interacting with a different application."); michael@0: reason = "inbound event was dropped because the current application is not responding " michael@0: "and the user has started interacting with a different application"; michael@0: break; michael@0: case DROP_REASON_STALE: michael@0: ALOGI("Dropped event because it is stale."); michael@0: reason = "inbound event was dropped because it is stale"; michael@0: break; michael@0: default: michael@0: ALOG_ASSERT(false); michael@0: return; michael@0: } michael@0: michael@0: switch (entry->type) { michael@0: case EventEntry::TYPE_KEY: { michael@0: CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason); michael@0: synthesizeCancelationEventsForAllConnectionsLocked(options); michael@0: break; michael@0: } michael@0: case EventEntry::TYPE_MOTION: { michael@0: MotionEntry* motionEntry = static_cast(entry); michael@0: if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) { michael@0: CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason); michael@0: synthesizeCancelationEventsForAllConnectionsLocked(options); michael@0: } else { michael@0: CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason); michael@0: synthesizeCancelationEventsForAllConnectionsLocked(options); michael@0: } michael@0: break; michael@0: } michael@0: } michael@0: } michael@0: michael@0: bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) { michael@0: return keyCode == AKEYCODE_HOME michael@0: || keyCode == AKEYCODE_ENDCALL michael@0: || keyCode == AKEYCODE_APP_SWITCH; michael@0: } michael@0: michael@0: bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) { michael@0: return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) michael@0: && isAppSwitchKeyCode(keyEntry->keyCode) michael@0: && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED) michael@0: && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER); michael@0: } michael@0: michael@0: bool InputDispatcher::isAppSwitchPendingLocked() { michael@0: return mAppSwitchDueTime != LONG_LONG_MAX; michael@0: } michael@0: michael@0: void InputDispatcher::resetPendingAppSwitchLocked(bool handled) { michael@0: mAppSwitchDueTime = LONG_LONG_MAX; michael@0: michael@0: #if DEBUG_APP_SWITCH michael@0: if (handled) { michael@0: ALOGD("App switch has arrived."); michael@0: } else { michael@0: ALOGD("App switch was abandoned."); michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) { michael@0: return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT; michael@0: } michael@0: michael@0: bool InputDispatcher::haveCommandsLocked() const { michael@0: return !mCommandQueue.isEmpty(); michael@0: } michael@0: michael@0: bool InputDispatcher::runCommandsLockedInterruptible() { michael@0: if (mCommandQueue.isEmpty()) { michael@0: return false; michael@0: } michael@0: michael@0: do { michael@0: CommandEntry* commandEntry = mCommandQueue.dequeueAtHead(); michael@0: michael@0: Command command = commandEntry->command; michael@0: (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible' michael@0: michael@0: commandEntry->connection.clear(); michael@0: delete commandEntry; michael@0: } while (! mCommandQueue.isEmpty()); michael@0: return true; michael@0: } michael@0: michael@0: InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) { michael@0: CommandEntry* commandEntry = new CommandEntry(command); michael@0: mCommandQueue.enqueueAtTail(commandEntry); michael@0: return commandEntry; michael@0: } michael@0: michael@0: void InputDispatcher::drainInboundQueueLocked() { michael@0: while (! mInboundQueue.isEmpty()) { michael@0: EventEntry* entry = mInboundQueue.dequeueAtHead(); michael@0: releaseInboundEventLocked(entry); michael@0: } michael@0: traceInboundQueueLengthLocked(); michael@0: } michael@0: michael@0: void InputDispatcher::releasePendingEventLocked() { michael@0: if (mPendingEvent) { michael@0: resetANRTimeoutsLocked(); michael@0: releaseInboundEventLocked(mPendingEvent); michael@0: mPendingEvent = NULL; michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) { michael@0: InjectionState* injectionState = entry->injectionState; michael@0: if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) { michael@0: #if DEBUG_DISPATCH_CYCLE michael@0: ALOGD("Injected inbound event was dropped."); michael@0: #endif michael@0: setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED); michael@0: } michael@0: if (entry == mNextUnblockedEvent) { michael@0: mNextUnblockedEvent = NULL; michael@0: } michael@0: entry->release(); michael@0: } michael@0: michael@0: void InputDispatcher::resetKeyRepeatLocked() { michael@0: if (mKeyRepeatState.lastKeyEntry) { michael@0: mKeyRepeatState.lastKeyEntry->release(); michael@0: mKeyRepeatState.lastKeyEntry = NULL; michael@0: } michael@0: } michael@0: michael@0: InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) { michael@0: KeyEntry* entry = mKeyRepeatState.lastKeyEntry; michael@0: michael@0: // Reuse the repeated key entry if it is otherwise unreferenced. michael@0: uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK) michael@0: | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED; michael@0: if (entry->refCount == 1) { michael@0: entry->recycle(); michael@0: entry->eventTime = currentTime; michael@0: entry->policyFlags = policyFlags; michael@0: entry->repeatCount += 1; michael@0: } else { michael@0: KeyEntry* newEntry = new KeyEntry(currentTime, michael@0: entry->deviceId, entry->source, policyFlags, michael@0: entry->action, entry->flags, entry->keyCode, entry->scanCode, michael@0: entry->metaState, entry->repeatCount + 1, entry->downTime); michael@0: michael@0: mKeyRepeatState.lastKeyEntry = newEntry; michael@0: entry->release(); michael@0: michael@0: entry = newEntry; michael@0: } michael@0: entry->syntheticRepeat = true; michael@0: michael@0: // Increment reference count since we keep a reference to the event in michael@0: // mKeyRepeatState.lastKeyEntry in addition to the one we return. michael@0: entry->refCount += 1; michael@0: michael@0: mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay; michael@0: return entry; michael@0: } michael@0: michael@0: bool InputDispatcher::dispatchConfigurationChangedLocked( michael@0: nsecs_t currentTime, ConfigurationChangedEntry* entry) { michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime); michael@0: #endif michael@0: michael@0: // Reset key repeating in case a keyboard device was added or removed or something. michael@0: resetKeyRepeatLocked(); michael@0: michael@0: // Enqueue a command to run outside the lock to tell the policy that the configuration changed. michael@0: CommandEntry* commandEntry = postCommandLocked( michael@0: & InputDispatcher::doNotifyConfigurationChangedInterruptible); michael@0: commandEntry->eventTime = entry->eventTime; michael@0: return true; michael@0: } michael@0: michael@0: bool InputDispatcher::dispatchDeviceResetLocked( michael@0: nsecs_t currentTime, DeviceResetEntry* entry) { michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId); michael@0: #endif michael@0: michael@0: CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, michael@0: "device was reset"); michael@0: options.deviceId = entry->deviceId; michael@0: synthesizeCancelationEventsForAllConnectionsLocked(options); michael@0: return true; michael@0: } michael@0: michael@0: bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry, michael@0: DropReason* dropReason, nsecs_t* nextWakeupTime) { michael@0: // Preprocessing. michael@0: if (! entry->dispatchInProgress) { michael@0: if (entry->repeatCount == 0 michael@0: && entry->action == AKEY_EVENT_ACTION_DOWN michael@0: && (entry->policyFlags & POLICY_FLAG_TRUSTED) michael@0: && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) { michael@0: if (mKeyRepeatState.lastKeyEntry michael@0: && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) { michael@0: // We have seen two identical key downs in a row which indicates that the device michael@0: // driver is automatically generating key repeats itself. We take note of the michael@0: // repeat here, but we disable our own next key repeat timer since it is clear that michael@0: // we will not need to synthesize key repeats ourselves. michael@0: entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1; michael@0: resetKeyRepeatLocked(); michael@0: mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves michael@0: } else { michael@0: // Not a repeat. Save key down state in case we do see a repeat later. michael@0: resetKeyRepeatLocked(); michael@0: mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout; michael@0: } michael@0: mKeyRepeatState.lastKeyEntry = entry; michael@0: entry->refCount += 1; michael@0: } else if (! entry->syntheticRepeat) { michael@0: resetKeyRepeatLocked(); michael@0: } michael@0: michael@0: if (entry->repeatCount == 1) { michael@0: entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS; michael@0: } else { michael@0: entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS; michael@0: } michael@0: michael@0: entry->dispatchInProgress = true; michael@0: michael@0: logOutboundKeyDetailsLocked("dispatchKey - ", entry); michael@0: } michael@0: michael@0: // Handle case where the policy asked us to try again later last time. michael@0: if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) { michael@0: if (currentTime < entry->interceptKeyWakeupTime) { michael@0: if (entry->interceptKeyWakeupTime < *nextWakeupTime) { michael@0: *nextWakeupTime = entry->interceptKeyWakeupTime; michael@0: } michael@0: return false; // wait until next wakeup michael@0: } michael@0: entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN; michael@0: entry->interceptKeyWakeupTime = 0; michael@0: } michael@0: michael@0: // Give the policy a chance to intercept the key. michael@0: if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) { michael@0: if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) { michael@0: CommandEntry* commandEntry = postCommandLocked( michael@0: & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible); michael@0: if (mFocusedWindowHandle != NULL) { michael@0: commandEntry->inputWindowHandle = mFocusedWindowHandle; michael@0: } michael@0: commandEntry->keyEntry = entry; michael@0: entry->refCount += 1; michael@0: return false; // wait for the command to run michael@0: } else { michael@0: entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE; michael@0: } michael@0: } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) { michael@0: if (*dropReason == DROP_REASON_NOT_DROPPED) { michael@0: *dropReason = DROP_REASON_POLICY; michael@0: } michael@0: } michael@0: michael@0: // Clean up if dropping the event. michael@0: if (*dropReason != DROP_REASON_NOT_DROPPED) { michael@0: setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY michael@0: ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED); michael@0: return true; michael@0: } michael@0: michael@0: // Identify targets. michael@0: Vector inputTargets; michael@0: int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime, michael@0: entry, inputTargets, nextWakeupTime); michael@0: if (injectionResult == INPUT_EVENT_INJECTION_PENDING) { michael@0: return false; michael@0: } michael@0: michael@0: setInjectionResultLocked(entry, injectionResult); michael@0: if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) { michael@0: return true; michael@0: } michael@0: michael@0: addMonitoringTargetsLocked(inputTargets); michael@0: michael@0: // Dispatch the key. michael@0: dispatchEventLocked(currentTime, entry, inputTargets); michael@0: return true; michael@0: } michael@0: michael@0: void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) { michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, " michael@0: "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, " michael@0: "repeatCount=%d, downTime=%lld", michael@0: prefix, michael@0: entry->eventTime, entry->deviceId, entry->source, entry->policyFlags, michael@0: entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState, michael@0: entry->repeatCount, entry->downTime); michael@0: #endif michael@0: } michael@0: michael@0: bool InputDispatcher::dispatchMotionLocked( michael@0: nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) { michael@0: // Preprocessing. michael@0: if (! entry->dispatchInProgress) { michael@0: entry->dispatchInProgress = true; michael@0: michael@0: logOutboundMotionDetailsLocked("dispatchMotion - ", entry); michael@0: } michael@0: michael@0: // Clean up if dropping the event. michael@0: if (*dropReason != DROP_REASON_NOT_DROPPED) { michael@0: setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY michael@0: ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED); michael@0: return true; michael@0: } michael@0: michael@0: bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER; michael@0: michael@0: // Identify targets. michael@0: Vector inputTargets; michael@0: michael@0: bool conflictingPointerActions = false; michael@0: int32_t injectionResult; michael@0: if (isPointerEvent) { michael@0: // Pointer event. (eg. touchscreen) michael@0: injectionResult = findTouchedWindowTargetsLocked(currentTime, michael@0: entry, inputTargets, nextWakeupTime, &conflictingPointerActions); michael@0: } else { michael@0: // Non touch event. (eg. trackball) michael@0: injectionResult = findFocusedWindowTargetsLocked(currentTime, michael@0: entry, inputTargets, nextWakeupTime); michael@0: } michael@0: if (injectionResult == INPUT_EVENT_INJECTION_PENDING) { michael@0: return false; michael@0: } michael@0: michael@0: setInjectionResultLocked(entry, injectionResult); michael@0: if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) { michael@0: return true; michael@0: } michael@0: michael@0: // TODO: support sending secondary display events to input monitors michael@0: if (isMainDisplay(entry->displayId)) { michael@0: addMonitoringTargetsLocked(inputTargets); michael@0: } michael@0: michael@0: // Dispatch the motion. michael@0: if (conflictingPointerActions) { michael@0: CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, michael@0: "conflicting pointer actions"); michael@0: synthesizeCancelationEventsForAllConnectionsLocked(options); michael@0: } michael@0: dispatchEventLocked(currentTime, entry, inputTargets); michael@0: return true; michael@0: } michael@0: michael@0: michael@0: void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) { michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, " michael@0: "action=0x%x, flags=0x%x, " michael@0: "metaState=0x%x, buttonState=0x%x, " michael@0: "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld", michael@0: prefix, michael@0: entry->eventTime, entry->deviceId, entry->source, entry->policyFlags, michael@0: entry->action, entry->flags, michael@0: entry->metaState, entry->buttonState, michael@0: entry->edgeFlags, entry->xPrecision, entry->yPrecision, michael@0: entry->downTime); michael@0: michael@0: for (uint32_t i = 0; i < entry->pointerCount; i++) { michael@0: ALOGD(" Pointer %d: id=%d, toolType=%d, " michael@0: "x=%f, y=%f, pressure=%f, size=%f, " michael@0: "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, " michael@0: "orientation=%f", michael@0: i, entry->pointerProperties[i].id, michael@0: entry->pointerProperties[i].toolType, michael@0: entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X), michael@0: entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y), michael@0: entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE), michael@0: entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE), michael@0: entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR), michael@0: entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR), michael@0: entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR), michael@0: entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR), michael@0: entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION)); michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: void InputDispatcher::dispatchEventLocked(nsecs_t currentTime, michael@0: EventEntry* eventEntry, const Vector& inputTargets) { michael@0: #if DEBUG_DISPATCH_CYCLE michael@0: ALOGD("dispatchEventToCurrentInputTargets"); michael@0: #endif michael@0: michael@0: ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true michael@0: michael@0: pokeUserActivityLocked(eventEntry); michael@0: michael@0: for (size_t i = 0; i < inputTargets.size(); i++) { michael@0: const InputTarget& inputTarget = inputTargets.itemAt(i); michael@0: michael@0: ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel); michael@0: if (connectionIndex >= 0) { michael@0: sp connection = mConnectionsByFd.valueAt(connectionIndex); michael@0: prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget); michael@0: } else { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Dropping event delivery to target with channel '%s' because it " michael@0: "is no longer registered with the input dispatcher.", michael@0: inputTarget.inputChannel->getName().string()); michael@0: #endif michael@0: } michael@0: } michael@0: } michael@0: michael@0: int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime, michael@0: const EventEntry* entry, michael@0: const sp& applicationHandle, michael@0: const sp& windowHandle, michael@0: nsecs_t* nextWakeupTime, const char* reason) { michael@0: if (applicationHandle == NULL && windowHandle == NULL) { michael@0: if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Waiting for system to become ready for input. Reason: %s", reason); michael@0: #endif michael@0: mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY; michael@0: mInputTargetWaitStartTime = currentTime; michael@0: mInputTargetWaitTimeoutTime = LONG_LONG_MAX; michael@0: mInputTargetWaitTimeoutExpired = false; michael@0: mInputTargetWaitApplicationHandle.clear(); michael@0: } michael@0: } else { michael@0: if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Waiting for application to become ready for input: %s. Reason: %s", michael@0: getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(), michael@0: reason); michael@0: #endif michael@0: nsecs_t timeout; michael@0: if (windowHandle != NULL) { michael@0: timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT); michael@0: } else if (applicationHandle != NULL) { michael@0: timeout = applicationHandle->getDispatchingTimeout( michael@0: DEFAULT_INPUT_DISPATCHING_TIMEOUT); michael@0: } else { michael@0: timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT; michael@0: } michael@0: michael@0: mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY; michael@0: mInputTargetWaitStartTime = currentTime; michael@0: mInputTargetWaitTimeoutTime = currentTime + timeout; michael@0: mInputTargetWaitTimeoutExpired = false; michael@0: mInputTargetWaitApplicationHandle.clear(); michael@0: michael@0: if (windowHandle != NULL) { michael@0: mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle; michael@0: } michael@0: if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) { michael@0: mInputTargetWaitApplicationHandle = applicationHandle; michael@0: } michael@0: } michael@0: } michael@0: michael@0: if (mInputTargetWaitTimeoutExpired) { michael@0: return INPUT_EVENT_INJECTION_TIMED_OUT; michael@0: } michael@0: michael@0: if (currentTime >= mInputTargetWaitTimeoutTime) { michael@0: onANRLocked(currentTime, applicationHandle, windowHandle, michael@0: entry->eventTime, mInputTargetWaitStartTime, reason); michael@0: michael@0: // Force poll loop to wake up immediately on next iteration once we get the michael@0: // ANR response back from the policy. michael@0: *nextWakeupTime = LONG_LONG_MIN; michael@0: return INPUT_EVENT_INJECTION_PENDING; michael@0: } else { michael@0: // Force poll loop to wake up when timeout is due. michael@0: if (mInputTargetWaitTimeoutTime < *nextWakeupTime) { michael@0: *nextWakeupTime = mInputTargetWaitTimeoutTime; michael@0: } michael@0: return INPUT_EVENT_INJECTION_PENDING; michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout, michael@0: const sp& inputChannel) { michael@0: if (newTimeout > 0) { michael@0: // Extend the timeout. michael@0: mInputTargetWaitTimeoutTime = now() + newTimeout; michael@0: } else { michael@0: // Give up. michael@0: mInputTargetWaitTimeoutExpired = true; michael@0: michael@0: // Input state will not be realistic. Mark it out of sync. michael@0: if (inputChannel.get()) { michael@0: ssize_t connectionIndex = getConnectionIndexLocked(inputChannel); michael@0: if (connectionIndex >= 0) { michael@0: sp connection = mConnectionsByFd.valueAt(connectionIndex); michael@0: sp windowHandle = connection->inputWindowHandle; michael@0: michael@0: if (windowHandle != NULL) { michael@0: mTouchState.removeWindow(windowHandle); michael@0: } michael@0: michael@0: if (connection->status == Connection::STATUS_NORMAL) { michael@0: CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, michael@0: "application not responding"); michael@0: synthesizeCancelationEventsForConnectionLocked(connection, options); michael@0: } michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked( michael@0: nsecs_t currentTime) { michael@0: if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) { michael@0: return currentTime - mInputTargetWaitStartTime; michael@0: } michael@0: return 0; michael@0: } michael@0: michael@0: void InputDispatcher::resetANRTimeoutsLocked() { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Resetting ANR timeouts."); michael@0: #endif michael@0: michael@0: // Reset input target wait timeout. michael@0: mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE; michael@0: mInputTargetWaitApplicationHandle.clear(); michael@0: } michael@0: michael@0: int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime, michael@0: const EventEntry* entry, Vector& inputTargets, nsecs_t* nextWakeupTime) { michael@0: int32_t injectionResult; michael@0: michael@0: // If there is no currently focused window and no focused application michael@0: // then drop the event. michael@0: if (mFocusedWindowHandle == NULL) { michael@0: if (mFocusedApplicationHandle != NULL) { michael@0: injectionResult = handleTargetsNotReadyLocked(currentTime, entry, michael@0: mFocusedApplicationHandle, NULL, nextWakeupTime, michael@0: "Waiting because no window has focus but there is a " michael@0: "focused application that may eventually add a window " michael@0: "when it finishes starting up."); michael@0: goto Unresponsive; michael@0: } michael@0: michael@0: ALOGI("Dropping event because there is no focused window or focused application."); michael@0: injectionResult = INPUT_EVENT_INJECTION_FAILED; michael@0: goto Failed; michael@0: } michael@0: michael@0: // Check permissions. michael@0: if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) { michael@0: injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED; michael@0: goto Failed; michael@0: } michael@0: michael@0: // If the currently focused window is paused then keep waiting. michael@0: if (mFocusedWindowHandle->getInfo()->paused) { michael@0: injectionResult = handleTargetsNotReadyLocked(currentTime, entry, michael@0: mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, michael@0: "Waiting because the focused window is paused."); michael@0: goto Unresponsive; michael@0: } michael@0: michael@0: // If the currently focused window is still working on previous events then keep waiting. michael@0: if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) { michael@0: injectionResult = handleTargetsNotReadyLocked(currentTime, entry, michael@0: mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, michael@0: "Waiting because the focused window has not finished " michael@0: "processing the input events that were previously delivered to it."); michael@0: goto Unresponsive; michael@0: } michael@0: michael@0: // Success! Output targets. michael@0: injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED; michael@0: addWindowTargetLocked(mFocusedWindowHandle, michael@0: InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0), michael@0: inputTargets); michael@0: michael@0: // Done. michael@0: Failed: michael@0: Unresponsive: michael@0: nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime); michael@0: updateDispatchStatisticsLocked(currentTime, entry, michael@0: injectionResult, timeSpentWaitingForApplication); michael@0: #if DEBUG_FOCUS michael@0: ALOGD("findFocusedWindow finished: injectionResult=%d, " michael@0: "timeSpentWaitingForApplication=%0.1fms", michael@0: injectionResult, timeSpentWaitingForApplication / 1000000.0); michael@0: #endif michael@0: return injectionResult; michael@0: } michael@0: michael@0: int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime, michael@0: const MotionEntry* entry, Vector& inputTargets, nsecs_t* nextWakeupTime, michael@0: bool* outConflictingPointerActions) { michael@0: enum InjectionPermission { michael@0: INJECTION_PERMISSION_UNKNOWN, michael@0: INJECTION_PERMISSION_GRANTED, michael@0: INJECTION_PERMISSION_DENIED michael@0: }; michael@0: michael@0: nsecs_t startTime = now(); michael@0: michael@0: // For security reasons, we defer updating the touch state until we are sure that michael@0: // event injection will be allowed. michael@0: // michael@0: // FIXME In the original code, screenWasOff could never be set to true. michael@0: // The reason is that the POLICY_FLAG_WOKE_HERE michael@0: // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw michael@0: // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was michael@0: // actually enqueued using the policyFlags that appeared in the final EV_SYN michael@0: // events upon which no preprocessing took place. So policyFlags was always 0. michael@0: // In the new native input dispatcher we're a bit more careful about event michael@0: // preprocessing so the touches we receive can actually have non-zero policyFlags. michael@0: // Unfortunately we obtain undesirable behavior. michael@0: // michael@0: // Here's what happens: michael@0: // michael@0: // When the device dims in anticipation of going to sleep, touches michael@0: // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause michael@0: // the device to brighten and reset the user activity timer. michael@0: // Touches on other windows (such as the launcher window) michael@0: // are dropped. Then after a moment, the device goes to sleep. Oops. michael@0: // michael@0: // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE michael@0: // instead of POLICY_FLAG_WOKE_HERE... michael@0: // michael@0: bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE; michael@0: michael@0: int32_t displayId = entry->displayId; michael@0: int32_t action = entry->action; michael@0: int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK; michael@0: michael@0: // Update the touch state as needed based on the properties of the touch event. michael@0: int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING; michael@0: InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN; michael@0: sp newHoverWindowHandle; michael@0: michael@0: bool isSplit = mTouchState.split; michael@0: bool switchedDevice = mTouchState.deviceId >= 0 && mTouchState.displayId >= 0 michael@0: && (mTouchState.deviceId != entry->deviceId michael@0: || mTouchState.source != entry->source michael@0: || mTouchState.displayId != displayId); michael@0: bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE michael@0: || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER michael@0: || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT); michael@0: bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN michael@0: || maskedAction == AMOTION_EVENT_ACTION_SCROLL michael@0: || isHoverAction); michael@0: bool wrongDevice = false; michael@0: if (newGesture) { michael@0: bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN; michael@0: if (switchedDevice && mTouchState.down && !down) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Dropping event because a pointer for a different device is already down."); michael@0: #endif michael@0: mTempTouchState.copyFrom(mTouchState); michael@0: injectionResult = INPUT_EVENT_INJECTION_FAILED; michael@0: switchedDevice = false; michael@0: wrongDevice = true; michael@0: goto Failed; michael@0: } michael@0: mTempTouchState.reset(); michael@0: mTempTouchState.down = down; michael@0: mTempTouchState.deviceId = entry->deviceId; michael@0: mTempTouchState.source = entry->source; michael@0: mTempTouchState.displayId = displayId; michael@0: isSplit = false; michael@0: } else { michael@0: mTempTouchState.copyFrom(mTouchState); michael@0: } michael@0: michael@0: if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) { michael@0: /* Case 1: New splittable pointer going down, or need target for hover or scroll. */ michael@0: michael@0: int32_t pointerIndex = getMotionEventActionPointerIndex(action); michael@0: int32_t x = int32_t(entry->pointerCoords[pointerIndex]. michael@0: getAxisValue(AMOTION_EVENT_AXIS_X)); michael@0: int32_t y = int32_t(entry->pointerCoords[pointerIndex]. michael@0: getAxisValue(AMOTION_EVENT_AXIS_Y)); michael@0: sp newTouchedWindowHandle; michael@0: sp topErrorWindowHandle; michael@0: bool isTouchModal = false; michael@0: michael@0: // Traverse windows from front to back to find touched window and outside targets. michael@0: size_t numWindows = mWindowHandles.size(); michael@0: for (size_t i = 0; i < numWindows; i++) { michael@0: sp windowHandle = mWindowHandles.itemAt(i); michael@0: const InputWindowInfo* windowInfo = windowHandle->getInfo(); michael@0: if (windowInfo->displayId != displayId) { michael@0: continue; // wrong display michael@0: } michael@0: michael@0: int32_t flags = windowInfo->layoutParamsFlags; michael@0: if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) { michael@0: if (topErrorWindowHandle == NULL) { michael@0: topErrorWindowHandle = windowHandle; michael@0: } michael@0: } michael@0: michael@0: if (windowInfo->visible) { michael@0: if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) { michael@0: isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE michael@0: | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0; michael@0: if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) { michael@0: if (! screenWasOff michael@0: || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) { michael@0: newTouchedWindowHandle = windowHandle; michael@0: } michael@0: break; // found touched window, exit window loop michael@0: } michael@0: } michael@0: michael@0: if (maskedAction == AMOTION_EVENT_ACTION_DOWN michael@0: && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) { michael@0: int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE; michael@0: if (isWindowObscuredAtPointLocked(windowHandle, x, y)) { michael@0: outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; michael@0: } michael@0: michael@0: mTempTouchState.addOrUpdateWindow( michael@0: windowHandle, outsideTargetFlags, BitSet32(0)); michael@0: } michael@0: } michael@0: } michael@0: michael@0: // If there is an error window but it is not taking focus (typically because michael@0: // it is invisible) then wait for it. Any other focused window may in michael@0: // fact be in ANR state. michael@0: if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) { michael@0: injectionResult = handleTargetsNotReadyLocked(currentTime, entry, michael@0: NULL, NULL, nextWakeupTime, michael@0: "Waiting because a system error window is about to be displayed."); michael@0: injectionPermission = INJECTION_PERMISSION_UNKNOWN; michael@0: goto Unresponsive; michael@0: } michael@0: michael@0: // Figure out whether splitting will be allowed for this window. michael@0: if (newTouchedWindowHandle != NULL michael@0: && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) { michael@0: // New window supports splitting. michael@0: isSplit = true; michael@0: } else if (isSplit) { michael@0: // New window does not support splitting but we have already split events. michael@0: // Ignore the new window. michael@0: newTouchedWindowHandle = NULL; michael@0: } michael@0: michael@0: // Handle the case where we did not find a window. michael@0: if (newTouchedWindowHandle == NULL) { michael@0: // Try to assign the pointer to the first foreground window we find, if there is one. michael@0: newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle(); michael@0: if (newTouchedWindowHandle == NULL) { michael@0: // There is no touched window. If this is an initial down event michael@0: // then wait for a window to appear that will handle the touch. This is michael@0: // to ensure that we report an ANR in the case where an application has started michael@0: // but not yet put up a window and the user is starting to get impatient. michael@0: if (maskedAction == AMOTION_EVENT_ACTION_DOWN michael@0: && mFocusedApplicationHandle != NULL) { michael@0: injectionResult = handleTargetsNotReadyLocked(currentTime, entry, michael@0: mFocusedApplicationHandle, NULL, nextWakeupTime, michael@0: "Waiting because there is no touchable window that can " michael@0: "handle the event but there is focused application that may " michael@0: "eventually add a new window when it finishes starting up."); michael@0: goto Unresponsive; michael@0: } michael@0: michael@0: ALOGI("Dropping event because there is no touched window."); michael@0: injectionResult = INPUT_EVENT_INJECTION_FAILED; michael@0: goto Failed; michael@0: } michael@0: } michael@0: michael@0: // Set target flags. michael@0: int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS; michael@0: if (isSplit) { michael@0: targetFlags |= InputTarget::FLAG_SPLIT; michael@0: } michael@0: if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) { michael@0: targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; michael@0: } michael@0: michael@0: // Update hover state. michael@0: if (isHoverAction) { michael@0: newHoverWindowHandle = newTouchedWindowHandle; michael@0: } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) { michael@0: newHoverWindowHandle = mLastHoverWindowHandle; michael@0: } michael@0: michael@0: // Update the temporary touch state. michael@0: BitSet32 pointerIds; michael@0: if (isSplit) { michael@0: uint32_t pointerId = entry->pointerProperties[pointerIndex].id; michael@0: pointerIds.markBit(pointerId); michael@0: } michael@0: mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds); michael@0: } else { michael@0: /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */ michael@0: michael@0: // If the pointer is not currently down, then ignore the event. michael@0: if (! mTempTouchState.down) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Dropping event because the pointer is not down or we previously " michael@0: "dropped the pointer down event."); michael@0: #endif michael@0: injectionResult = INPUT_EVENT_INJECTION_FAILED; michael@0: goto Failed; michael@0: } michael@0: michael@0: // Check whether touches should slip outside of the current foreground window. michael@0: if (maskedAction == AMOTION_EVENT_ACTION_MOVE michael@0: && entry->pointerCount == 1 michael@0: && mTempTouchState.isSlippery()) { michael@0: int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X)); michael@0: int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y)); michael@0: michael@0: sp oldTouchedWindowHandle = michael@0: mTempTouchState.getFirstForegroundWindowHandle(); michael@0: sp newTouchedWindowHandle = michael@0: findTouchedWindowAtLocked(displayId, x, y); michael@0: if (oldTouchedWindowHandle != newTouchedWindowHandle michael@0: && newTouchedWindowHandle != NULL) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Touch is slipping out of window %s into window %s.", michael@0: oldTouchedWindowHandle->getName().string(), michael@0: newTouchedWindowHandle->getName().string()); michael@0: #endif michael@0: // Make a slippery exit from the old window. michael@0: mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle, michael@0: InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0)); michael@0: michael@0: // Make a slippery entrance into the new window. michael@0: if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) { michael@0: isSplit = true; michael@0: } michael@0: michael@0: int32_t targetFlags = InputTarget::FLAG_FOREGROUND michael@0: | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER; michael@0: if (isSplit) { michael@0: targetFlags |= InputTarget::FLAG_SPLIT; michael@0: } michael@0: if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) { michael@0: targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED; michael@0: } michael@0: michael@0: BitSet32 pointerIds; michael@0: if (isSplit) { michael@0: pointerIds.markBit(entry->pointerProperties[0].id); michael@0: } michael@0: mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds); michael@0: } michael@0: } michael@0: } michael@0: michael@0: if (newHoverWindowHandle != mLastHoverWindowHandle) { michael@0: // Let the previous window know that the hover sequence is over. michael@0: if (mLastHoverWindowHandle != NULL) { michael@0: #if DEBUG_HOVER michael@0: ALOGD("Sending hover exit event to window %s.", michael@0: mLastHoverWindowHandle->getName().string()); michael@0: #endif michael@0: mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle, michael@0: InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0)); michael@0: } michael@0: michael@0: // Let the new window know that the hover sequence is starting. michael@0: if (newHoverWindowHandle != NULL) { michael@0: #if DEBUG_HOVER michael@0: ALOGD("Sending hover enter event to window %s.", michael@0: newHoverWindowHandle->getName().string()); michael@0: #endif michael@0: mTempTouchState.addOrUpdateWindow(newHoverWindowHandle, michael@0: InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0)); michael@0: } michael@0: } michael@0: michael@0: // Check permission to inject into all touched foreground windows and ensure there michael@0: // is at least one touched foreground window. michael@0: { michael@0: bool haveForegroundWindow = false; michael@0: for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { michael@0: const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; michael@0: if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) { michael@0: haveForegroundWindow = true; michael@0: if (! checkInjectionPermission(touchedWindow.windowHandle, michael@0: entry->injectionState)) { michael@0: injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED; michael@0: injectionPermission = INJECTION_PERMISSION_DENIED; michael@0: goto Failed; michael@0: } michael@0: } michael@0: } michael@0: if (! haveForegroundWindow) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Dropping event because there is no touched foreground window to receive it."); michael@0: #endif michael@0: injectionResult = INPUT_EVENT_INJECTION_FAILED; michael@0: goto Failed; michael@0: } michael@0: michael@0: // Permission granted to injection into all touched foreground windows. michael@0: injectionPermission = INJECTION_PERMISSION_GRANTED; michael@0: } michael@0: michael@0: // Check whether windows listening for outside touches are owned by the same UID. If it is michael@0: // set the policy flag that we will not reveal coordinate information to this window. michael@0: if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { michael@0: sp foregroundWindowHandle = michael@0: mTempTouchState.getFirstForegroundWindowHandle(); michael@0: const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid; michael@0: for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { michael@0: const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; michael@0: if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) { michael@0: sp inputWindowHandle = touchedWindow.windowHandle; michael@0: if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) { michael@0: mTempTouchState.addOrUpdateWindow(inputWindowHandle, michael@0: InputTarget::FLAG_ZERO_COORDS, BitSet32(0)); michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Ensure all touched foreground windows are ready for new input. michael@0: for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { michael@0: const TouchedWindow& touchedWindow = mTempTouchState.windows[i]; michael@0: if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) { michael@0: // If the touched window is paused then keep waiting. michael@0: if (touchedWindow.windowHandle->getInfo()->paused) { michael@0: injectionResult = handleTargetsNotReadyLocked(currentTime, entry, michael@0: NULL, touchedWindow.windowHandle, nextWakeupTime, michael@0: "Waiting because the touched window is paused."); michael@0: goto Unresponsive; michael@0: } michael@0: michael@0: // If the touched window is still working on previous events then keep waiting. michael@0: if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) { michael@0: injectionResult = handleTargetsNotReadyLocked(currentTime, entry, michael@0: NULL, touchedWindow.windowHandle, nextWakeupTime, michael@0: "Waiting because the touched window has not finished " michael@0: "processing the input events that were previously delivered to it."); michael@0: goto Unresponsive; michael@0: } michael@0: } michael@0: } michael@0: michael@0: // If this is the first pointer going down and the touched window has a wallpaper michael@0: // then also add the touched wallpaper windows so they are locked in for the duration michael@0: // of the touch gesture. michael@0: // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper michael@0: // engine only supports touch events. We would need to add a mechanism similar michael@0: // to View.onGenericMotionEvent to enable wallpapers to handle these events. michael@0: if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { michael@0: sp foregroundWindowHandle = michael@0: mTempTouchState.getFirstForegroundWindowHandle(); michael@0: if (foregroundWindowHandle->getInfo()->hasWallpaper) { michael@0: for (size_t i = 0; i < mWindowHandles.size(); i++) { michael@0: sp windowHandle = mWindowHandles.itemAt(i); michael@0: const InputWindowInfo* info = windowHandle->getInfo(); michael@0: if (info->displayId == displayId michael@0: && windowHandle->getInfo()->layoutParamsType michael@0: == InputWindowInfo::TYPE_WALLPAPER) { michael@0: mTempTouchState.addOrUpdateWindow(windowHandle, michael@0: InputTarget::FLAG_WINDOW_IS_OBSCURED michael@0: | InputTarget::FLAG_DISPATCH_AS_IS, michael@0: BitSet32(0)); michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Success! Output targets. michael@0: injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED; michael@0: michael@0: for (size_t i = 0; i < mTempTouchState.windows.size(); i++) { michael@0: const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i); michael@0: addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags, michael@0: touchedWindow.pointerIds, inputTargets); michael@0: } michael@0: michael@0: // Drop the outside or hover touch windows since we will not care about them michael@0: // in the next iteration. michael@0: mTempTouchState.filterNonAsIsTouchWindows(); michael@0: michael@0: Failed: michael@0: // Check injection permission once and for all. michael@0: if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) { michael@0: if (checkInjectionPermission(NULL, entry->injectionState)) { michael@0: injectionPermission = INJECTION_PERMISSION_GRANTED; michael@0: } else { michael@0: injectionPermission = INJECTION_PERMISSION_DENIED; michael@0: } michael@0: } michael@0: michael@0: // Update final pieces of touch state if the injector had permission. michael@0: if (injectionPermission == INJECTION_PERMISSION_GRANTED) { michael@0: if (!wrongDevice) { michael@0: if (switchedDevice) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Conflicting pointer actions: Switched to a different device."); michael@0: #endif michael@0: *outConflictingPointerActions = true; michael@0: } michael@0: michael@0: if (isHoverAction) { michael@0: // Started hovering, therefore no longer down. michael@0: if (mTouchState.down) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Conflicting pointer actions: Hover received while pointer was down."); michael@0: #endif michael@0: *outConflictingPointerActions = true; michael@0: } michael@0: mTouchState.reset(); michael@0: if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER michael@0: || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) { michael@0: mTouchState.deviceId = entry->deviceId; michael@0: mTouchState.source = entry->source; michael@0: mTouchState.displayId = displayId; michael@0: } michael@0: } else if (maskedAction == AMOTION_EVENT_ACTION_UP michael@0: || maskedAction == AMOTION_EVENT_ACTION_CANCEL) { michael@0: // All pointers up or canceled. michael@0: mTouchState.reset(); michael@0: } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) { michael@0: // First pointer went down. michael@0: if (mTouchState.down) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Conflicting pointer actions: Down received while already down."); michael@0: #endif michael@0: *outConflictingPointerActions = true; michael@0: } michael@0: mTouchState.copyFrom(mTempTouchState); michael@0: } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) { michael@0: // One pointer went up. michael@0: if (isSplit) { michael@0: int32_t pointerIndex = getMotionEventActionPointerIndex(action); michael@0: uint32_t pointerId = entry->pointerProperties[pointerIndex].id; michael@0: michael@0: for (size_t i = 0; i < mTempTouchState.windows.size(); ) { michael@0: TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i); michael@0: if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) { michael@0: touchedWindow.pointerIds.clearBit(pointerId); michael@0: if (touchedWindow.pointerIds.isEmpty()) { michael@0: mTempTouchState.windows.removeAt(i); michael@0: continue; michael@0: } michael@0: } michael@0: i += 1; michael@0: } michael@0: } michael@0: mTouchState.copyFrom(mTempTouchState); michael@0: } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) { michael@0: // Discard temporary touch state since it was only valid for this action. michael@0: } else { michael@0: // Save changes to touch state as-is for all other actions. michael@0: mTouchState.copyFrom(mTempTouchState); michael@0: } michael@0: michael@0: // Update hover state. michael@0: mLastHoverWindowHandle = newHoverWindowHandle; michael@0: } michael@0: } else { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Not updating touch focus because injection was denied."); michael@0: #endif michael@0: } michael@0: michael@0: Unresponsive: michael@0: // Reset temporary touch state to ensure we release unnecessary references to input channels. michael@0: mTempTouchState.reset(); michael@0: michael@0: nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime); michael@0: updateDispatchStatisticsLocked(currentTime, entry, michael@0: injectionResult, timeSpentWaitingForApplication); michael@0: #if DEBUG_FOCUS michael@0: ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, " michael@0: "timeSpentWaitingForApplication=%0.1fms", michael@0: injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0); michael@0: #endif michael@0: return injectionResult; michael@0: } michael@0: michael@0: void InputDispatcher::addWindowTargetLocked(const sp& windowHandle, michael@0: int32_t targetFlags, BitSet32 pointerIds, Vector& inputTargets) { michael@0: inputTargets.push(); michael@0: michael@0: const InputWindowInfo* windowInfo = windowHandle->getInfo(); michael@0: InputTarget& target = inputTargets.editTop(); michael@0: target.inputChannel = windowInfo->inputChannel; michael@0: target.flags = targetFlags; michael@0: target.xOffset = - windowInfo->frameLeft; michael@0: target.yOffset = - windowInfo->frameTop; michael@0: target.scaleFactor = windowInfo->scaleFactor; michael@0: target.pointerIds = pointerIds; michael@0: } michael@0: michael@0: void InputDispatcher::addMonitoringTargetsLocked(Vector& inputTargets) { michael@0: for (size_t i = 0; i < mMonitoringChannels.size(); i++) { michael@0: inputTargets.push(); michael@0: michael@0: InputTarget& target = inputTargets.editTop(); michael@0: target.inputChannel = mMonitoringChannels[i]; michael@0: target.flags = InputTarget::FLAG_DISPATCH_AS_IS; michael@0: target.xOffset = 0; michael@0: target.yOffset = 0; michael@0: target.pointerIds.clear(); michael@0: target.scaleFactor = 1.0f; michael@0: } michael@0: } michael@0: michael@0: bool InputDispatcher::checkInjectionPermission(const sp& windowHandle, michael@0: const InjectionState* injectionState) { michael@0: if (injectionState michael@0: && (windowHandle == NULL michael@0: || windowHandle->getInfo()->ownerUid != injectionState->injectorUid) michael@0: && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) { michael@0: if (windowHandle != NULL) { michael@0: ALOGW("Permission denied: injecting event from pid %d uid %d to window %s " michael@0: "owned by uid %d", michael@0: injectionState->injectorPid, injectionState->injectorUid, michael@0: windowHandle->getName().string(), michael@0: windowHandle->getInfo()->ownerUid); michael@0: } else { michael@0: ALOGW("Permission denied: injecting event from pid %d uid %d", michael@0: injectionState->injectorPid, injectionState->injectorUid); michael@0: } michael@0: return false; michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: bool InputDispatcher::isWindowObscuredAtPointLocked( michael@0: const sp& windowHandle, int32_t x, int32_t y) const { michael@0: int32_t displayId = windowHandle->getInfo()->displayId; michael@0: size_t numWindows = mWindowHandles.size(); michael@0: for (size_t i = 0; i < numWindows; i++) { michael@0: sp otherHandle = mWindowHandles.itemAt(i); michael@0: if (otherHandle == windowHandle) { michael@0: break; michael@0: } michael@0: michael@0: const InputWindowInfo* otherInfo = otherHandle->getInfo(); michael@0: if (otherInfo->displayId == displayId michael@0: && otherInfo->visible && !otherInfo->isTrustedOverlay() michael@0: && otherInfo->frameContainsPoint(x, y)) { michael@0: return true; michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime, michael@0: const sp& windowHandle, const EventEntry* eventEntry) { michael@0: ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel()); michael@0: if (connectionIndex >= 0) { michael@0: sp connection = mConnectionsByFd.valueAt(connectionIndex); michael@0: if (connection->inputPublisherBlocked) { michael@0: return false; michael@0: } michael@0: if (eventEntry->type == EventEntry::TYPE_KEY) { michael@0: // If the event is a key event, then we must wait for all previous events to michael@0: // complete before delivering it because previous events may have the michael@0: // side-effect of transferring focus to a different window and we want to michael@0: // ensure that the following keys are sent to the new window. michael@0: // michael@0: // Suppose the user touches a button in a window then immediately presses "A". michael@0: // If the button causes a pop-up window to appear then we want to ensure that michael@0: // the "A" key is delivered to the new pop-up window. This is because users michael@0: // often anticipate pending UI changes when typing on a keyboard. michael@0: // To obtain this behavior, we must serialize key events with respect to all michael@0: // prior input events. michael@0: return connection->outboundQueue.isEmpty() michael@0: && connection->waitQueue.isEmpty(); michael@0: } michael@0: // Touch events can always be sent to a window immediately because the user intended michael@0: // to touch whatever was visible at the time. Even if focus changes or a new michael@0: // window appears moments later, the touch event was meant to be delivered to michael@0: // whatever window happened to be on screen at the time. michael@0: // michael@0: // Generic motion events, such as trackball or joystick events are a little trickier. michael@0: // Like key events, generic motion events are delivered to the focused window. michael@0: // Unlike key events, generic motion events don't tend to transfer focus to other michael@0: // windows and it is not important for them to be serialized. So we prefer to deliver michael@0: // generic motion events as soon as possible to improve efficiency and reduce lag michael@0: // through batching. michael@0: // michael@0: // The one case where we pause input event delivery is when the wait queue is piling michael@0: // up with lots of events because the application is not responding. michael@0: // This condition ensures that ANRs are detected reliably. michael@0: if (!connection->waitQueue.isEmpty() michael@0: && currentTime >= connection->waitQueue.head->eventEntry->eventTime michael@0: + STREAM_AHEAD_EVENT_TIMEOUT) { michael@0: return false; michael@0: } michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: String8 InputDispatcher::getApplicationWindowLabelLocked( michael@0: const sp& applicationHandle, michael@0: const sp& windowHandle) { michael@0: if (applicationHandle != NULL) { michael@0: if (windowHandle != NULL) { michael@0: String8 label(applicationHandle->getName()); michael@0: label.append(" - "); michael@0: label.append(windowHandle->getName()); michael@0: return label; michael@0: } else { michael@0: return applicationHandle->getName(); michael@0: } michael@0: } else if (windowHandle != NULL) { michael@0: return windowHandle->getName(); michael@0: } else { michael@0: return String8(""); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) { michael@0: if (mFocusedWindowHandle != NULL) { michael@0: const InputWindowInfo* info = mFocusedWindowHandle->getInfo(); michael@0: if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) { michael@0: #if DEBUG_DISPATCH_CYCLE michael@0: ALOGD("Not poking user activity: disabled by window '%s'.", info->name.string()); michael@0: #endif michael@0: return; michael@0: } michael@0: } michael@0: michael@0: int32_t eventType = USER_ACTIVITY_EVENT_OTHER; michael@0: switch (eventEntry->type) { michael@0: case EventEntry::TYPE_MOTION: { michael@0: const MotionEntry* motionEntry = static_cast(eventEntry); michael@0: if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) { michael@0: return; michael@0: } michael@0: michael@0: if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) { michael@0: eventType = USER_ACTIVITY_EVENT_TOUCH; michael@0: } michael@0: break; michael@0: } michael@0: case EventEntry::TYPE_KEY: { michael@0: const KeyEntry* keyEntry = static_cast(eventEntry); michael@0: if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) { michael@0: return; michael@0: } michael@0: eventType = USER_ACTIVITY_EVENT_BUTTON; michael@0: break; michael@0: } michael@0: } michael@0: michael@0: CommandEntry* commandEntry = postCommandLocked( michael@0: & InputDispatcher::doPokeUserActivityLockedInterruptible); michael@0: commandEntry->eventTime = eventEntry->eventTime; michael@0: commandEntry->userActivityEventType = eventType; michael@0: } michael@0: michael@0: void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime, michael@0: const sp& connection, EventEntry* eventEntry, const InputTarget* inputTarget) { michael@0: #if DEBUG_DISPATCH_CYCLE michael@0: ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, " michael@0: "xOffset=%f, yOffset=%f, scaleFactor=%f, " michael@0: "pointerIds=0x%x", michael@0: connection->getInputChannelName(), inputTarget->flags, michael@0: inputTarget->xOffset, inputTarget->yOffset, michael@0: inputTarget->scaleFactor, inputTarget->pointerIds.value); michael@0: #endif michael@0: michael@0: // Skip this event if the connection status is not normal. michael@0: // We don't want to enqueue additional outbound events if the connection is broken. michael@0: if (connection->status != Connection::STATUS_NORMAL) { michael@0: #if DEBUG_DISPATCH_CYCLE michael@0: ALOGD("channel '%s' ~ Dropping event because the channel status is %s", michael@0: connection->getInputChannelName(), connection->getStatusLabel()); michael@0: #endif michael@0: return; michael@0: } michael@0: michael@0: // Split a motion event if needed. michael@0: if (inputTarget->flags & InputTarget::FLAG_SPLIT) { michael@0: ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION); michael@0: michael@0: MotionEntry* originalMotionEntry = static_cast(eventEntry); michael@0: if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) { michael@0: MotionEntry* splitMotionEntry = splitMotionEvent( michael@0: originalMotionEntry, inputTarget->pointerIds); michael@0: if (!splitMotionEntry) { michael@0: return; // split event was dropped michael@0: } michael@0: #if DEBUG_FOCUS michael@0: ALOGD("channel '%s' ~ Split motion event.", michael@0: connection->getInputChannelName()); michael@0: logOutboundMotionDetailsLocked(" ", splitMotionEntry); michael@0: #endif michael@0: enqueueDispatchEntriesLocked(currentTime, connection, michael@0: splitMotionEntry, inputTarget); michael@0: splitMotionEntry->release(); michael@0: return; michael@0: } michael@0: } michael@0: michael@0: // Not splitting. Enqueue dispatch entries for the event as is. michael@0: enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget); michael@0: } michael@0: michael@0: void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime, michael@0: const sp& connection, EventEntry* eventEntry, const InputTarget* inputTarget) { michael@0: bool wasEmpty = connection->outboundQueue.isEmpty(); michael@0: michael@0: // Enqueue dispatch entries for the requested modes. michael@0: enqueueDispatchEntryLocked(connection, eventEntry, inputTarget, michael@0: InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT); michael@0: enqueueDispatchEntryLocked(connection, eventEntry, inputTarget, michael@0: InputTarget::FLAG_DISPATCH_AS_OUTSIDE); michael@0: enqueueDispatchEntryLocked(connection, eventEntry, inputTarget, michael@0: InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER); michael@0: enqueueDispatchEntryLocked(connection, eventEntry, inputTarget, michael@0: InputTarget::FLAG_DISPATCH_AS_IS); michael@0: enqueueDispatchEntryLocked(connection, eventEntry, inputTarget, michael@0: InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT); michael@0: enqueueDispatchEntryLocked(connection, eventEntry, inputTarget, michael@0: InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER); michael@0: michael@0: // If the outbound queue was previously empty, start the dispatch cycle going. michael@0: if (wasEmpty && !connection->outboundQueue.isEmpty()) { michael@0: startDispatchCycleLocked(currentTime, connection); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::enqueueDispatchEntryLocked( michael@0: const sp& connection, EventEntry* eventEntry, const InputTarget* inputTarget, michael@0: int32_t dispatchMode) { michael@0: int32_t inputTargetFlags = inputTarget->flags; michael@0: if (!(inputTargetFlags & dispatchMode)) { michael@0: return; michael@0: } michael@0: inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode; michael@0: michael@0: // This is a new event. michael@0: // Enqueue a new dispatch entry onto the outbound queue for this connection. michael@0: DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref michael@0: inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset, michael@0: inputTarget->scaleFactor); michael@0: michael@0: // Apply target flags and update the connection's input state. michael@0: switch (eventEntry->type) { michael@0: case EventEntry::TYPE_KEY: { michael@0: KeyEntry* keyEntry = static_cast(eventEntry); michael@0: dispatchEntry->resolvedAction = keyEntry->action; michael@0: dispatchEntry->resolvedFlags = keyEntry->flags; michael@0: michael@0: if (!connection->inputState.trackKey(keyEntry, michael@0: dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) { michael@0: #if DEBUG_DISPATCH_CYCLE michael@0: ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event", michael@0: connection->getInputChannelName()); michael@0: #endif michael@0: delete dispatchEntry; michael@0: return; // skip the inconsistent event michael@0: } michael@0: break; michael@0: } michael@0: michael@0: case EventEntry::TYPE_MOTION: { michael@0: MotionEntry* motionEntry = static_cast(eventEntry); michael@0: if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) { michael@0: dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE; michael@0: } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) { michael@0: dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT; michael@0: } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) { michael@0: dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER; michael@0: } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) { michael@0: dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL; michael@0: } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) { michael@0: dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN; michael@0: } else { michael@0: dispatchEntry->resolvedAction = motionEntry->action; michael@0: } michael@0: if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE michael@0: && !connection->inputState.isHovering( michael@0: motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) { michael@0: #if DEBUG_DISPATCH_CYCLE michael@0: ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event", michael@0: connection->getInputChannelName()); michael@0: #endif michael@0: dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER; michael@0: } michael@0: michael@0: dispatchEntry->resolvedFlags = motionEntry->flags; michael@0: if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) { michael@0: dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED; michael@0: } michael@0: michael@0: if (!connection->inputState.trackMotion(motionEntry, michael@0: dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) { michael@0: #if DEBUG_DISPATCH_CYCLE michael@0: ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event", michael@0: connection->getInputChannelName()); michael@0: #endif michael@0: delete dispatchEntry; michael@0: return; // skip the inconsistent event michael@0: } michael@0: break; michael@0: } michael@0: } michael@0: michael@0: // Remember that we are waiting for this dispatch to complete. michael@0: if (dispatchEntry->hasForegroundTarget()) { michael@0: incrementPendingForegroundDispatchesLocked(eventEntry); michael@0: } michael@0: michael@0: // Enqueue the dispatch entry. michael@0: connection->outboundQueue.enqueueAtTail(dispatchEntry); michael@0: traceOutboundQueueLengthLocked(connection); michael@0: } michael@0: michael@0: void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime, michael@0: const sp& connection) { michael@0: #if DEBUG_DISPATCH_CYCLE michael@0: ALOGD("channel '%s' ~ startDispatchCycle", michael@0: connection->getInputChannelName()); michael@0: #endif michael@0: michael@0: while (connection->status == Connection::STATUS_NORMAL michael@0: && !connection->outboundQueue.isEmpty()) { michael@0: DispatchEntry* dispatchEntry = connection->outboundQueue.head; michael@0: dispatchEntry->deliveryTime = currentTime; michael@0: michael@0: // Publish the event. michael@0: status_t status; michael@0: EventEntry* eventEntry = dispatchEntry->eventEntry; michael@0: switch (eventEntry->type) { michael@0: case EventEntry::TYPE_KEY: { michael@0: KeyEntry* keyEntry = static_cast(eventEntry); michael@0: michael@0: // Publish the key event. michael@0: status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq, michael@0: keyEntry->deviceId, keyEntry->source, michael@0: dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags, michael@0: keyEntry->keyCode, keyEntry->scanCode, michael@0: keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime, michael@0: keyEntry->eventTime); michael@0: break; michael@0: } michael@0: michael@0: case EventEntry::TYPE_MOTION: { michael@0: MotionEntry* motionEntry = static_cast(eventEntry); michael@0: michael@0: PointerCoords scaledCoords[MAX_POINTERS]; michael@0: const PointerCoords* usingCoords = motionEntry->pointerCoords; michael@0: michael@0: // Set the X and Y offset depending on the input source. michael@0: float xOffset, yOffset, scaleFactor; michael@0: if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) michael@0: && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) { michael@0: scaleFactor = dispatchEntry->scaleFactor; michael@0: xOffset = dispatchEntry->xOffset * scaleFactor; michael@0: yOffset = dispatchEntry->yOffset * scaleFactor; michael@0: if (scaleFactor != 1.0f) { michael@0: for (size_t i = 0; i < motionEntry->pointerCount; i++) { michael@0: scaledCoords[i] = motionEntry->pointerCoords[i]; michael@0: scaledCoords[i].scale(scaleFactor); michael@0: } michael@0: usingCoords = scaledCoords; michael@0: } michael@0: } else { michael@0: xOffset = 0.0f; michael@0: yOffset = 0.0f; michael@0: scaleFactor = 1.0f; michael@0: michael@0: // We don't want the dispatch target to know. michael@0: if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) { michael@0: for (size_t i = 0; i < motionEntry->pointerCount; i++) { michael@0: scaledCoords[i].clear(); michael@0: } michael@0: usingCoords = scaledCoords; michael@0: } michael@0: } michael@0: michael@0: // Publish the motion event. michael@0: status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq, michael@0: motionEntry->deviceId, motionEntry->source, michael@0: dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags, michael@0: motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState, michael@0: xOffset, yOffset, michael@0: motionEntry->xPrecision, motionEntry->yPrecision, michael@0: motionEntry->downTime, motionEntry->eventTime, michael@0: motionEntry->pointerCount, motionEntry->pointerProperties, michael@0: usingCoords); michael@0: break; michael@0: } michael@0: michael@0: default: michael@0: ALOG_ASSERT(false); michael@0: return; michael@0: } michael@0: michael@0: // Check the result. michael@0: if (status) { michael@0: if (status == WOULD_BLOCK) { michael@0: if (connection->waitQueue.isEmpty()) { michael@0: ALOGE("channel '%s' ~ Could not publish event because the pipe is full. " michael@0: "This is unexpected because the wait queue is empty, so the pipe " michael@0: "should be empty and we shouldn't have any problems writing an " michael@0: "event to it, status=%d", connection->getInputChannelName(), status); michael@0: abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/); michael@0: } else { michael@0: // Pipe is full and we are waiting for the app to finish process some events michael@0: // before sending more events to it. michael@0: #if DEBUG_DISPATCH_CYCLE michael@0: ALOGD("channel '%s' ~ Could not publish event because the pipe is full, " michael@0: "waiting for the application to catch up", michael@0: connection->getInputChannelName()); michael@0: #endif michael@0: connection->inputPublisherBlocked = true; michael@0: } michael@0: } else { michael@0: ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, " michael@0: "status=%d", connection->getInputChannelName(), status); michael@0: abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/); michael@0: } michael@0: return; michael@0: } michael@0: michael@0: // Re-enqueue the event on the wait queue. michael@0: connection->outboundQueue.dequeue(dispatchEntry); michael@0: traceOutboundQueueLengthLocked(connection); michael@0: connection->waitQueue.enqueueAtTail(dispatchEntry); michael@0: traceWaitQueueLengthLocked(connection); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime, michael@0: const sp& connection, uint32_t seq, bool handled) { michael@0: #if DEBUG_DISPATCH_CYCLE michael@0: ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s", michael@0: connection->getInputChannelName(), seq, toString(handled)); michael@0: #endif michael@0: michael@0: connection->inputPublisherBlocked = false; michael@0: michael@0: if (connection->status == Connection::STATUS_BROKEN michael@0: || connection->status == Connection::STATUS_ZOMBIE) { michael@0: return; michael@0: } michael@0: michael@0: // Notify other system components and prepare to start the next dispatch cycle. michael@0: onDispatchCycleFinishedLocked(currentTime, connection, seq, handled); michael@0: } michael@0: michael@0: void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime, michael@0: const sp& connection, bool notify) { michael@0: #if DEBUG_DISPATCH_CYCLE michael@0: ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s", michael@0: connection->getInputChannelName(), toString(notify)); michael@0: #endif michael@0: michael@0: // Clear the dispatch queues. michael@0: drainDispatchQueueLocked(&connection->outboundQueue); michael@0: traceOutboundQueueLengthLocked(connection); michael@0: drainDispatchQueueLocked(&connection->waitQueue); michael@0: traceWaitQueueLengthLocked(connection); michael@0: michael@0: // The connection appears to be unrecoverably broken. michael@0: // Ignore already broken or zombie connections. michael@0: if (connection->status == Connection::STATUS_NORMAL) { michael@0: connection->status = Connection::STATUS_BROKEN; michael@0: michael@0: if (notify) { michael@0: // Notify other system components. michael@0: onDispatchCycleBrokenLocked(currentTime, connection); michael@0: } michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::drainDispatchQueueLocked(Queue* queue) { michael@0: while (!queue->isEmpty()) { michael@0: DispatchEntry* dispatchEntry = queue->dequeueAtHead(); michael@0: releaseDispatchEntryLocked(dispatchEntry); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) { michael@0: if (dispatchEntry->hasForegroundTarget()) { michael@0: decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry); michael@0: } michael@0: delete dispatchEntry; michael@0: } michael@0: michael@0: int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) { michael@0: InputDispatcher* d = static_cast(data); michael@0: michael@0: { // acquire lock michael@0: AutoMutex _l(d->mLock); michael@0: michael@0: ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd); michael@0: if (connectionIndex < 0) { michael@0: ALOGE("Received spurious receive callback for unknown input channel. " michael@0: "fd=%d, events=0x%x", fd, events); michael@0: return 0; // remove the callback michael@0: } michael@0: michael@0: bool notify; michael@0: sp connection = d->mConnectionsByFd.valueAt(connectionIndex); michael@0: if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) { michael@0: if (!(events & ALOOPER_EVENT_INPUT)) { michael@0: ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. " michael@0: "events=0x%x", connection->getInputChannelName(), events); michael@0: return 1; michael@0: } michael@0: michael@0: nsecs_t currentTime = now(); michael@0: bool gotOne = false; michael@0: status_t status; michael@0: for (;;) { michael@0: uint32_t seq; michael@0: bool handled; michael@0: status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled); michael@0: if (status) { michael@0: break; michael@0: } michael@0: d->finishDispatchCycleLocked(currentTime, connection, seq, handled); michael@0: gotOne = true; michael@0: } michael@0: if (gotOne) { michael@0: d->runCommandsLockedInterruptible(); michael@0: if (status == WOULD_BLOCK) { michael@0: return 1; michael@0: } michael@0: } michael@0: michael@0: notify = status != DEAD_OBJECT || !connection->monitor; michael@0: if (notify) { michael@0: ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d", michael@0: connection->getInputChannelName(), status); michael@0: } michael@0: } else { michael@0: // Monitor channels are never explicitly unregistered. michael@0: // We do it automatically when the remote endpoint is closed so don't warn michael@0: // about them. michael@0: notify = !connection->monitor; michael@0: if (notify) { michael@0: ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. " michael@0: "events=0x%x", connection->getInputChannelName(), events); michael@0: } michael@0: } michael@0: michael@0: // Unregister the channel. michael@0: d->unregisterInputChannelLocked(connection->inputChannel, notify); michael@0: return 0; // remove the callback michael@0: } // release lock michael@0: } michael@0: michael@0: void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked( michael@0: const CancelationOptions& options) { michael@0: for (size_t i = 0; i < mConnectionsByFd.size(); i++) { michael@0: synthesizeCancelationEventsForConnectionLocked( michael@0: mConnectionsByFd.valueAt(i), options); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked( michael@0: const sp& channel, const CancelationOptions& options) { michael@0: ssize_t index = getConnectionIndexLocked(channel); michael@0: if (index >= 0) { michael@0: synthesizeCancelationEventsForConnectionLocked( michael@0: mConnectionsByFd.valueAt(index), options); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::synthesizeCancelationEventsForConnectionLocked( michael@0: const sp& connection, const CancelationOptions& options) { michael@0: if (connection->status == Connection::STATUS_BROKEN) { michael@0: return; michael@0: } michael@0: michael@0: nsecs_t currentTime = now(); michael@0: michael@0: Vector cancelationEvents; michael@0: connection->inputState.synthesizeCancelationEvents(currentTime, michael@0: cancelationEvents, options); michael@0: michael@0: if (!cancelationEvents.isEmpty()) { michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync " michael@0: "with reality: %s, mode=%d.", michael@0: connection->getInputChannelName(), cancelationEvents.size(), michael@0: options.reason, options.mode); michael@0: #endif michael@0: for (size_t i = 0; i < cancelationEvents.size(); i++) { michael@0: EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i); michael@0: switch (cancelationEventEntry->type) { michael@0: case EventEntry::TYPE_KEY: michael@0: logOutboundKeyDetailsLocked("cancel - ", michael@0: static_cast(cancelationEventEntry)); michael@0: break; michael@0: case EventEntry::TYPE_MOTION: michael@0: logOutboundMotionDetailsLocked("cancel - ", michael@0: static_cast(cancelationEventEntry)); michael@0: break; michael@0: } michael@0: michael@0: InputTarget target; michael@0: sp windowHandle = getWindowHandleLocked(connection->inputChannel); michael@0: if (windowHandle != NULL) { michael@0: const InputWindowInfo* windowInfo = windowHandle->getInfo(); michael@0: target.xOffset = -windowInfo->frameLeft; michael@0: target.yOffset = -windowInfo->frameTop; michael@0: target.scaleFactor = windowInfo->scaleFactor; michael@0: } else { michael@0: target.xOffset = 0; michael@0: target.yOffset = 0; michael@0: target.scaleFactor = 1.0f; michael@0: } michael@0: target.inputChannel = connection->inputChannel; michael@0: target.flags = InputTarget::FLAG_DISPATCH_AS_IS; michael@0: michael@0: enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref michael@0: &target, InputTarget::FLAG_DISPATCH_AS_IS); michael@0: michael@0: cancelationEventEntry->release(); michael@0: } michael@0: michael@0: startDispatchCycleLocked(currentTime, connection); michael@0: } michael@0: } michael@0: michael@0: InputDispatcher::MotionEntry* michael@0: InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) { michael@0: ALOG_ASSERT(pointerIds.value != 0); michael@0: michael@0: uint32_t splitPointerIndexMap[MAX_POINTERS]; michael@0: PointerProperties splitPointerProperties[MAX_POINTERS]; michael@0: PointerCoords splitPointerCoords[MAX_POINTERS]; michael@0: michael@0: uint32_t originalPointerCount = originalMotionEntry->pointerCount; michael@0: uint32_t splitPointerCount = 0; michael@0: michael@0: for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount; michael@0: originalPointerIndex++) { michael@0: const PointerProperties& pointerProperties = michael@0: originalMotionEntry->pointerProperties[originalPointerIndex]; michael@0: uint32_t pointerId = uint32_t(pointerProperties.id); michael@0: if (pointerIds.hasBit(pointerId)) { michael@0: splitPointerIndexMap[splitPointerCount] = originalPointerIndex; michael@0: splitPointerProperties[splitPointerCount].copyFrom(pointerProperties); michael@0: splitPointerCoords[splitPointerCount].copyFrom( michael@0: originalMotionEntry->pointerCoords[originalPointerIndex]); michael@0: splitPointerCount += 1; michael@0: } michael@0: } michael@0: michael@0: if (splitPointerCount != pointerIds.count()) { michael@0: // This is bad. We are missing some of the pointers that we expected to deliver. michael@0: // Most likely this indicates that we received an ACTION_MOVE events that has michael@0: // different pointer ids than we expected based on the previous ACTION_DOWN michael@0: // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers michael@0: // in this way. michael@0: ALOGW("Dropping split motion event because the pointer count is %d but " michael@0: "we expected there to be %d pointers. This probably means we received " michael@0: "a broken sequence of pointer ids from the input device.", michael@0: splitPointerCount, pointerIds.count()); michael@0: return NULL; michael@0: } michael@0: michael@0: int32_t action = originalMotionEntry->action; michael@0: int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK; michael@0: if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN michael@0: || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) { michael@0: int32_t originalPointerIndex = getMotionEventActionPointerIndex(action); michael@0: const PointerProperties& pointerProperties = michael@0: originalMotionEntry->pointerProperties[originalPointerIndex]; michael@0: uint32_t pointerId = uint32_t(pointerProperties.id); michael@0: if (pointerIds.hasBit(pointerId)) { michael@0: if (pointerIds.count() == 1) { michael@0: // The first/last pointer went down/up. michael@0: action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN michael@0: ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP; michael@0: } else { michael@0: // A secondary pointer went down/up. michael@0: uint32_t splitPointerIndex = 0; michael@0: while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) { michael@0: splitPointerIndex += 1; michael@0: } michael@0: action = maskedAction | (splitPointerIndex michael@0: << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT); michael@0: } michael@0: } else { michael@0: // An unrelated pointer changed. michael@0: action = AMOTION_EVENT_ACTION_MOVE; michael@0: } michael@0: } michael@0: michael@0: MotionEntry* splitMotionEntry = new MotionEntry( michael@0: originalMotionEntry->eventTime, michael@0: originalMotionEntry->deviceId, michael@0: originalMotionEntry->source, michael@0: originalMotionEntry->policyFlags, michael@0: action, michael@0: originalMotionEntry->flags, michael@0: originalMotionEntry->metaState, michael@0: originalMotionEntry->buttonState, michael@0: originalMotionEntry->edgeFlags, michael@0: originalMotionEntry->xPrecision, michael@0: originalMotionEntry->yPrecision, michael@0: originalMotionEntry->downTime, michael@0: originalMotionEntry->displayId, michael@0: splitPointerCount, splitPointerProperties, splitPointerCoords); michael@0: michael@0: if (originalMotionEntry->injectionState) { michael@0: splitMotionEntry->injectionState = originalMotionEntry->injectionState; michael@0: splitMotionEntry->injectionState->refCount += 1; michael@0: } michael@0: michael@0: return splitMotionEntry; michael@0: } michael@0: michael@0: void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) { michael@0: #if DEBUG_INBOUND_EVENT_DETAILS michael@0: ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime); michael@0: #endif michael@0: michael@0: bool needWake; michael@0: { // acquire lock michael@0: AutoMutex _l(mLock); michael@0: michael@0: ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime); michael@0: needWake = enqueueInboundEventLocked(newEntry); michael@0: } // release lock michael@0: michael@0: if (needWake) { michael@0: mLooper->wake(); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::notifyKey(const NotifyKeyArgs* args) { michael@0: #if DEBUG_INBOUND_EVENT_DETAILS michael@0: ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, " michael@0: "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld", michael@0: args->eventTime, args->deviceId, args->source, args->policyFlags, michael@0: args->action, args->flags, args->keyCode, args->scanCode, michael@0: args->metaState, args->downTime); michael@0: #endif michael@0: if (!validateKeyEvent(args->action)) { michael@0: return; michael@0: } michael@0: michael@0: uint32_t policyFlags = args->policyFlags; michael@0: int32_t flags = args->flags; michael@0: int32_t metaState = args->metaState; michael@0: if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) { michael@0: policyFlags |= POLICY_FLAG_VIRTUAL; michael@0: flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY; michael@0: } michael@0: if (policyFlags & POLICY_FLAG_ALT) { michael@0: metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON; michael@0: } michael@0: if (policyFlags & POLICY_FLAG_ALT_GR) { michael@0: metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON; michael@0: } michael@0: if (policyFlags & POLICY_FLAG_SHIFT) { michael@0: metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON; michael@0: } michael@0: if (policyFlags & POLICY_FLAG_CAPS_LOCK) { michael@0: metaState |= AMETA_CAPS_LOCK_ON; michael@0: } michael@0: if (policyFlags & POLICY_FLAG_FUNCTION) { michael@0: metaState |= AMETA_FUNCTION_ON; michael@0: } michael@0: michael@0: policyFlags |= POLICY_FLAG_TRUSTED; michael@0: michael@0: KeyEvent event; michael@0: event.initialize(args->deviceId, args->source, args->action, michael@0: flags, args->keyCode, args->scanCode, metaState, 0, michael@0: args->downTime, args->eventTime); michael@0: michael@0: mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags); michael@0: michael@0: if (policyFlags & POLICY_FLAG_WOKE_HERE) { michael@0: flags |= AKEY_EVENT_FLAG_WOKE_HERE; michael@0: } michael@0: michael@0: bool needWake; michael@0: { // acquire lock michael@0: mLock.lock(); michael@0: michael@0: if (shouldSendKeyToInputFilterLocked(args)) { michael@0: mLock.unlock(); michael@0: michael@0: policyFlags |= POLICY_FLAG_FILTERED; michael@0: if (!mPolicy->filterInputEvent(&event, policyFlags)) { michael@0: return; // event was consumed by the filter michael@0: } michael@0: michael@0: mLock.lock(); michael@0: } michael@0: michael@0: int32_t repeatCount = 0; michael@0: KeyEntry* newEntry = new KeyEntry(args->eventTime, michael@0: args->deviceId, args->source, policyFlags, michael@0: args->action, flags, args->keyCode, args->scanCode, michael@0: metaState, repeatCount, args->downTime); michael@0: michael@0: needWake = enqueueInboundEventLocked(newEntry); michael@0: mLock.unlock(); michael@0: } // release lock michael@0: michael@0: if (needWake) { michael@0: mLooper->wake(); michael@0: } michael@0: } michael@0: michael@0: bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) { michael@0: return mInputFilterEnabled; michael@0: } michael@0: michael@0: void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) { michael@0: #if DEBUG_INBOUND_EVENT_DETAILS michael@0: ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, " michael@0: "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, " michael@0: "xPrecision=%f, yPrecision=%f, downTime=%lld", michael@0: args->eventTime, args->deviceId, args->source, args->policyFlags, michael@0: args->action, args->flags, args->metaState, args->buttonState, michael@0: args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime); michael@0: for (uint32_t i = 0; i < args->pointerCount; i++) { michael@0: ALOGD(" Pointer %d: id=%d, toolType=%d, " michael@0: "x=%f, y=%f, pressure=%f, size=%f, " michael@0: "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, " michael@0: "orientation=%f", michael@0: i, args->pointerProperties[i].id, michael@0: args->pointerProperties[i].toolType, michael@0: args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X), michael@0: args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y), michael@0: args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE), michael@0: args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE), michael@0: args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR), michael@0: args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR), michael@0: args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR), michael@0: args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR), michael@0: args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION)); michael@0: } michael@0: #endif michael@0: if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) { michael@0: return; michael@0: } michael@0: michael@0: uint32_t policyFlags = args->policyFlags; michael@0: policyFlags |= POLICY_FLAG_TRUSTED; michael@0: mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags); michael@0: michael@0: bool needWake; michael@0: { // acquire lock michael@0: mLock.lock(); michael@0: michael@0: if (shouldSendMotionToInputFilterLocked(args)) { michael@0: mLock.unlock(); michael@0: michael@0: MotionEvent event; michael@0: event.initialize(args->deviceId, args->source, args->action, args->flags, michael@0: args->edgeFlags, args->metaState, args->buttonState, 0, 0, michael@0: args->xPrecision, args->yPrecision, michael@0: args->downTime, args->eventTime, michael@0: args->pointerCount, args->pointerProperties, args->pointerCoords); michael@0: michael@0: policyFlags |= POLICY_FLAG_FILTERED; michael@0: if (!mPolicy->filterInputEvent(&event, policyFlags)) { michael@0: return; // event was consumed by the filter michael@0: } michael@0: michael@0: mLock.lock(); michael@0: } michael@0: michael@0: // Just enqueue a new motion event. michael@0: MotionEntry* newEntry = new MotionEntry(args->eventTime, michael@0: args->deviceId, args->source, policyFlags, michael@0: args->action, args->flags, args->metaState, args->buttonState, michael@0: args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime, michael@0: args->displayId, michael@0: args->pointerCount, args->pointerProperties, args->pointerCoords); michael@0: michael@0: needWake = enqueueInboundEventLocked(newEntry); michael@0: mLock.unlock(); michael@0: } // release lock michael@0: michael@0: if (needWake) { michael@0: mLooper->wake(); michael@0: } michael@0: } michael@0: michael@0: bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) { michael@0: // TODO: support sending secondary display events to input filter michael@0: return mInputFilterEnabled && isMainDisplay(args->displayId); michael@0: } michael@0: michael@0: void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) { michael@0: #if DEBUG_INBOUND_EVENT_DETAILS michael@0: ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x", michael@0: args->eventTime, args->policyFlags, michael@0: args->switchValues, args->switchMask); michael@0: #endif michael@0: michael@0: uint32_t policyFlags = args->policyFlags; michael@0: policyFlags |= POLICY_FLAG_TRUSTED; michael@0: mPolicy->notifySwitch(args->eventTime, michael@0: args->switchValues, args->switchMask, policyFlags); michael@0: } michael@0: michael@0: void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) { michael@0: #if DEBUG_INBOUND_EVENT_DETAILS michael@0: ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d", michael@0: args->eventTime, args->deviceId); michael@0: #endif michael@0: michael@0: bool needWake; michael@0: { // acquire lock michael@0: AutoMutex _l(mLock); michael@0: michael@0: DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId); michael@0: needWake = enqueueInboundEventLocked(newEntry); michael@0: } // release lock michael@0: michael@0: if (needWake) { michael@0: mLooper->wake(); michael@0: } michael@0: } michael@0: michael@0: int32_t InputDispatcher::injectInputEvent(const InputEvent* event, michael@0: int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis, michael@0: uint32_t policyFlags) { michael@0: #if DEBUG_INBOUND_EVENT_DETAILS michael@0: ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, " michael@0: "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x", michael@0: event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags); michael@0: #endif michael@0: michael@0: nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis); michael@0: michael@0: policyFlags |= POLICY_FLAG_INJECTED; michael@0: if (hasInjectionPermission(injectorPid, injectorUid)) { michael@0: policyFlags |= POLICY_FLAG_TRUSTED; michael@0: } michael@0: michael@0: EventEntry* firstInjectedEntry; michael@0: EventEntry* lastInjectedEntry; michael@0: switch (event->getType()) { michael@0: case AINPUT_EVENT_TYPE_KEY: { michael@0: const KeyEvent* keyEvent = static_cast(event); michael@0: int32_t action = keyEvent->getAction(); michael@0: if (! validateKeyEvent(action)) { michael@0: return INPUT_EVENT_INJECTION_FAILED; michael@0: } michael@0: michael@0: int32_t flags = keyEvent->getFlags(); michael@0: if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) { michael@0: policyFlags |= POLICY_FLAG_VIRTUAL; michael@0: } michael@0: michael@0: if (!(policyFlags & POLICY_FLAG_FILTERED)) { michael@0: mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags); michael@0: } michael@0: michael@0: if (policyFlags & POLICY_FLAG_WOKE_HERE) { michael@0: flags |= AKEY_EVENT_FLAG_WOKE_HERE; michael@0: } michael@0: michael@0: mLock.lock(); michael@0: firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(), michael@0: keyEvent->getDeviceId(), keyEvent->getSource(), michael@0: policyFlags, action, flags, michael@0: keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(), michael@0: keyEvent->getRepeatCount(), keyEvent->getDownTime()); michael@0: lastInjectedEntry = firstInjectedEntry; michael@0: break; michael@0: } michael@0: michael@0: case AINPUT_EVENT_TYPE_MOTION: { michael@0: const MotionEvent* motionEvent = static_cast(event); michael@0: int32_t displayId = ADISPLAY_ID_DEFAULT; michael@0: int32_t action = motionEvent->getAction(); michael@0: size_t pointerCount = motionEvent->getPointerCount(); michael@0: const PointerProperties* pointerProperties = motionEvent->getPointerProperties(); michael@0: if (! validateMotionEvent(action, pointerCount, pointerProperties)) { michael@0: return INPUT_EVENT_INJECTION_FAILED; michael@0: } michael@0: michael@0: if (!(policyFlags & POLICY_FLAG_FILTERED)) { michael@0: nsecs_t eventTime = motionEvent->getEventTime(); michael@0: mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags); michael@0: } michael@0: michael@0: mLock.lock(); michael@0: const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes(); michael@0: const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords(); michael@0: firstInjectedEntry = new MotionEntry(*sampleEventTimes, michael@0: motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags, michael@0: action, motionEvent->getFlags(), michael@0: motionEvent->getMetaState(), motionEvent->getButtonState(), michael@0: motionEvent->getEdgeFlags(), michael@0: motionEvent->getXPrecision(), motionEvent->getYPrecision(), michael@0: motionEvent->getDownTime(), displayId, michael@0: uint32_t(pointerCount), pointerProperties, samplePointerCoords); michael@0: lastInjectedEntry = firstInjectedEntry; michael@0: for (size_t i = motionEvent->getHistorySize(); i > 0; i--) { michael@0: sampleEventTimes += 1; michael@0: samplePointerCoords += pointerCount; michael@0: MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes, michael@0: motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags, michael@0: action, motionEvent->getFlags(), michael@0: motionEvent->getMetaState(), motionEvent->getButtonState(), michael@0: motionEvent->getEdgeFlags(), michael@0: motionEvent->getXPrecision(), motionEvent->getYPrecision(), michael@0: motionEvent->getDownTime(), displayId, michael@0: uint32_t(pointerCount), pointerProperties, samplePointerCoords); michael@0: lastInjectedEntry->next = nextInjectedEntry; michael@0: lastInjectedEntry = nextInjectedEntry; michael@0: } michael@0: break; michael@0: } michael@0: michael@0: default: michael@0: ALOGW("Cannot inject event of type %d", event->getType()); michael@0: return INPUT_EVENT_INJECTION_FAILED; michael@0: } michael@0: michael@0: InjectionState* injectionState = new InjectionState(injectorPid, injectorUid); michael@0: if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) { michael@0: injectionState->injectionIsAsync = true; michael@0: } michael@0: michael@0: injectionState->refCount += 1; michael@0: lastInjectedEntry->injectionState = injectionState; michael@0: michael@0: bool needWake = false; michael@0: for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) { michael@0: EventEntry* nextEntry = entry->next; michael@0: needWake |= enqueueInboundEventLocked(entry); michael@0: entry = nextEntry; michael@0: } michael@0: michael@0: mLock.unlock(); michael@0: michael@0: if (needWake) { michael@0: mLooper->wake(); michael@0: } michael@0: michael@0: int32_t injectionResult; michael@0: { // acquire lock michael@0: AutoMutex _l(mLock); michael@0: michael@0: if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) { michael@0: injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED; michael@0: } else { michael@0: for (;;) { michael@0: injectionResult = injectionState->injectionResult; michael@0: if (injectionResult != INPUT_EVENT_INJECTION_PENDING) { michael@0: break; michael@0: } michael@0: michael@0: nsecs_t remainingTimeout = endTime - now(); michael@0: if (remainingTimeout <= 0) { michael@0: #if DEBUG_INJECTION michael@0: ALOGD("injectInputEvent - Timed out waiting for injection result " michael@0: "to become available."); michael@0: #endif michael@0: injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT; michael@0: break; michael@0: } michael@0: michael@0: mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout); michael@0: } michael@0: michael@0: if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED michael@0: && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) { michael@0: while (injectionState->pendingForegroundDispatches != 0) { michael@0: #if DEBUG_INJECTION michael@0: ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.", michael@0: injectionState->pendingForegroundDispatches); michael@0: #endif michael@0: nsecs_t remainingTimeout = endTime - now(); michael@0: if (remainingTimeout <= 0) { michael@0: #if DEBUG_INJECTION michael@0: ALOGD("injectInputEvent - Timed out waiting for pending foreground " michael@0: "dispatches to finish."); michael@0: #endif michael@0: injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT; michael@0: break; michael@0: } michael@0: michael@0: mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout); michael@0: } michael@0: } michael@0: } michael@0: michael@0: injectionState->release(); michael@0: } // release lock michael@0: michael@0: #if DEBUG_INJECTION michael@0: ALOGD("injectInputEvent - Finished with result %d. " michael@0: "injectorPid=%d, injectorUid=%d", michael@0: injectionResult, injectorPid, injectorUid); michael@0: #endif michael@0: michael@0: return injectionResult; michael@0: } michael@0: michael@0: bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) { michael@0: return injectorUid == 0 michael@0: || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid); michael@0: } michael@0: michael@0: void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) { michael@0: InjectionState* injectionState = entry->injectionState; michael@0: if (injectionState) { michael@0: #if DEBUG_INJECTION michael@0: ALOGD("Setting input event injection result to %d. " michael@0: "injectorPid=%d, injectorUid=%d", michael@0: injectionResult, injectionState->injectorPid, injectionState->injectorUid); michael@0: #endif michael@0: michael@0: if (injectionState->injectionIsAsync michael@0: && !(entry->policyFlags & POLICY_FLAG_FILTERED)) { michael@0: // Log the outcome since the injector did not wait for the injection result. michael@0: switch (injectionResult) { michael@0: case INPUT_EVENT_INJECTION_SUCCEEDED: michael@0: ALOGV("Asynchronous input event injection succeeded."); michael@0: break; michael@0: case INPUT_EVENT_INJECTION_FAILED: michael@0: ALOGW("Asynchronous input event injection failed."); michael@0: break; michael@0: case INPUT_EVENT_INJECTION_PERMISSION_DENIED: michael@0: ALOGW("Asynchronous input event injection permission denied."); michael@0: break; michael@0: case INPUT_EVENT_INJECTION_TIMED_OUT: michael@0: ALOGW("Asynchronous input event injection timed out."); michael@0: break; michael@0: } michael@0: } michael@0: michael@0: injectionState->injectionResult = injectionResult; michael@0: mInjectionResultAvailableCondition.broadcast(); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) { michael@0: InjectionState* injectionState = entry->injectionState; michael@0: if (injectionState) { michael@0: injectionState->pendingForegroundDispatches += 1; michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) { michael@0: InjectionState* injectionState = entry->injectionState; michael@0: if (injectionState) { michael@0: injectionState->pendingForegroundDispatches -= 1; michael@0: michael@0: if (injectionState->pendingForegroundDispatches == 0) { michael@0: mInjectionSyncFinishedCondition.broadcast(); michael@0: } michael@0: } michael@0: } michael@0: michael@0: sp InputDispatcher::getWindowHandleLocked( michael@0: const sp& inputChannel) const { michael@0: size_t numWindows = mWindowHandles.size(); michael@0: for (size_t i = 0; i < numWindows; i++) { michael@0: const sp& windowHandle = mWindowHandles.itemAt(i); michael@0: if (windowHandle->getInputChannel() == inputChannel) { michael@0: return windowHandle; michael@0: } michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: bool InputDispatcher::hasWindowHandleLocked( michael@0: const sp& windowHandle) const { michael@0: size_t numWindows = mWindowHandles.size(); michael@0: for (size_t i = 0; i < numWindows; i++) { michael@0: if (mWindowHandles.itemAt(i) == windowHandle) { michael@0: return true; michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: void InputDispatcher::setInputWindows(const Vector >& inputWindowHandles) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("setInputWindows"); michael@0: #endif michael@0: { // acquire lock michael@0: AutoMutex _l(mLock); michael@0: michael@0: Vector > oldWindowHandles = mWindowHandles; michael@0: mWindowHandles = inputWindowHandles; michael@0: michael@0: sp newFocusedWindowHandle; michael@0: bool foundHoveredWindow = false; michael@0: for (size_t i = 0; i < mWindowHandles.size(); i++) { michael@0: const sp& windowHandle = mWindowHandles.itemAt(i); michael@0: if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) { michael@0: mWindowHandles.removeAt(i--); michael@0: continue; michael@0: } michael@0: if (windowHandle->getInfo()->hasFocus) { michael@0: newFocusedWindowHandle = windowHandle; michael@0: } michael@0: if (windowHandle == mLastHoverWindowHandle) { michael@0: foundHoveredWindow = true; michael@0: } michael@0: } michael@0: michael@0: if (!foundHoveredWindow) { michael@0: mLastHoverWindowHandle = NULL; michael@0: } michael@0: michael@0: if (mFocusedWindowHandle != newFocusedWindowHandle) { michael@0: if (mFocusedWindowHandle != NULL) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Focus left window: %s", michael@0: mFocusedWindowHandle->getName().string()); michael@0: #endif michael@0: sp focusedInputChannel = mFocusedWindowHandle->getInputChannel(); michael@0: if (focusedInputChannel != NULL) { michael@0: CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, michael@0: "focus left window"); michael@0: synthesizeCancelationEventsForInputChannelLocked( michael@0: focusedInputChannel, options); michael@0: } michael@0: } michael@0: if (newFocusedWindowHandle != NULL) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Focus entered window: %s", michael@0: newFocusedWindowHandle->getName().string()); michael@0: #endif michael@0: } michael@0: mFocusedWindowHandle = newFocusedWindowHandle; michael@0: } michael@0: michael@0: for (size_t i = 0; i < mTouchState.windows.size(); i++) { michael@0: TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i); michael@0: if (!hasWindowHandleLocked(touchedWindow.windowHandle)) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Touched window was removed: %s", michael@0: touchedWindow.windowHandle->getName().string()); michael@0: #endif michael@0: sp touchedInputChannel = michael@0: touchedWindow.windowHandle->getInputChannel(); michael@0: if (touchedInputChannel != NULL) { michael@0: CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, michael@0: "touched window was removed"); michael@0: synthesizeCancelationEventsForInputChannelLocked( michael@0: touchedInputChannel, options); michael@0: } michael@0: mTouchState.windows.removeAt(i--); michael@0: } michael@0: } michael@0: michael@0: // Release information for windows that are no longer present. michael@0: // This ensures that unused input channels are released promptly. michael@0: // Otherwise, they might stick around until the window handle is destroyed michael@0: // which might not happen until the next GC. michael@0: for (size_t i = 0; i < oldWindowHandles.size(); i++) { michael@0: const sp& oldWindowHandle = oldWindowHandles.itemAt(i); michael@0: if (!hasWindowHandleLocked(oldWindowHandle)) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Window went away: %s", oldWindowHandle->getName().string()); michael@0: #endif michael@0: oldWindowHandle->releaseInfo(); michael@0: } michael@0: } michael@0: } // release lock michael@0: michael@0: // Wake up poll loop since it may need to make new input dispatching choices. michael@0: mLooper->wake(); michael@0: } michael@0: michael@0: void InputDispatcher::setFocusedApplication( michael@0: const sp& inputApplicationHandle) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("setFocusedApplication"); michael@0: #endif michael@0: { // acquire lock michael@0: AutoMutex _l(mLock); michael@0: michael@0: if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) { michael@0: if (mFocusedApplicationHandle != inputApplicationHandle) { michael@0: if (mFocusedApplicationHandle != NULL) { michael@0: resetANRTimeoutsLocked(); michael@0: mFocusedApplicationHandle->releaseInfo(); michael@0: } michael@0: mFocusedApplicationHandle = inputApplicationHandle; michael@0: } michael@0: } else if (mFocusedApplicationHandle != NULL) { michael@0: resetANRTimeoutsLocked(); michael@0: mFocusedApplicationHandle->releaseInfo(); michael@0: mFocusedApplicationHandle.clear(); michael@0: } michael@0: michael@0: #if DEBUG_FOCUS michael@0: //logDispatchStateLocked(); michael@0: #endif michael@0: } // release lock michael@0: michael@0: // Wake up poll loop since it may need to make new input dispatching choices. michael@0: mLooper->wake(); michael@0: } michael@0: michael@0: void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen); michael@0: #endif michael@0: michael@0: bool changed; michael@0: { // acquire lock michael@0: AutoMutex _l(mLock); michael@0: michael@0: if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) { michael@0: if (mDispatchFrozen && !frozen) { michael@0: resetANRTimeoutsLocked(); michael@0: } michael@0: michael@0: if (mDispatchEnabled && !enabled) { michael@0: resetAndDropEverythingLocked("dispatcher is being disabled"); michael@0: } michael@0: michael@0: mDispatchEnabled = enabled; michael@0: mDispatchFrozen = frozen; michael@0: changed = true; michael@0: } else { michael@0: changed = false; michael@0: } michael@0: michael@0: #if DEBUG_FOCUS michael@0: //logDispatchStateLocked(); michael@0: #endif michael@0: } // release lock michael@0: michael@0: if (changed) { michael@0: // Wake up poll loop since it may need to make new input dispatching choices. michael@0: mLooper->wake(); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::setInputFilterEnabled(bool enabled) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("setInputFilterEnabled: enabled=%d", enabled); michael@0: #endif michael@0: michael@0: { // acquire lock michael@0: AutoMutex _l(mLock); michael@0: michael@0: if (mInputFilterEnabled == enabled) { michael@0: return; michael@0: } michael@0: michael@0: mInputFilterEnabled = enabled; michael@0: resetAndDropEverythingLocked("input filter is being enabled or disabled"); michael@0: } // release lock michael@0: michael@0: // Wake up poll loop since there might be work to do to drop everything. michael@0: mLooper->wake(); michael@0: } michael@0: michael@0: bool InputDispatcher::transferTouchFocus(const sp& fromChannel, michael@0: const sp& toChannel) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s", michael@0: fromChannel->getName().string(), toChannel->getName().string()); michael@0: #endif michael@0: { // acquire lock michael@0: AutoMutex _l(mLock); michael@0: michael@0: sp fromWindowHandle = getWindowHandleLocked(fromChannel); michael@0: sp toWindowHandle = getWindowHandleLocked(toChannel); michael@0: if (fromWindowHandle == NULL || toWindowHandle == NULL) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Cannot transfer focus because from or to window not found."); michael@0: #endif michael@0: return false; michael@0: } michael@0: if (fromWindowHandle == toWindowHandle) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Trivial transfer to same window."); michael@0: #endif michael@0: return true; michael@0: } michael@0: if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Cannot transfer focus because windows are on different displays."); michael@0: #endif michael@0: return false; michael@0: } michael@0: michael@0: bool found = false; michael@0: for (size_t i = 0; i < mTouchState.windows.size(); i++) { michael@0: const TouchedWindow& touchedWindow = mTouchState.windows[i]; michael@0: if (touchedWindow.windowHandle == fromWindowHandle) { michael@0: int32_t oldTargetFlags = touchedWindow.targetFlags; michael@0: BitSet32 pointerIds = touchedWindow.pointerIds; michael@0: michael@0: mTouchState.windows.removeAt(i); michael@0: michael@0: int32_t newTargetFlags = oldTargetFlags michael@0: & (InputTarget::FLAG_FOREGROUND michael@0: | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS); michael@0: mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds); michael@0: michael@0: found = true; michael@0: break; michael@0: } michael@0: } michael@0: michael@0: if (! found) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Focus transfer failed because from window did not have focus."); michael@0: #endif michael@0: return false; michael@0: } michael@0: michael@0: ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel); michael@0: ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel); michael@0: if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) { michael@0: sp fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex); michael@0: sp toConnection = mConnectionsByFd.valueAt(toConnectionIndex); michael@0: michael@0: fromConnection->inputState.copyPointerStateTo(toConnection->inputState); michael@0: CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, michael@0: "transferring touch focus from this window to another window"); michael@0: synthesizeCancelationEventsForConnectionLocked(fromConnection, options); michael@0: } michael@0: michael@0: #if DEBUG_FOCUS michael@0: logDispatchStateLocked(); michael@0: #endif michael@0: } // release lock michael@0: michael@0: // Wake up poll loop since it may need to make new input dispatching choices. michael@0: mLooper->wake(); michael@0: return true; michael@0: } michael@0: michael@0: void InputDispatcher::resetAndDropEverythingLocked(const char* reason) { michael@0: #if DEBUG_FOCUS michael@0: ALOGD("Resetting and dropping all events (%s).", reason); michael@0: #endif michael@0: michael@0: CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason); michael@0: synthesizeCancelationEventsForAllConnectionsLocked(options); michael@0: michael@0: resetKeyRepeatLocked(); michael@0: releasePendingEventLocked(); michael@0: drainInboundQueueLocked(); michael@0: resetANRTimeoutsLocked(); michael@0: michael@0: mTouchState.reset(); michael@0: mLastHoverWindowHandle.clear(); michael@0: } michael@0: michael@0: void InputDispatcher::logDispatchStateLocked() { michael@0: String8 dump; michael@0: dumpDispatchStateLocked(dump); michael@0: michael@0: char* text = dump.lockBuffer(dump.size()); michael@0: char* start = text; michael@0: while (*start != '\0') { michael@0: char* end = strchr(start, '\n'); michael@0: if (*end == '\n') { michael@0: *(end++) = '\0'; michael@0: } michael@0: ALOGD("%s", start); michael@0: start = end; michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::dumpDispatchStateLocked(String8& dump) { michael@0: dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled); michael@0: dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen); michael@0: michael@0: if (mFocusedApplicationHandle != NULL) { michael@0: dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n", michael@0: mFocusedApplicationHandle->getName().string(), michael@0: mFocusedApplicationHandle->getDispatchingTimeout( michael@0: DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0); michael@0: } else { michael@0: dump.append(INDENT "FocusedApplication: \n"); michael@0: } michael@0: dump.appendFormat(INDENT "FocusedWindow: name='%s'\n", michael@0: mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : ""); michael@0: michael@0: dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down)); michael@0: dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split)); michael@0: dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId); michael@0: dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source); michael@0: dump.appendFormat(INDENT "TouchDisplayId: %d\n", mTouchState.displayId); michael@0: if (!mTouchState.windows.isEmpty()) { michael@0: dump.append(INDENT "TouchedWindows:\n"); michael@0: for (size_t i = 0; i < mTouchState.windows.size(); i++) { michael@0: const TouchedWindow& touchedWindow = mTouchState.windows[i]; michael@0: dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n", michael@0: i, touchedWindow.windowHandle->getName().string(), michael@0: touchedWindow.pointerIds.value, michael@0: touchedWindow.targetFlags); michael@0: } michael@0: } else { michael@0: dump.append(INDENT "TouchedWindows: \n"); michael@0: } michael@0: michael@0: if (!mWindowHandles.isEmpty()) { michael@0: dump.append(INDENT "Windows:\n"); michael@0: for (size_t i = 0; i < mWindowHandles.size(); i++) { michael@0: const sp& windowHandle = mWindowHandles.itemAt(i); michael@0: const InputWindowInfo* windowInfo = windowHandle->getInfo(); michael@0: michael@0: dump.appendFormat(INDENT2 "%d: name='%s', displayId=%d, " michael@0: "paused=%s, hasFocus=%s, hasWallpaper=%s, " michael@0: "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, " michael@0: "frame=[%d,%d][%d,%d], scale=%f, " michael@0: "touchableRegion=", michael@0: i, windowInfo->name.string(), windowInfo->displayId, michael@0: toString(windowInfo->paused), michael@0: toString(windowInfo->hasFocus), michael@0: toString(windowInfo->hasWallpaper), michael@0: toString(windowInfo->visible), michael@0: toString(windowInfo->canReceiveKeys), michael@0: windowInfo->layoutParamsFlags, windowInfo->layoutParamsType, michael@0: windowInfo->layer, michael@0: windowInfo->frameLeft, windowInfo->frameTop, michael@0: windowInfo->frameRight, windowInfo->frameBottom, michael@0: windowInfo->scaleFactor); michael@0: dumpRegion(dump, windowInfo->touchableRegion); michael@0: dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures); michael@0: dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n", michael@0: windowInfo->ownerPid, windowInfo->ownerUid, michael@0: windowInfo->dispatchingTimeout / 1000000.0); michael@0: } michael@0: } else { michael@0: dump.append(INDENT "Windows: \n"); michael@0: } michael@0: michael@0: if (!mMonitoringChannels.isEmpty()) { michael@0: dump.append(INDENT "MonitoringChannels:\n"); michael@0: for (size_t i = 0; i < mMonitoringChannels.size(); i++) { michael@0: const sp& channel = mMonitoringChannels[i]; michael@0: dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string()); michael@0: } michael@0: } else { michael@0: dump.append(INDENT "MonitoringChannels: \n"); michael@0: } michael@0: michael@0: nsecs_t currentTime = now(); michael@0: michael@0: if (!mInboundQueue.isEmpty()) { michael@0: dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count()); michael@0: for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) { michael@0: dump.append(INDENT2); michael@0: entry->appendDescription(dump); michael@0: dump.appendFormat(", age=%0.1fms\n", michael@0: (currentTime - entry->eventTime) * 0.000001f); michael@0: } michael@0: } else { michael@0: dump.append(INDENT "InboundQueue: \n"); michael@0: } michael@0: michael@0: if (!mConnectionsByFd.isEmpty()) { michael@0: dump.append(INDENT "Connections:\n"); michael@0: for (size_t i = 0; i < mConnectionsByFd.size(); i++) { michael@0: const sp& connection = mConnectionsByFd.valueAt(i); michael@0: dump.appendFormat(INDENT2 "%d: channelName='%s', windowName='%s', " michael@0: "status=%s, monitor=%s, inputPublisherBlocked=%s\n", michael@0: i, connection->getInputChannelName(), connection->getWindowName(), michael@0: connection->getStatusLabel(), toString(connection->monitor), michael@0: toString(connection->inputPublisherBlocked)); michael@0: michael@0: if (!connection->outboundQueue.isEmpty()) { michael@0: dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n", michael@0: connection->outboundQueue.count()); michael@0: for (DispatchEntry* entry = connection->outboundQueue.head; entry; michael@0: entry = entry->next) { michael@0: dump.append(INDENT4); michael@0: entry->eventEntry->appendDescription(dump); michael@0: dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n", michael@0: entry->targetFlags, entry->resolvedAction, michael@0: (currentTime - entry->eventEntry->eventTime) * 0.000001f); michael@0: } michael@0: } else { michael@0: dump.append(INDENT3 "OutboundQueue: \n"); michael@0: } michael@0: michael@0: if (!connection->waitQueue.isEmpty()) { michael@0: dump.appendFormat(INDENT3 "WaitQueue: length=%u\n", michael@0: connection->waitQueue.count()); michael@0: for (DispatchEntry* entry = connection->waitQueue.head; entry; michael@0: entry = entry->next) { michael@0: dump.append(INDENT4); michael@0: entry->eventEntry->appendDescription(dump); michael@0: dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, " michael@0: "age=%0.1fms, wait=%0.1fms\n", michael@0: entry->targetFlags, entry->resolvedAction, michael@0: (currentTime - entry->eventEntry->eventTime) * 0.000001f, michael@0: (currentTime - entry->deliveryTime) * 0.000001f); michael@0: } michael@0: } else { michael@0: dump.append(INDENT3 "WaitQueue: \n"); michael@0: } michael@0: } michael@0: } else { michael@0: dump.append(INDENT "Connections: \n"); michael@0: } michael@0: michael@0: if (isAppSwitchPendingLocked()) { michael@0: dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n", michael@0: (mAppSwitchDueTime - now()) / 1000000.0); michael@0: } else { michael@0: dump.append(INDENT "AppSwitch: not pending\n"); michael@0: } michael@0: michael@0: dump.append(INDENT "Configuration:\n"); michael@0: dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n", michael@0: mConfig.keyRepeatDelay * 0.000001f); michael@0: dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n", michael@0: mConfig.keyRepeatTimeout * 0.000001f); michael@0: } michael@0: michael@0: status_t InputDispatcher::registerInputChannel(const sp& inputChannel, michael@0: const sp& inputWindowHandle, bool monitor) { michael@0: #if DEBUG_REGISTRATION michael@0: ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(), michael@0: toString(monitor)); michael@0: #endif michael@0: michael@0: { // acquire lock michael@0: AutoMutex _l(mLock); michael@0: michael@0: if (getConnectionIndexLocked(inputChannel) >= 0) { michael@0: ALOGW("Attempted to register already registered input channel '%s'", michael@0: inputChannel->getName().string()); michael@0: return BAD_VALUE; michael@0: } michael@0: michael@0: sp connection = new Connection(inputChannel, inputWindowHandle, monitor); michael@0: michael@0: int fd = inputChannel->getFd(); michael@0: mConnectionsByFd.add(fd, connection); michael@0: michael@0: if (monitor) { michael@0: mMonitoringChannels.push(inputChannel); michael@0: } michael@0: michael@0: mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this); michael@0: } // release lock michael@0: michael@0: // Wake the looper because some connections have changed. michael@0: mLooper->wake(); michael@0: return OK; michael@0: } michael@0: michael@0: status_t InputDispatcher::unregisterInputChannel(const sp& inputChannel) { michael@0: #if DEBUG_REGISTRATION michael@0: ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string()); michael@0: #endif michael@0: michael@0: { // acquire lock michael@0: AutoMutex _l(mLock); michael@0: michael@0: status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/); michael@0: if (status) { michael@0: return status; michael@0: } michael@0: } // release lock michael@0: michael@0: // Wake the poll loop because removing the connection may have changed the current michael@0: // synchronization state. michael@0: mLooper->wake(); michael@0: return OK; michael@0: } michael@0: michael@0: status_t InputDispatcher::unregisterInputChannelLocked(const sp& inputChannel, michael@0: bool notify) { michael@0: ssize_t connectionIndex = getConnectionIndexLocked(inputChannel); michael@0: if (connectionIndex < 0) { michael@0: ALOGW("Attempted to unregister already unregistered input channel '%s'", michael@0: inputChannel->getName().string()); michael@0: return BAD_VALUE; michael@0: } michael@0: michael@0: sp connection = mConnectionsByFd.valueAt(connectionIndex); michael@0: mConnectionsByFd.removeItemsAt(connectionIndex); michael@0: michael@0: if (connection->monitor) { michael@0: removeMonitorChannelLocked(inputChannel); michael@0: } michael@0: michael@0: mLooper->removeFd(inputChannel->getFd()); michael@0: michael@0: nsecs_t currentTime = now(); michael@0: abortBrokenDispatchCycleLocked(currentTime, connection, notify); michael@0: michael@0: connection->status = Connection::STATUS_ZOMBIE; michael@0: return OK; michael@0: } michael@0: michael@0: void InputDispatcher::removeMonitorChannelLocked(const sp& inputChannel) { michael@0: for (size_t i = 0; i < mMonitoringChannels.size(); i++) { michael@0: if (mMonitoringChannels[i] == inputChannel) { michael@0: mMonitoringChannels.removeAt(i); michael@0: break; michael@0: } michael@0: } michael@0: } michael@0: michael@0: ssize_t InputDispatcher::getConnectionIndexLocked(const sp& inputChannel) { michael@0: ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd()); michael@0: if (connectionIndex >= 0) { michael@0: sp connection = mConnectionsByFd.valueAt(connectionIndex); michael@0: if (connection->inputChannel.get() == inputChannel.get()) { michael@0: return connectionIndex; michael@0: } michael@0: } michael@0: michael@0: return -1; michael@0: } michael@0: michael@0: void InputDispatcher::onDispatchCycleFinishedLocked( michael@0: nsecs_t currentTime, const sp& connection, uint32_t seq, bool handled) { michael@0: CommandEntry* commandEntry = postCommandLocked( michael@0: & InputDispatcher::doDispatchCycleFinishedLockedInterruptible); michael@0: commandEntry->connection = connection; michael@0: commandEntry->eventTime = currentTime; michael@0: commandEntry->seq = seq; michael@0: commandEntry->handled = handled; michael@0: } michael@0: michael@0: void InputDispatcher::onDispatchCycleBrokenLocked( michael@0: nsecs_t currentTime, const sp& connection) { michael@0: ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!", michael@0: connection->getInputChannelName()); michael@0: michael@0: CommandEntry* commandEntry = postCommandLocked( michael@0: & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible); michael@0: commandEntry->connection = connection; michael@0: } michael@0: michael@0: void InputDispatcher::onANRLocked( michael@0: nsecs_t currentTime, const sp& applicationHandle, michael@0: const sp& windowHandle, michael@0: nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) { michael@0: float dispatchLatency = (currentTime - eventTime) * 0.000001f; michael@0: float waitDuration = (currentTime - waitStartTime) * 0.000001f; michael@0: ALOGI("Application is not responding: %s. " michael@0: "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s", michael@0: getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(), michael@0: dispatchLatency, waitDuration, reason); michael@0: michael@0: // Capture a record of the InputDispatcher state at the time of the ANR. michael@0: time_t t = time(NULL); michael@0: struct tm tm; michael@0: localtime_r(&t, &tm); michael@0: char timestr[64]; michael@0: strftime(timestr, sizeof(timestr), "%F %T", &tm); michael@0: mLastANRState.clear(); michael@0: mLastANRState.append(INDENT "ANR:\n"); michael@0: mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr); michael@0: mLastANRState.appendFormat(INDENT2 "Window: %s\n", michael@0: getApplicationWindowLabelLocked(applicationHandle, windowHandle).string()); michael@0: mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency); michael@0: mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration); michael@0: mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason); michael@0: dumpDispatchStateLocked(mLastANRState); michael@0: michael@0: CommandEntry* commandEntry = postCommandLocked( michael@0: & InputDispatcher::doNotifyANRLockedInterruptible); michael@0: commandEntry->inputApplicationHandle = applicationHandle; michael@0: commandEntry->inputWindowHandle = windowHandle; michael@0: } michael@0: michael@0: void InputDispatcher::doNotifyConfigurationChangedInterruptible( michael@0: CommandEntry* commandEntry) { michael@0: mLock.unlock(); michael@0: michael@0: mPolicy->notifyConfigurationChanged(commandEntry->eventTime); michael@0: michael@0: mLock.lock(); michael@0: } michael@0: michael@0: void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible( michael@0: CommandEntry* commandEntry) { michael@0: sp connection = commandEntry->connection; michael@0: michael@0: if (connection->status != Connection::STATUS_ZOMBIE) { michael@0: mLock.unlock(); michael@0: michael@0: mPolicy->notifyInputChannelBroken(connection->inputWindowHandle); michael@0: michael@0: mLock.lock(); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::doNotifyANRLockedInterruptible( michael@0: CommandEntry* commandEntry) { michael@0: mLock.unlock(); michael@0: michael@0: nsecs_t newTimeout = mPolicy->notifyANR( michael@0: commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle); michael@0: michael@0: mLock.lock(); michael@0: michael@0: resumeAfterTargetsNotReadyTimeoutLocked(newTimeout, michael@0: commandEntry->inputWindowHandle != NULL michael@0: ? commandEntry->inputWindowHandle->getInputChannel() : NULL); michael@0: } michael@0: michael@0: void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible( michael@0: CommandEntry* commandEntry) { michael@0: KeyEntry* entry = commandEntry->keyEntry; michael@0: michael@0: KeyEvent event; michael@0: initializeKeyEvent(&event, entry); michael@0: michael@0: mLock.unlock(); michael@0: michael@0: nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle, michael@0: &event, entry->policyFlags); michael@0: michael@0: mLock.lock(); michael@0: michael@0: if (delay < 0) { michael@0: entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP; michael@0: } else if (!delay) { michael@0: entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE; michael@0: } else { michael@0: entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER; michael@0: entry->interceptKeyWakeupTime = now() + delay; michael@0: } michael@0: entry->release(); michael@0: } michael@0: michael@0: void InputDispatcher::doDispatchCycleFinishedLockedInterruptible( michael@0: CommandEntry* commandEntry) { michael@0: sp connection = commandEntry->connection; michael@0: nsecs_t finishTime = commandEntry->eventTime; michael@0: uint32_t seq = commandEntry->seq; michael@0: bool handled = commandEntry->handled; michael@0: michael@0: // Handle post-event policy actions. michael@0: DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq); michael@0: if (dispatchEntry) { michael@0: nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime; michael@0: if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) { michael@0: String8 msg; michael@0: msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ", michael@0: connection->getWindowName(), eventDuration * 0.000001f); michael@0: dispatchEntry->eventEntry->appendDescription(msg); michael@0: ALOGI("%s", msg.string()); michael@0: } michael@0: michael@0: bool restartEvent; michael@0: if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) { michael@0: KeyEntry* keyEntry = static_cast(dispatchEntry->eventEntry); michael@0: restartEvent = afterKeyEventLockedInterruptible(connection, michael@0: dispatchEntry, keyEntry, handled); michael@0: } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) { michael@0: MotionEntry* motionEntry = static_cast(dispatchEntry->eventEntry); michael@0: restartEvent = afterMotionEventLockedInterruptible(connection, michael@0: dispatchEntry, motionEntry, handled); michael@0: } else { michael@0: restartEvent = false; michael@0: } michael@0: michael@0: // Dequeue the event and start the next cycle. michael@0: // Note that because the lock might have been released, it is possible that the michael@0: // contents of the wait queue to have been drained, so we need to double-check michael@0: // a few things. michael@0: if (dispatchEntry == connection->findWaitQueueEntry(seq)) { michael@0: connection->waitQueue.dequeue(dispatchEntry); michael@0: traceWaitQueueLengthLocked(connection); michael@0: if (restartEvent && connection->status == Connection::STATUS_NORMAL) { michael@0: connection->outboundQueue.enqueueAtHead(dispatchEntry); michael@0: traceOutboundQueueLengthLocked(connection); michael@0: } else { michael@0: releaseDispatchEntryLocked(dispatchEntry); michael@0: } michael@0: } michael@0: michael@0: // Start the next dispatch cycle for this connection. michael@0: startDispatchCycleLocked(now(), connection); michael@0: } michael@0: } michael@0: michael@0: bool InputDispatcher::afterKeyEventLockedInterruptible(const sp& connection, michael@0: DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) { michael@0: if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) { michael@0: // Get the fallback key state. michael@0: // Clear it out after dispatching the UP. michael@0: int32_t originalKeyCode = keyEntry->keyCode; michael@0: int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode); michael@0: if (keyEntry->action == AKEY_EVENT_ACTION_UP) { michael@0: connection->inputState.removeFallbackKey(originalKeyCode); michael@0: } michael@0: michael@0: if (handled || !dispatchEntry->hasForegroundTarget()) { michael@0: // If the application handles the original key for which we previously michael@0: // generated a fallback or if the window is not a foreground window, michael@0: // then cancel the associated fallback key, if any. michael@0: if (fallbackKeyCode != -1) { michael@0: // Dispatch the unhandled key to the policy with the cancel flag. michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("Unhandled key event: Asking policy to cancel fallback action. " michael@0: "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x", michael@0: keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, michael@0: keyEntry->policyFlags); michael@0: #endif michael@0: KeyEvent event; michael@0: initializeKeyEvent(&event, keyEntry); michael@0: event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED); michael@0: michael@0: mLock.unlock(); michael@0: michael@0: mPolicy->dispatchUnhandledKey(connection->inputWindowHandle, michael@0: &event, keyEntry->policyFlags, &event); michael@0: michael@0: mLock.lock(); michael@0: michael@0: // Cancel the fallback key. michael@0: if (fallbackKeyCode != AKEYCODE_UNKNOWN) { michael@0: CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS, michael@0: "application handled the original non-fallback key " michael@0: "or is no longer a foreground target, " michael@0: "canceling previously dispatched fallback key"); michael@0: options.keyCode = fallbackKeyCode; michael@0: synthesizeCancelationEventsForConnectionLocked(connection, options); michael@0: } michael@0: connection->inputState.removeFallbackKey(originalKeyCode); michael@0: } michael@0: } else { michael@0: // If the application did not handle a non-fallback key, first check michael@0: // that we are in a good state to perform unhandled key event processing michael@0: // Then ask the policy what to do with it. michael@0: bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN michael@0: && keyEntry->repeatCount == 0; michael@0: if (fallbackKeyCode == -1 && !initialDown) { michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("Unhandled key event: Skipping unhandled key event processing " michael@0: "since this is not an initial down. " michael@0: "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x", michael@0: originalKeyCode, keyEntry->action, keyEntry->repeatCount, michael@0: keyEntry->policyFlags); michael@0: #endif michael@0: return false; michael@0: } michael@0: michael@0: // Dispatch the unhandled key to the policy. michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("Unhandled key event: Asking policy to perform fallback action. " michael@0: "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x", michael@0: keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount, michael@0: keyEntry->policyFlags); michael@0: #endif michael@0: KeyEvent event; michael@0: initializeKeyEvent(&event, keyEntry); michael@0: michael@0: mLock.unlock(); michael@0: michael@0: bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle, michael@0: &event, keyEntry->policyFlags, &event); michael@0: michael@0: mLock.lock(); michael@0: michael@0: if (connection->status != Connection::STATUS_NORMAL) { michael@0: connection->inputState.removeFallbackKey(originalKeyCode); michael@0: return false; michael@0: } michael@0: michael@0: // Latch the fallback keycode for this key on an initial down. michael@0: // The fallback keycode cannot change at any other point in the lifecycle. michael@0: if (initialDown) { michael@0: if (fallback) { michael@0: fallbackKeyCode = event.getKeyCode(); michael@0: } else { michael@0: fallbackKeyCode = AKEYCODE_UNKNOWN; michael@0: } michael@0: connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode); michael@0: } michael@0: michael@0: ALOG_ASSERT(fallbackKeyCode != -1); michael@0: michael@0: // Cancel the fallback key if the policy decides not to send it anymore. michael@0: // We will continue to dispatch the key to the policy but we will no michael@0: // longer dispatch a fallback key to the application. michael@0: if (fallbackKeyCode != AKEYCODE_UNKNOWN michael@0: && (!fallback || fallbackKeyCode != event.getKeyCode())) { michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: if (fallback) { michael@0: ALOGD("Unhandled key event: Policy requested to send key %d" michael@0: "as a fallback for %d, but on the DOWN it had requested " michael@0: "to send %d instead. Fallback canceled.", michael@0: event.getKeyCode(), originalKeyCode, fallbackKeyCode); michael@0: } else { michael@0: ALOGD("Unhandled key event: Policy did not request fallback for %d, " michael@0: "but on the DOWN it had requested to send %d. " michael@0: "Fallback canceled.", michael@0: originalKeyCode, fallbackKeyCode); michael@0: } michael@0: #endif michael@0: michael@0: CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS, michael@0: "canceling fallback, policy no longer desires it"); michael@0: options.keyCode = fallbackKeyCode; michael@0: synthesizeCancelationEventsForConnectionLocked(connection, options); michael@0: michael@0: fallback = false; michael@0: fallbackKeyCode = AKEYCODE_UNKNOWN; michael@0: if (keyEntry->action != AKEY_EVENT_ACTION_UP) { michael@0: connection->inputState.setFallbackKey(originalKeyCode, michael@0: fallbackKeyCode); michael@0: } michael@0: } michael@0: michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: { michael@0: String8 msg; michael@0: const KeyedVector& fallbackKeys = michael@0: connection->inputState.getFallbackKeys(); michael@0: for (size_t i = 0; i < fallbackKeys.size(); i++) { michael@0: msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i), michael@0: fallbackKeys.valueAt(i)); michael@0: } michael@0: ALOGD("Unhandled key event: %d currently tracked fallback keys%s.", michael@0: fallbackKeys.size(), msg.string()); michael@0: } michael@0: #endif michael@0: michael@0: if (fallback) { michael@0: // Restart the dispatch cycle using the fallback key. michael@0: keyEntry->eventTime = event.getEventTime(); michael@0: keyEntry->deviceId = event.getDeviceId(); michael@0: keyEntry->source = event.getSource(); michael@0: keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK; michael@0: keyEntry->keyCode = fallbackKeyCode; michael@0: keyEntry->scanCode = event.getScanCode(); michael@0: keyEntry->metaState = event.getMetaState(); michael@0: keyEntry->repeatCount = event.getRepeatCount(); michael@0: keyEntry->downTime = event.getDownTime(); michael@0: keyEntry->syntheticRepeat = false; michael@0: michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("Unhandled key event: Dispatching fallback key. " michael@0: "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x", michael@0: originalKeyCode, fallbackKeyCode, keyEntry->metaState); michael@0: #endif michael@0: return true; // restart the event michael@0: } else { michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("Unhandled key event: No fallback key."); michael@0: #endif michael@0: } michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: bool InputDispatcher::afterMotionEventLockedInterruptible(const sp& connection, michael@0: DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) { michael@0: return false; michael@0: } michael@0: michael@0: void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) { michael@0: mLock.unlock(); michael@0: michael@0: mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType); michael@0: michael@0: mLock.lock(); michael@0: } michael@0: michael@0: void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) { michael@0: event->initialize(entry->deviceId, entry->source, entry->action, entry->flags, michael@0: entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount, michael@0: entry->downTime, entry->eventTime); michael@0: } michael@0: michael@0: void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry, michael@0: int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) { michael@0: // TODO Write some statistics about how long we spend waiting. michael@0: } michael@0: michael@0: void InputDispatcher::traceInboundQueueLengthLocked() { michael@0: #ifdef HAVE_ANDROID_OS michael@0: if (ATRACE_ENABLED()) { michael@0: ATRACE_INT("iq", mInboundQueue.count()); michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: void InputDispatcher::traceOutboundQueueLengthLocked(const sp& connection) { michael@0: #ifdef HAVE_ANDROID_OS michael@0: if (ATRACE_ENABLED()) { michael@0: char counterName[40]; michael@0: snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName()); michael@0: ATRACE_INT(counterName, connection->outboundQueue.count()); michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: void InputDispatcher::traceWaitQueueLengthLocked(const sp& connection) { michael@0: #ifdef HAVE_ANDROID_OS michael@0: if (ATRACE_ENABLED()) { michael@0: char counterName[40]; michael@0: snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName()); michael@0: ATRACE_INT(counterName, connection->waitQueue.count()); michael@0: } michael@0: #endif michael@0: } michael@0: michael@0: void InputDispatcher::dump(String8& dump) { michael@0: AutoMutex _l(mLock); michael@0: michael@0: dump.append("Input Dispatcher State:\n"); michael@0: dumpDispatchStateLocked(dump); michael@0: michael@0: if (!mLastANRState.isEmpty()) { michael@0: dump.append("\nInput Dispatcher State at time of last ANR:\n"); michael@0: dump.append(mLastANRState); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::monitor() { michael@0: // Acquire and release the lock to ensure that the dispatcher has not deadlocked. michael@0: mLock.lock(); michael@0: mLooper->wake(); michael@0: mDispatcherIsAliveCondition.wait(mLock); michael@0: mLock.unlock(); michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcher::Queue --- michael@0: michael@0: template michael@0: uint32_t InputDispatcher::Queue::count() const { michael@0: uint32_t result = 0; michael@0: for (const T* entry = head; entry; entry = entry->next) { michael@0: result += 1; michael@0: } michael@0: return result; michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcher::InjectionState --- michael@0: michael@0: InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) : michael@0: refCount(1), michael@0: injectorPid(injectorPid), injectorUid(injectorUid), michael@0: injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false), michael@0: pendingForegroundDispatches(0) { michael@0: } michael@0: michael@0: InputDispatcher::InjectionState::~InjectionState() { michael@0: } michael@0: michael@0: void InputDispatcher::InjectionState::release() { michael@0: refCount -= 1; michael@0: if (refCount == 0) { michael@0: delete this; michael@0: } else { michael@0: ALOG_ASSERT(refCount > 0); michael@0: } michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcher::EventEntry --- michael@0: michael@0: InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) : michael@0: refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags), michael@0: injectionState(NULL), dispatchInProgress(false) { michael@0: } michael@0: michael@0: InputDispatcher::EventEntry::~EventEntry() { michael@0: releaseInjectionState(); michael@0: } michael@0: michael@0: void InputDispatcher::EventEntry::release() { michael@0: refCount -= 1; michael@0: if (refCount == 0) { michael@0: delete this; michael@0: } else { michael@0: ALOG_ASSERT(refCount > 0); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::EventEntry::releaseInjectionState() { michael@0: if (injectionState) { michael@0: injectionState->release(); michael@0: injectionState = NULL; michael@0: } michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcher::ConfigurationChangedEntry --- michael@0: michael@0: InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) : michael@0: EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) { michael@0: } michael@0: michael@0: InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() { michael@0: } michael@0: michael@0: void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const { michael@0: msg.append("ConfigurationChangedEvent()"); michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcher::DeviceResetEntry --- michael@0: michael@0: InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) : michael@0: EventEntry(TYPE_DEVICE_RESET, eventTime, 0), michael@0: deviceId(deviceId) { michael@0: } michael@0: michael@0: InputDispatcher::DeviceResetEntry::~DeviceResetEntry() { michael@0: } michael@0: michael@0: void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const { michael@0: msg.appendFormat("DeviceResetEvent(deviceId=%d)", deviceId); michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcher::KeyEntry --- michael@0: michael@0: InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime, michael@0: int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, michael@0: int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState, michael@0: int32_t repeatCount, nsecs_t downTime) : michael@0: EventEntry(TYPE_KEY, eventTime, policyFlags), michael@0: deviceId(deviceId), source(source), action(action), flags(flags), michael@0: keyCode(keyCode), scanCode(scanCode), metaState(metaState), michael@0: repeatCount(repeatCount), downTime(downTime), michael@0: syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN), michael@0: interceptKeyWakeupTime(0) { michael@0: } michael@0: michael@0: InputDispatcher::KeyEntry::~KeyEntry() { michael@0: } michael@0: michael@0: void InputDispatcher::KeyEntry::appendDescription(String8& msg) const { michael@0: msg.appendFormat("KeyEvent(action=%d, deviceId=%d, source=0x%08x)", michael@0: action, deviceId, source); michael@0: } michael@0: michael@0: void InputDispatcher::KeyEntry::recycle() { michael@0: releaseInjectionState(); michael@0: michael@0: dispatchInProgress = false; michael@0: syntheticRepeat = false; michael@0: interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN; michael@0: interceptKeyWakeupTime = 0; michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcher::MotionEntry --- michael@0: michael@0: InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, michael@0: int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags, michael@0: int32_t metaState, int32_t buttonState, michael@0: int32_t edgeFlags, float xPrecision, float yPrecision, michael@0: nsecs_t downTime, int32_t displayId, uint32_t pointerCount, michael@0: const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) : michael@0: EventEntry(TYPE_MOTION, eventTime, policyFlags), michael@0: eventTime(eventTime), michael@0: deviceId(deviceId), source(source), action(action), flags(flags), michael@0: metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags), michael@0: xPrecision(xPrecision), yPrecision(yPrecision), michael@0: downTime(downTime), displayId(displayId), pointerCount(pointerCount) { michael@0: for (uint32_t i = 0; i < pointerCount; i++) { michael@0: this->pointerProperties[i].copyFrom(pointerProperties[i]); michael@0: this->pointerCoords[i].copyFrom(pointerCoords[i]); michael@0: } michael@0: } michael@0: michael@0: InputDispatcher::MotionEntry::~MotionEntry() { michael@0: } michael@0: michael@0: void InputDispatcher::MotionEntry::appendDescription(String8& msg) const { michael@0: msg.appendFormat("MotionEvent(action=%d, deviceId=%d, source=0x%08x, displayId=%d)", michael@0: action, deviceId, source, displayId); michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcher::DispatchEntry --- michael@0: michael@0: volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic; michael@0: michael@0: InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry, michael@0: int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) : michael@0: seq(nextSeq()), michael@0: eventEntry(eventEntry), targetFlags(targetFlags), michael@0: xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor), michael@0: deliveryTime(0), resolvedAction(0), resolvedFlags(0) { michael@0: eventEntry->refCount += 1; michael@0: } michael@0: michael@0: InputDispatcher::DispatchEntry::~DispatchEntry() { michael@0: eventEntry->release(); michael@0: } michael@0: michael@0: uint32_t InputDispatcher::DispatchEntry::nextSeq() { michael@0: // Sequence number 0 is reserved and will never be returned. michael@0: uint32_t seq; michael@0: do { michael@0: seq = android_atomic_inc(&sNextSeqAtomic); michael@0: } while (!seq); michael@0: return seq; michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcher::InputState --- michael@0: michael@0: InputDispatcher::InputState::InputState() { michael@0: } michael@0: michael@0: InputDispatcher::InputState::~InputState() { michael@0: } michael@0: michael@0: bool InputDispatcher::InputState::isNeutral() const { michael@0: return mKeyMementos.isEmpty() && mMotionMementos.isEmpty(); michael@0: } michael@0: michael@0: bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source, michael@0: int32_t displayId) const { michael@0: for (size_t i = 0; i < mMotionMementos.size(); i++) { michael@0: const MotionMemento& memento = mMotionMementos.itemAt(i); michael@0: if (memento.deviceId == deviceId michael@0: && memento.source == source michael@0: && memento.displayId == displayId michael@0: && memento.hovering) { michael@0: return true; michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: bool InputDispatcher::InputState::trackKey(const KeyEntry* entry, michael@0: int32_t action, int32_t flags) { michael@0: switch (action) { michael@0: case AKEY_EVENT_ACTION_UP: { michael@0: if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) { michael@0: for (size_t i = 0; i < mFallbackKeys.size(); ) { michael@0: if (mFallbackKeys.valueAt(i) == entry->keyCode) { michael@0: mFallbackKeys.removeItemsAt(i); michael@0: } else { michael@0: i += 1; michael@0: } michael@0: } michael@0: } michael@0: ssize_t index = findKeyMemento(entry); michael@0: if (index >= 0) { michael@0: mKeyMementos.removeAt(index); michael@0: return true; michael@0: } michael@0: /* FIXME: We can't just drop the key up event because that prevents creating michael@0: * popup windows that are automatically shown when a key is held and then michael@0: * dismissed when the key is released. The problem is that the popup will michael@0: * not have received the original key down, so the key up will be considered michael@0: * to be inconsistent with its observed state. We could perhaps handle this michael@0: * by synthesizing a key down but that will cause other problems. michael@0: * michael@0: * So for now, allow inconsistent key up events to be dispatched. michael@0: * michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, " michael@0: "keyCode=%d, scanCode=%d", michael@0: entry->deviceId, entry->source, entry->keyCode, entry->scanCode); michael@0: #endif michael@0: return false; michael@0: */ michael@0: return true; michael@0: } michael@0: michael@0: case AKEY_EVENT_ACTION_DOWN: { michael@0: ssize_t index = findKeyMemento(entry); michael@0: if (index >= 0) { michael@0: mKeyMementos.removeAt(index); michael@0: } michael@0: addKeyMemento(entry, flags); michael@0: return true; michael@0: } michael@0: michael@0: default: michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry, michael@0: int32_t action, int32_t flags) { michael@0: int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK; michael@0: switch (actionMasked) { michael@0: case AMOTION_EVENT_ACTION_UP: michael@0: case AMOTION_EVENT_ACTION_CANCEL: { michael@0: ssize_t index = findMotionMemento(entry, false /*hovering*/); michael@0: if (index >= 0) { michael@0: mMotionMementos.removeAt(index); michael@0: return true; michael@0: } michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, " michael@0: "actionMasked=%d", michael@0: entry->deviceId, entry->source, actionMasked); michael@0: #endif michael@0: return false; michael@0: } michael@0: michael@0: case AMOTION_EVENT_ACTION_DOWN: { michael@0: ssize_t index = findMotionMemento(entry, false /*hovering*/); michael@0: if (index >= 0) { michael@0: mMotionMementos.removeAt(index); michael@0: } michael@0: addMotionMemento(entry, flags, false /*hovering*/); michael@0: return true; michael@0: } michael@0: michael@0: case AMOTION_EVENT_ACTION_POINTER_UP: michael@0: case AMOTION_EVENT_ACTION_POINTER_DOWN: michael@0: case AMOTION_EVENT_ACTION_MOVE: { michael@0: ssize_t index = findMotionMemento(entry, false /*hovering*/); michael@0: if (index >= 0) { michael@0: MotionMemento& memento = mMotionMementos.editItemAt(index); michael@0: memento.setPointers(entry); michael@0: return true; michael@0: } michael@0: if (actionMasked == AMOTION_EVENT_ACTION_MOVE michael@0: && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK michael@0: | AINPUT_SOURCE_CLASS_NAVIGATION))) { michael@0: // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP. michael@0: return true; michael@0: } michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("Dropping inconsistent motion pointer up/down or move event: " michael@0: "deviceId=%d, source=%08x, actionMasked=%d", michael@0: entry->deviceId, entry->source, actionMasked); michael@0: #endif michael@0: return false; michael@0: } michael@0: michael@0: case AMOTION_EVENT_ACTION_HOVER_EXIT: { michael@0: ssize_t index = findMotionMemento(entry, true /*hovering*/); michael@0: if (index >= 0) { michael@0: mMotionMementos.removeAt(index); michael@0: return true; michael@0: } michael@0: #if DEBUG_OUTBOUND_EVENT_DETAILS michael@0: ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x", michael@0: entry->deviceId, entry->source); michael@0: #endif michael@0: return false; michael@0: } michael@0: michael@0: case AMOTION_EVENT_ACTION_HOVER_ENTER: michael@0: case AMOTION_EVENT_ACTION_HOVER_MOVE: { michael@0: ssize_t index = findMotionMemento(entry, true /*hovering*/); michael@0: if (index >= 0) { michael@0: mMotionMementos.removeAt(index); michael@0: } michael@0: addMotionMemento(entry, flags, true /*hovering*/); michael@0: return true; michael@0: } michael@0: michael@0: default: michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const { michael@0: for (size_t i = 0; i < mKeyMementos.size(); i++) { michael@0: const KeyMemento& memento = mKeyMementos.itemAt(i); michael@0: if (memento.deviceId == entry->deviceId michael@0: && memento.source == entry->source michael@0: && memento.keyCode == entry->keyCode michael@0: && memento.scanCode == entry->scanCode) { michael@0: return i; michael@0: } michael@0: } michael@0: return -1; michael@0: } michael@0: michael@0: ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry, michael@0: bool hovering) const { michael@0: for (size_t i = 0; i < mMotionMementos.size(); i++) { michael@0: const MotionMemento& memento = mMotionMementos.itemAt(i); michael@0: if (memento.deviceId == entry->deviceId michael@0: && memento.source == entry->source michael@0: && memento.displayId == entry->displayId michael@0: && memento.hovering == hovering) { michael@0: return i; michael@0: } michael@0: } michael@0: return -1; michael@0: } michael@0: michael@0: void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) { michael@0: mKeyMementos.push(); michael@0: KeyMemento& memento = mKeyMementos.editTop(); michael@0: memento.deviceId = entry->deviceId; michael@0: memento.source = entry->source; michael@0: memento.keyCode = entry->keyCode; michael@0: memento.scanCode = entry->scanCode; michael@0: memento.metaState = entry->metaState; michael@0: memento.flags = flags; michael@0: memento.downTime = entry->downTime; michael@0: memento.policyFlags = entry->policyFlags; michael@0: } michael@0: michael@0: void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry, michael@0: int32_t flags, bool hovering) { michael@0: mMotionMementos.push(); michael@0: MotionMemento& memento = mMotionMementos.editTop(); michael@0: memento.deviceId = entry->deviceId; michael@0: memento.source = entry->source; michael@0: memento.flags = flags; michael@0: memento.xPrecision = entry->xPrecision; michael@0: memento.yPrecision = entry->yPrecision; michael@0: memento.downTime = entry->downTime; michael@0: memento.displayId = entry->displayId; michael@0: memento.setPointers(entry); michael@0: memento.hovering = hovering; michael@0: memento.policyFlags = entry->policyFlags; michael@0: } michael@0: michael@0: void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) { michael@0: pointerCount = entry->pointerCount; michael@0: for (uint32_t i = 0; i < entry->pointerCount; i++) { michael@0: pointerProperties[i].copyFrom(entry->pointerProperties[i]); michael@0: pointerCoords[i].copyFrom(entry->pointerCoords[i]); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime, michael@0: Vector& outEvents, const CancelationOptions& options) { michael@0: for (size_t i = 0; i < mKeyMementos.size(); i++) { michael@0: const KeyMemento& memento = mKeyMementos.itemAt(i); michael@0: if (shouldCancelKey(memento, options)) { michael@0: outEvents.push(new KeyEntry(currentTime, michael@0: memento.deviceId, memento.source, memento.policyFlags, michael@0: AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED, michael@0: memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime)); michael@0: } michael@0: } michael@0: michael@0: for (size_t i = 0; i < mMotionMementos.size(); i++) { michael@0: const MotionMemento& memento = mMotionMementos.itemAt(i); michael@0: if (shouldCancelMotion(memento, options)) { michael@0: outEvents.push(new MotionEntry(currentTime, michael@0: memento.deviceId, memento.source, memento.policyFlags, michael@0: memento.hovering michael@0: ? AMOTION_EVENT_ACTION_HOVER_EXIT michael@0: : AMOTION_EVENT_ACTION_CANCEL, michael@0: memento.flags, 0, 0, 0, michael@0: memento.xPrecision, memento.yPrecision, memento.downTime, michael@0: memento.displayId, michael@0: memento.pointerCount, memento.pointerProperties, memento.pointerCoords)); michael@0: } michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::InputState::clear() { michael@0: mKeyMementos.clear(); michael@0: mMotionMementos.clear(); michael@0: mFallbackKeys.clear(); michael@0: } michael@0: michael@0: void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const { michael@0: for (size_t i = 0; i < mMotionMementos.size(); i++) { michael@0: const MotionMemento& memento = mMotionMementos.itemAt(i); michael@0: if (memento.source & AINPUT_SOURCE_CLASS_POINTER) { michael@0: for (size_t j = 0; j < other.mMotionMementos.size(); ) { michael@0: const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j); michael@0: if (memento.deviceId == otherMemento.deviceId michael@0: && memento.source == otherMemento.source michael@0: && memento.displayId == otherMemento.displayId) { michael@0: other.mMotionMementos.removeAt(j); michael@0: } else { michael@0: j += 1; michael@0: } michael@0: } michael@0: other.mMotionMementos.push(memento); michael@0: } michael@0: } michael@0: } michael@0: michael@0: int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) { michael@0: ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode); michael@0: return index >= 0 ? mFallbackKeys.valueAt(index) : -1; michael@0: } michael@0: michael@0: void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode, michael@0: int32_t fallbackKeyCode) { michael@0: ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode); michael@0: if (index >= 0) { michael@0: mFallbackKeys.replaceValueAt(index, fallbackKeyCode); michael@0: } else { michael@0: mFallbackKeys.add(originalKeyCode, fallbackKeyCode); michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) { michael@0: mFallbackKeys.removeItem(originalKeyCode); michael@0: } michael@0: michael@0: bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento, michael@0: const CancelationOptions& options) { michael@0: if (options.keyCode != -1 && memento.keyCode != options.keyCode) { michael@0: return false; michael@0: } michael@0: michael@0: if (options.deviceId != -1 && memento.deviceId != options.deviceId) { michael@0: return false; michael@0: } michael@0: michael@0: switch (options.mode) { michael@0: case CancelationOptions::CANCEL_ALL_EVENTS: michael@0: case CancelationOptions::CANCEL_NON_POINTER_EVENTS: michael@0: return true; michael@0: case CancelationOptions::CANCEL_FALLBACK_EVENTS: michael@0: return memento.flags & AKEY_EVENT_FLAG_FALLBACK; michael@0: default: michael@0: return false; michael@0: } michael@0: } michael@0: michael@0: bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento, michael@0: const CancelationOptions& options) { michael@0: if (options.deviceId != -1 && memento.deviceId != options.deviceId) { michael@0: return false; michael@0: } michael@0: michael@0: switch (options.mode) { michael@0: case CancelationOptions::CANCEL_ALL_EVENTS: michael@0: return true; michael@0: case CancelationOptions::CANCEL_POINTER_EVENTS: michael@0: return memento.source & AINPUT_SOURCE_CLASS_POINTER; michael@0: case CancelationOptions::CANCEL_NON_POINTER_EVENTS: michael@0: return !(memento.source & AINPUT_SOURCE_CLASS_POINTER); michael@0: default: michael@0: return false; michael@0: } michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcher::Connection --- michael@0: michael@0: InputDispatcher::Connection::Connection(const sp& inputChannel, michael@0: const sp& inputWindowHandle, bool monitor) : michael@0: status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle), michael@0: monitor(monitor), michael@0: inputPublisher(inputChannel), inputPublisherBlocked(false) { michael@0: } michael@0: michael@0: InputDispatcher::Connection::~Connection() { michael@0: } michael@0: michael@0: const char* InputDispatcher::Connection::getWindowName() const { michael@0: if (inputWindowHandle != NULL) { michael@0: return inputWindowHandle->getName().string(); michael@0: } michael@0: if (monitor) { michael@0: return "monitor"; michael@0: } michael@0: return "?"; michael@0: } michael@0: michael@0: const char* InputDispatcher::Connection::getStatusLabel() const { michael@0: switch (status) { michael@0: case STATUS_NORMAL: michael@0: return "NORMAL"; michael@0: michael@0: case STATUS_BROKEN: michael@0: return "BROKEN"; michael@0: michael@0: case STATUS_ZOMBIE: michael@0: return "ZOMBIE"; michael@0: michael@0: default: michael@0: return "UNKNOWN"; michael@0: } michael@0: } michael@0: michael@0: InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) { michael@0: for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) { michael@0: if (entry->seq == seq) { michael@0: return entry; michael@0: } michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcher::CommandEntry --- michael@0: michael@0: InputDispatcher::CommandEntry::CommandEntry(Command command) : michael@0: command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0), michael@0: seq(0), handled(false) { michael@0: } michael@0: michael@0: InputDispatcher::CommandEntry::~CommandEntry() { michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcher::TouchState --- michael@0: michael@0: InputDispatcher::TouchState::TouchState() : michael@0: down(false), split(false), deviceId(-1), source(0), displayId(-1) { michael@0: } michael@0: michael@0: InputDispatcher::TouchState::~TouchState() { michael@0: } michael@0: michael@0: void InputDispatcher::TouchState::reset() { michael@0: down = false; michael@0: split = false; michael@0: deviceId = -1; michael@0: source = 0; michael@0: displayId = -1; michael@0: windows.clear(); michael@0: } michael@0: michael@0: void InputDispatcher::TouchState::copyFrom(const TouchState& other) { michael@0: down = other.down; michael@0: split = other.split; michael@0: deviceId = other.deviceId; michael@0: source = other.source; michael@0: displayId = other.displayId; michael@0: windows = other.windows; michael@0: } michael@0: michael@0: void InputDispatcher::TouchState::addOrUpdateWindow(const sp& windowHandle, michael@0: int32_t targetFlags, BitSet32 pointerIds) { michael@0: if (targetFlags & InputTarget::FLAG_SPLIT) { michael@0: split = true; michael@0: } michael@0: michael@0: for (size_t i = 0; i < windows.size(); i++) { michael@0: TouchedWindow& touchedWindow = windows.editItemAt(i); michael@0: if (touchedWindow.windowHandle == windowHandle) { michael@0: touchedWindow.targetFlags |= targetFlags; michael@0: if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) { michael@0: touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS; michael@0: } michael@0: touchedWindow.pointerIds.value |= pointerIds.value; michael@0: return; michael@0: } michael@0: } michael@0: michael@0: windows.push(); michael@0: michael@0: TouchedWindow& touchedWindow = windows.editTop(); michael@0: touchedWindow.windowHandle = windowHandle; michael@0: touchedWindow.targetFlags = targetFlags; michael@0: touchedWindow.pointerIds = pointerIds; michael@0: } michael@0: michael@0: void InputDispatcher::TouchState::removeWindow(const sp& windowHandle) { michael@0: for (size_t i = 0; i < windows.size(); i++) { michael@0: if (windows.itemAt(i).windowHandle == windowHandle) { michael@0: windows.removeAt(i); michael@0: return; michael@0: } michael@0: } michael@0: } michael@0: michael@0: void InputDispatcher::TouchState::filterNonAsIsTouchWindows() { michael@0: for (size_t i = 0 ; i < windows.size(); ) { michael@0: TouchedWindow& window = windows.editItemAt(i); michael@0: if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS michael@0: | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) { michael@0: window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK; michael@0: window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS; michael@0: i += 1; michael@0: } else { michael@0: windows.removeAt(i); michael@0: } michael@0: } michael@0: } michael@0: michael@0: sp InputDispatcher::TouchState::getFirstForegroundWindowHandle() const { michael@0: for (size_t i = 0; i < windows.size(); i++) { michael@0: const TouchedWindow& window = windows.itemAt(i); michael@0: if (window.targetFlags & InputTarget::FLAG_FOREGROUND) { michael@0: return window.windowHandle; michael@0: } michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: bool InputDispatcher::TouchState::isSlippery() const { michael@0: // Must have exactly one foreground window. michael@0: bool haveSlipperyForegroundWindow = false; michael@0: for (size_t i = 0; i < windows.size(); i++) { michael@0: const TouchedWindow& window = windows.itemAt(i); michael@0: if (window.targetFlags & InputTarget::FLAG_FOREGROUND) { michael@0: if (haveSlipperyForegroundWindow michael@0: || !(window.windowHandle->getInfo()->layoutParamsFlags michael@0: & InputWindowInfo::FLAG_SLIPPERY)) { michael@0: return false; michael@0: } michael@0: haveSlipperyForegroundWindow = true; michael@0: } michael@0: } michael@0: return haveSlipperyForegroundWindow; michael@0: } michael@0: michael@0: michael@0: // --- InputDispatcherThread --- michael@0: michael@0: InputDispatcherThread::InputDispatcherThread(const sp& dispatcher) : michael@0: Thread(/*canCallJava*/ true), mDispatcher(dispatcher) { michael@0: } michael@0: michael@0: InputDispatcherThread::~InputDispatcherThread() { michael@0: } michael@0: michael@0: bool InputDispatcherThread::threadLoop() { michael@0: mDispatcher->dispatchOnce(); michael@0: return true; michael@0: } michael@0: michael@0: } // namespace android