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