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