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