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