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