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