~mir-team/mir/in-process-egl+input-conglomeration

« back to all changes in this revision

Viewing changes to 3rd_party/android-input/android_pristine/frameworks/base/services/input/InputDispatcher.cpp

Merged trunk and fixed issues

Show diffs side-by-side

added added

removed removed

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