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