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