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