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