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