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