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