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