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