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