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