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