2
* Copyright (C) 2010 The Android Open Source Project
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
8
* http://www.apache.org/licenses/LICENSE-2.0
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.
17
#define LOG_TAG "InputDispatcher"
18
#define ATRACE_TAG ATRACE_TAG_INPUT
20
//#define LOG_NDEBUG 0
22
// Log detailed debug messages about each inbound event notification to the dispatcher.
23
#define DEBUG_INBOUND_EVENT_DETAILS 0
25
// Log detailed debug messages about each outbound event processed by the dispatcher.
26
#define DEBUG_OUTBOUND_EVENT_DETAILS 0
28
// Log debug messages about the dispatch cycle.
29
#define DEBUG_DISPATCH_CYCLE 0
31
// Log debug messages about registrations.
32
#define DEBUG_REGISTRATION 0
34
// Log debug messages about input event injection.
35
#define DEBUG_INJECTION 0
37
// Log debug messages about input focus tracking.
40
// Log debug messages about the app switch latency optimization.
41
#define DEBUG_APP_SWITCH 0
43
// Log debug messages about hover events.
46
#include "InputDispatcher.h"
48
#include <utils/Trace.h>
49
#include <cutils/log.h>
50
#include <androidfw/PowerManager.h>
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
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
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
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
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
88
static inline nsecs_t now() {
89
return systemTime(SYSTEM_TIME_MONOTONIC);
92
static inline const char* toString(bool value) {
93
return value ? "true" : "false";
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;
101
static bool isValidKeyAction(int32_t action) {
103
case AKEY_EVENT_ACTION_DOWN:
104
case AKEY_EVENT_ACTION_UP:
111
static bool validateKeyEvent(int32_t action) {
112
if (! isValidKeyAction(action)) {
113
ALOGE("Key event has invalid action code 0x%x", action);
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:
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;
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);
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);
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",
160
if (pointerIdBits.hasBit(id)) {
161
ALOGE("Motion event has duplicate pointer id %d", id);
164
pointerIdBits.markBit(id);
169
static void dumpRegion(String8& dump, const SkRegion& region) {
170
if (region.isEmpty()) {
171
dump.append("<empty>");
176
for (SkRegion::Iterator it(region); !it.done(); it.next()) {
182
const SkIRect& rect = it.rect();
183
dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
188
// --- InputDispatcher ---
190
InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& 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);
198
mKeyRepeatState.lastKeyEntry = NULL;
200
policy->getDispatcherConfiguration(&mConfig);
203
InputDispatcher::~InputDispatcher() {
207
resetKeyRepeatLocked();
208
releasePendingEventLocked();
209
drainInboundQueueLocked();
212
while (mConnectionsByFd.size() != 0) {
213
unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
217
void InputDispatcher::dispatchOnce() {
218
nsecs_t nextWakeupTime = LONG_LONG_MAX;
221
mDispatcherIsAliveCondition.broadcast();
223
dispatchOnceInnerLocked(&nextWakeupTime);
225
if (runCommandsLockedInterruptible()) {
226
nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
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);
236
void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
237
nsecs_t currentTime = now();
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
242
if (!mPolicy->isKeyRepeatEnabled()) {
243
resetKeyRepeatLocked();
246
// If dispatching is frozen, do not process timeouts or try to deliver any new events.
247
if (mDispatchFrozen) {
249
ALOGD("Dispatch frozen. Waiting some more.");
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;
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;
273
// Synthesize a key repeat if appropriate.
274
if (mKeyRepeatState.lastKeyEntry) {
275
if (currentTime >= mKeyRepeatState.nextRepeatTime) {
276
mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
278
if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
279
*nextWakeupTime = mKeyRepeatState.nextRepeatTime;
284
// Nothing to do if there is no pending event.
285
if (!mPendingEvent) {
289
// Inbound queue has at least one entry.
290
mPendingEvent = mInboundQueue.dequeueAtHead();
291
traceInboundQueueLengthLocked();
294
// Poke user activity for this event.
295
if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
296
pokeUserActivityLocked(mPendingEvent);
299
// Get ready to dispatch the event.
300
resetANRTimeoutsLocked();
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);
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;
314
if (mNextUnblockedEvent == mPendingEvent) {
315
mNextUnblockedEvent = NULL;
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
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
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;
345
if (dropReason == DROP_REASON_NOT_DROPPED
346
&& isStaleEventLocked(currentTime, typedEntry)) {
347
dropReason = DROP_REASON_STALE;
349
if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
350
dropReason = DROP_REASON_BLOCKED;
352
done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
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;
361
if (dropReason == DROP_REASON_NOT_DROPPED
362
&& isStaleEventLocked(currentTime, typedEntry)) {
363
dropReason = DROP_REASON_STALE;
365
if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
366
dropReason = DROP_REASON_BLOCKED;
368
done = dispatchMotionLocked(currentTime, typedEntry,
369
&dropReason, nextWakeupTime);
379
if (dropReason != DROP_REASON_NOT_DROPPED) {
380
dropInboundEventLocked(mPendingEvent, dropReason);
383
releasePendingEventLocked();
384
*nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
388
bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
389
bool needWake = mInboundQueue.isEmpty();
390
mInboundQueue.enqueueAtTail(entry);
391
traceInboundQueueLengthLocked();
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) {
405
ALOGD("App switch is pending!");
407
mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
408
mAppSwitchSawKeyDown = false;
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;
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;
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)) {
466
if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
467
// Error window is on top but not visible, so touch is dropped.
474
void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
476
switch (dropReason) {
477
case DROP_REASON_POLICY:
478
#if DEBUG_INBOUND_EVENT_DETAILS
479
ALOGD("Dropped event because policy consumed it.");
481
reason = "inbound event was dropped because the policy consumed it";
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";
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";
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";
497
case DROP_REASON_STALE:
498
ALOGI("Dropped event because it is stale.");
499
reason = "inbound event was dropped because it is stale";
506
switch (entry->type) {
507
case EventEntry::TYPE_KEY: {
508
CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
509
synthesizeCancelationEventsForAllConnectionsLocked(options);
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);
518
CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
519
synthesizeCancelationEventsForAllConnectionsLocked(options);
526
bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
527
return keyCode == AKEYCODE_HOME || keyCode == AKEYCODE_ENDCALL;
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);
537
bool InputDispatcher::isAppSwitchPendingLocked() {
538
return mAppSwitchDueTime != LONG_LONG_MAX;
541
void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
542
mAppSwitchDueTime = LONG_LONG_MAX;
546
ALOGD("App switch has arrived.");
548
ALOGD("App switch was abandoned.");
553
bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
554
return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
557
bool InputDispatcher::runCommandsLockedInterruptible() {
558
if (mCommandQueue.isEmpty()) {
563
CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
565
Command command = commandEntry->command;
566
(this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
568
commandEntry->connection.clear();
570
} while (! mCommandQueue.isEmpty());
574
InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
575
CommandEntry* commandEntry = new CommandEntry(command);
576
mCommandQueue.enqueueAtTail(commandEntry);
580
void InputDispatcher::drainInboundQueueLocked() {
581
while (! mInboundQueue.isEmpty()) {
582
EventEntry* entry = mInboundQueue.dequeueAtHead();
583
releaseInboundEventLocked(entry);
585
traceInboundQueueLengthLocked();
588
void InputDispatcher::releasePendingEventLocked() {
590
resetANRTimeoutsLocked();
591
releaseInboundEventLocked(mPendingEvent);
592
mPendingEvent = NULL;
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.");
602
setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
604
if (entry == mNextUnblockedEvent) {
605
mNextUnblockedEvent = NULL;
610
void InputDispatcher::resetKeyRepeatLocked() {
611
if (mKeyRepeatState.lastKeyEntry) {
612
mKeyRepeatState.lastKeyEntry->release();
613
mKeyRepeatState.lastKeyEntry = NULL;
617
InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
618
KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
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) {
625
entry->eventTime = currentTime;
626
entry->policyFlags = policyFlags;
627
entry->repeatCount += 1;
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);
634
mKeyRepeatState.lastKeyEntry = newEntry;
639
entry->syntheticRepeat = true;
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;
645
mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
649
bool InputDispatcher::dispatchConfigurationChangedLocked(
650
nsecs_t currentTime, ConfigurationChangedEntry* entry) {
651
#if DEBUG_OUTBOUND_EVENT_DETAILS
652
ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
655
// Reset key repeating in case a keyboard device was added or removed or something.
656
resetKeyRepeatLocked();
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;
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);
671
CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
673
options.deviceId = entry->deviceId;
674
synthesizeCancelationEventsForAllConnectionsLocked(options);
678
bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
679
DropReason* dropReason, nsecs_t* nextWakeupTime) {
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
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;
700
mKeyRepeatState.lastKeyEntry = entry;
701
entry->refCount += 1;
702
} else if (! entry->syntheticRepeat) {
703
resetKeyRepeatLocked();
706
if (entry->repeatCount == 1) {
707
entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
709
entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
712
entry->dispatchInProgress = true;
714
logOutboundKeyDetailsLocked("dispatchKey - ", entry);
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;
723
return false; // wait until next wakeup
725
entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
726
entry->interceptKeyWakeupTime = 0;
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;
737
commandEntry->keyEntry = entry;
738
entry->refCount += 1;
739
return false; // wait for the command to run
741
entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
743
} else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
744
if (*dropReason == DROP_REASON_NOT_DROPPED) {
745
*dropReason = DROP_REASON_POLICY;
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);
757
Vector<InputTarget> inputTargets;
758
int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
759
entry, inputTargets, nextWakeupTime);
760
if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
764
setInjectionResultLocked(entry, injectionResult);
765
if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
769
addMonitoringTargetsLocked(inputTargets);
772
dispatchEventLocked(currentTime, entry, inputTargets);
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",
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);
788
bool InputDispatcher::dispatchMotionLocked(
789
nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
791
if (! entry->dispatchInProgress) {
792
entry->dispatchInProgress = true;
794
logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
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);
804
bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
807
Vector<InputTarget> inputTargets;
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);
816
// Non touch event. (eg. trackball)
817
injectionResult = findFocusedWindowTargetsLocked(currentTime,
818
entry, inputTargets, nextWakeupTime);
820
if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
824
setInjectionResultLocked(entry, injectionResult);
825
if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
829
addMonitoringTargetsLocked(inputTargets);
831
// Dispatch the motion.
832
if (conflictingPointerActions) {
833
CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
834
"conflicting pointer actions");
835
synthesizeCancelationEventsForAllConnectionsLocked(options);
837
dispatchEventLocked(currentTime, entry, inputTargets);
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",
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,
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, "
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));
875
void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
876
EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
877
#if DEBUG_DISPATCH_CYCLE
878
ALOGD("dispatchEventToCurrentInputTargets");
881
ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
883
pokeUserActivityLocked(eventEntry);
885
for (size_t i = 0; i < inputTargets.size(); i++) {
886
const InputTarget& inputTarget = inputTargets.itemAt(i);
888
ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
889
if (connectionIndex >= 0) {
890
sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
891
prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
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());
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) {
910
ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
912
mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
913
mInputTargetWaitStartTime = currentTime;
914
mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
915
mInputTargetWaitTimeoutExpired = false;
916
mInputTargetWaitApplicationHandle.clear();
919
if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
921
ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
922
getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
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);
932
timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
935
mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
936
mInputTargetWaitStartTime = currentTime;
937
mInputTargetWaitTimeoutTime = currentTime + timeout;
938
mInputTargetWaitTimeoutExpired = false;
939
mInputTargetWaitApplicationHandle.clear();
941
if (windowHandle != NULL) {
942
mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
944
if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
945
mInputTargetWaitApplicationHandle = applicationHandle;
950
if (mInputTargetWaitTimeoutExpired) {
951
return INPUT_EVENT_INJECTION_TIMED_OUT;
954
if (currentTime >= mInputTargetWaitTimeoutTime) {
955
onANRLocked(currentTime, applicationHandle, windowHandle,
956
entry->eventTime, mInputTargetWaitStartTime, reason);
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;
963
// Force poll loop to wake up when timeout is due.
964
if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
965
*nextWakeupTime = mInputTargetWaitTimeoutTime;
967
return INPUT_EVENT_INJECTION_PENDING;
971
void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
972
const sp<InputChannel>& inputChannel) {
973
if (newTimeout > 0) {
974
// Extend the timeout.
975
mInputTargetWaitTimeoutTime = now() + newTimeout;
978
mInputTargetWaitTimeoutExpired = true;
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;
987
if (windowHandle != NULL) {
988
mTouchState.removeWindow(windowHandle);
991
if (connection->status == Connection::STATUS_NORMAL) {
992
CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
993
"application not responding");
994
synthesizeCancelationEventsForConnectionLocked(connection, options);
1001
nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1002
nsecs_t currentTime) {
1003
if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1004
return currentTime - mInputTargetWaitStartTime;
1009
void InputDispatcher::resetANRTimeoutsLocked() {
1011
ALOGD("Resetting ANR timeouts.");
1014
// Reset input target wait timeout.
1015
mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1016
mInputTargetWaitApplicationHandle.clear();
1019
int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1020
const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1021
int32_t injectionResult;
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.");
1035
ALOGI("Dropping event because there is no focused window or focused application.");
1036
injectionResult = INPUT_EVENT_INJECTION_FAILED;
1040
// Check permissions.
1041
if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
1042
injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
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.");
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.");
1063
// Success! Output targets.
1064
injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1065
addWindowTargetLocked(mFocusedWindowHandle,
1066
InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1072
nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1073
updateDispatchStatisticsLocked(currentTime, entry,
1074
injectionResult, timeSpentWaitingForApplication);
1076
ALOGD("findFocusedWindow finished: injectionResult=%d, "
1077
"timeSpentWaitingForApplication=%0.1fms",
1078
injectionResult, timeSpentWaitingForApplication / 1000000.0);
1080
return injectionResult;
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
1092
nsecs_t startTime = now();
1094
// For security reasons, we defer updating the touch state until we are sure that
1095
// event injection will be allowed.
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.
1107
// Here's what happens:
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.
1115
// Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
1116
// instead of POLICY_FLAG_WOKE_HERE...
1118
bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
1120
int32_t action = entry->action;
1121
int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
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;
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
1138
bool wrongDevice = false;
1140
bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
1141
if (switchedDevice && mTouchState.down && !down) {
1143
ALOGD("Dropping event because a pointer for a different device is already down.");
1145
mTempTouchState.copyFrom(mTouchState);
1146
injectionResult = INPUT_EVENT_INJECTION_FAILED;
1147
switchedDevice = false;
1151
mTempTouchState.reset();
1152
mTempTouchState.down = down;
1153
mTempTouchState.deviceId = entry->deviceId;
1154
mTempTouchState.source = entry->source;
1157
mTempTouchState.copyFrom(mTouchState);
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. */
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;
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;
1179
if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
1180
if (topErrorWindowHandle == NULL) {
1181
topErrorWindowHandle = windowHandle;
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)) {
1191
|| (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
1192
newTouchedWindowHandle = windowHandle;
1194
break; // found touched window, exit window loop
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;
1205
mTempTouchState.addOrUpdateWindow(
1206
windowHandle, outsideTargetFlags, BitSet32(0));
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;
1222
// Figure out whether splitting will be allowed for this window.
1223
if (newTouchedWindowHandle != NULL
1224
&& newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1225
// New window supports splitting.
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;
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.");
1252
ALOGI("Dropping event because there is no touched window.");
1253
injectionResult = INPUT_EVENT_INJECTION_FAILED;
1258
// Set target flags.
1259
int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1261
targetFlags |= InputTarget::FLAG_SPLIT;
1263
if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1264
targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1267
// Update hover state.
1268
if (isHoverAction) {
1269
newHoverWindowHandle = newTouchedWindowHandle;
1270
} else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1271
newHoverWindowHandle = mLastHoverWindowHandle;
1274
// Update the temporary touch state.
1275
BitSet32 pointerIds;
1277
uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1278
pointerIds.markBit(pointerId);
1280
mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1282
/* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1284
// If the pointer is not currently down, then ignore the event.
1285
if (! mTempTouchState.down) {
1287
ALOGD("Dropping event because the pointer is not down or we previously "
1288
"dropped the pointer down event.");
1290
injectionResult = INPUT_EVENT_INJECTION_FAILED;
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));
1301
sp<InputWindowHandle> oldTouchedWindowHandle =
1302
mTempTouchState.getFirstForegroundWindowHandle();
1303
sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(x, y);
1304
if (oldTouchedWindowHandle != newTouchedWindowHandle
1305
&& newTouchedWindowHandle != NULL) {
1307
ALOGD("Touch is slipping out of window %s into window %s.",
1308
oldTouchedWindowHandle->getName().string(),
1309
newTouchedWindowHandle->getName().string());
1311
// Make a slippery exit from the old window.
1312
mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1313
InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1315
// Make a slippery entrance into the new window.
1316
if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1320
int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1321
| InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1323
targetFlags |= InputTarget::FLAG_SPLIT;
1325
if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1326
targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1329
BitSet32 pointerIds;
1331
pointerIds.markBit(entry->pointerProperties[0].id);
1333
mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1338
if (newHoverWindowHandle != mLastHoverWindowHandle) {
1339
// Let the previous window know that the hover sequence is over.
1340
if (mLastHoverWindowHandle != NULL) {
1342
ALOGD("Sending hover exit event to window %s.",
1343
mLastHoverWindowHandle->getName().string());
1345
mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1346
InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1349
// Let the new window know that the hover sequence is starting.
1350
if (newHoverWindowHandle != NULL) {
1352
ALOGD("Sending hover enter event to window %s.",
1353
newHoverWindowHandle->getName().string());
1355
mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1356
InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1360
// Check permission to inject into all touched foreground windows and ensure there
1361
// is at least one touched foreground window.
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;
1376
if (! haveForegroundWindow) {
1378
ALOGD("Dropping event because there is no touched foreground window to receive it.");
1380
injectionResult = INPUT_EVENT_INJECTION_FAILED;
1384
// Permission granted to injection into all touched foreground windows.
1385
injectionPermission = INJECTION_PERMISSION_GRANTED;
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));
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.");
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.");
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,
1452
// Success! Output targets.
1453
injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
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);
1461
// Drop the outside or hover touch windows since we will not care about them
1462
// in the next iteration.
1463
mTempTouchState.filterNonAsIsTouchWindows();
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;
1471
injectionPermission = INJECTION_PERMISSION_DENIED;
1475
// Update final pieces of touch state if the injector had permission.
1476
if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1478
if (switchedDevice) {
1480
ALOGD("Conflicting pointer actions: Switched to a different device.");
1482
*outConflictingPointerActions = true;
1485
if (isHoverAction) {
1486
// Started hovering, therefore no longer down.
1487
if (mTouchState.down) {
1489
ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1491
*outConflictingPointerActions = true;
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;
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) {
1507
ALOGD("Conflicting pointer actions: Down received while already down.");
1509
*outConflictingPointerActions = true;
1511
mTouchState.copyFrom(mTempTouchState);
1512
} else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1513
// One pointer went up.
1515
int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1516
uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
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);
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.
1534
// Save changes to touch state as-is for all other actions.
1535
mTouchState.copyFrom(mTempTouchState);
1538
// Update hover state.
1539
mLastHoverWindowHandle = newHoverWindowHandle;
1543
ALOGD("Not updating touch focus because injection was denied.");
1548
// Reset temporary touch state to ensure we release unnecessary references to input channels.
1549
mTempTouchState.reset();
1551
nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1552
updateDispatchStatisticsLocked(currentTime, entry,
1553
injectionResult, timeSpentWaitingForApplication);
1555
ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1556
"timeSpentWaitingForApplication=%0.1fms",
1557
injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1559
return injectionResult;
1562
void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1563
int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1564
inputTargets.push();
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;
1576
void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
1577
for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1578
inputTargets.push();
1580
InputTarget& target = inputTargets.editTop();
1581
target.inputChannel = mMonitoringChannels[i];
1582
target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1585
target.pointerIds.clear();
1586
target.scaleFactor = 1.0f;
1590
bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1591
const InjectionState* 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 "
1599
injectionState->injectorPid, injectionState->injectorUid,
1600
windowHandle->getName().string(),
1601
windowHandle->getInfo()->ownerUid);
1603
ALOGW("Permission denied: injecting event from pid %d uid %d",
1604
injectionState->injectorPid, injectionState->injectorUid);
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) {
1620
const InputWindowInfo* otherInfo = otherHandle->getInfo();
1621
if (otherInfo->visible && ! otherInfo->isTrustedOverlay()
1622
&& otherInfo->frameContainsPoint(x, y)) {
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) {
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.
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();
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.
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.
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) {
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());
1686
return applicationHandle->getName();
1688
} else if (windowHandle != NULL) {
1689
return windowHandle->getName();
1691
return String8("<unknown application or window>");
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) {
1704
if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1705
eventType = POWER_MANAGER_TOUCH_EVENT;
1709
case EventEntry::TYPE_KEY: {
1710
const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1711
if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1714
eventType = POWER_MANAGER_BUTTON_EVENT;
1719
CommandEntry* commandEntry = postCommandLocked(
1720
& InputDispatcher::doPokeUserActivityLockedInterruptible);
1721
commandEntry->eventTime = eventEntry->eventTime;
1722
commandEntry->userActivityEventType = eventType;
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, "
1731
connection->getInputChannelName(), inputTarget->flags,
1732
inputTarget->xOffset, inputTarget->yOffset,
1733
inputTarget->scaleFactor, inputTarget->pointerIds.value);
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());
1746
// Split a motion event if needed.
1747
if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1748
ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
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
1758
ALOGD("channel '%s' ~ Split motion event.",
1759
connection->getInputChannelName());
1760
logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1762
enqueueDispatchEntriesLocked(currentTime, connection,
1763
splitMotionEntry, inputTarget);
1764
splitMotionEntry->release();
1769
// Not splitting. Enqueue dispatch entries for the event as is.
1770
enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1773
void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1774
const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1775
bool wasEmpty = connection->outboundQueue.isEmpty();
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);
1791
// If the outbound queue was previously empty, start the dispatch cycle going.
1792
if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1793
startDispatchCycleLocked(currentTime, connection);
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)) {
1804
inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
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);
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;
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());
1825
delete dispatchEntry;
1826
return; // skip the inconsistent event
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;
1844
dispatchEntry->resolvedAction = motionEntry->action;
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());
1853
dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1856
dispatchEntry->resolvedFlags = motionEntry->flags;
1857
if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1858
dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
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());
1867
delete dispatchEntry;
1868
return; // skip the inconsistent event
1874
// Remember that we are waiting for this dispatch to complete.
1875
if (dispatchEntry->hasForegroundTarget()) {
1876
incrementPendingForegroundDispatchesLocked(eventEntry);
1879
// Enqueue the dispatch entry.
1880
connection->outboundQueue.enqueueAtTail(dispatchEntry);
1881
traceOutboundQueueLengthLocked(connection);
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());
1891
while (connection->status == Connection::STATUS_NORMAL
1892
&& !connection->outboundQueue.isEmpty()) {
1893
DispatchEntry* dispatchEntry = connection->outboundQueue.head;
1894
dispatchEntry->deliveryTime = currentTime;
1896
// Publish the event.
1898
EventEntry* eventEntry = dispatchEntry->eventEntry;
1899
switch (eventEntry->type) {
1900
case EventEntry::TYPE_KEY: {
1901
KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
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);
1913
case EventEntry::TYPE_MOTION: {
1914
MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1916
PointerCoords scaledCoords[MAX_POINTERS];
1917
const PointerCoords* usingCoords = motionEntry->pointerCoords;
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);
1931
usingCoords = scaledCoords;
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();
1943
usingCoords = scaledCoords;
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,
1953
motionEntry->xPrecision, motionEntry->yPrecision,
1954
motionEntry->downTime, motionEntry->eventTime,
1955
motionEntry->pointerCount, motionEntry->pointerProperties,
1965
// Check the result.
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*/);
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());
1982
connection->inputPublisherBlocked = true;
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*/);
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);
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));
2007
connection->inputPublisherBlocked = false;
2009
if (connection->status == Connection::STATUS_BROKEN
2010
|| connection->status == Connection::STATUS_ZOMBIE) {
2014
// Notify other system components and prepare to start the next dispatch cycle.
2015
onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
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));
2025
// Clear the dispatch queues.
2026
drainDispatchQueueLocked(&connection->outboundQueue);
2027
traceOutboundQueueLengthLocked(connection);
2028
drainDispatchQueueLocked(&connection->waitQueue);
2029
traceWaitQueueLengthLocked(connection);
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;
2037
// Notify other system components.
2038
onDispatchCycleBrokenLocked(currentTime, connection);
2043
void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2044
while (!queue->isEmpty()) {
2045
DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2046
releaseDispatchEntryLocked(dispatchEntry);
2050
void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2051
if (dispatchEntry->hasForegroundTarget()) {
2052
decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2054
delete dispatchEntry;
2057
int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2058
InputDispatcher* d = static_cast<InputDispatcher*>(data);
2061
AutoMutex _l(d->mLock);
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
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);
2079
nsecs_t currentTime = now();
2080
bool gotOne = false;
2085
status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2089
d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2093
d->runCommandsLockedInterruptible();
2094
if (status == WOULD_BLOCK) {
2099
notify = status != DEAD_OBJECT || !connection->monitor;
2101
ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2102
connection->getInputChannelName(), status);
2105
// Monitor channels are never explicitly unregistered.
2106
// We do it automatically when the remote endpoint is closed so don't warn
2108
notify = !connection->monitor;
2110
ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
2111
"events=0x%x", connection->getInputChannelName(), events);
2115
// Unregister the channel.
2116
d->unregisterInputChannelLocked(connection->inputChannel, notify);
2117
return 0; // remove the callback
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);
2129
void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2130
const sp<InputChannel>& channel, const CancelationOptions& options) {
2131
ssize_t index = getConnectionIndexLocked(channel);
2133
synthesizeCancelationEventsForConnectionLocked(
2134
mConnectionsByFd.valueAt(index), options);
2138
void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2139
const sp<Connection>& connection, const CancelationOptions& options) {
2140
if (connection->status == Connection::STATUS_BROKEN) {
2144
nsecs_t currentTime = now();
2146
Vector<EventEntry*> cancelationEvents;
2147
connection->inputState.synthesizeCancelationEvents(currentTime,
2148
cancelationEvents, options);
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);
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));
2164
case EventEntry::TYPE_MOTION:
2165
logOutboundMotionDetailsLocked("cancel - ",
2166
static_cast<MotionEntry*>(cancelationEventEntry));
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;
2180
target.scaleFactor = 1.0f;
2182
target.inputChannel = connection->inputChannel;
2183
target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2185
enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2186
&target, InputTarget::FLAG_DISPATCH_AS_IS);
2188
cancelationEventEntry->release();
2191
startDispatchCycleLocked(currentTime, connection);
2195
InputDispatcher::MotionEntry*
2196
InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2197
ALOG_ASSERT(pointerIds.value != 0);
2199
uint32_t splitPointerIndexMap[MAX_POINTERS];
2200
PointerProperties splitPointerProperties[MAX_POINTERS];
2201
PointerCoords splitPointerCoords[MAX_POINTERS];
2203
uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2204
uint32_t splitPointerCount = 0;
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;
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
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());
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;
2247
// A secondary pointer went down/up.
2248
uint32_t splitPointerIndex = 0;
2249
while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2250
splitPointerIndex += 1;
2252
action = maskedAction | (splitPointerIndex
2253
<< AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2256
// An unrelated pointer changed.
2257
action = AMOTION_EVENT_ACTION_MOVE;
2261
MotionEntry* splitMotionEntry = new MotionEntry(
2262
originalMotionEntry->eventTime,
2263
originalMotionEntry->deviceId,
2264
originalMotionEntry->source,
2265
originalMotionEntry->policyFlags,
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);
2276
if (originalMotionEntry->injectionState) {
2277
splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2278
splitMotionEntry->injectionState->refCount += 1;
2281
return splitMotionEntry;
2284
void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2285
#if DEBUG_INBOUND_EVENT_DETAILS
2286
ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
2291
AutoMutex _l(mLock);
2293
ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2294
needWake = enqueueInboundEventLocked(newEntry);
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);
2310
if (!validateKeyEvent(args->action)) {
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;
2321
if (policyFlags & POLICY_FLAG_ALT) {
2322
metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
2324
if (policyFlags & POLICY_FLAG_ALT_GR) {
2325
metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
2327
if (policyFlags & POLICY_FLAG_SHIFT) {
2328
metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
2330
if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
2331
metaState |= AMETA_CAPS_LOCK_ON;
2333
if (policyFlags & POLICY_FLAG_FUNCTION) {
2334
metaState |= AMETA_FUNCTION_ON;
2337
policyFlags |= POLICY_FLAG_TRUSTED;
2340
event.initialize(args->deviceId, args->source, args->action,
2341
flags, args->keyCode, args->scanCode, metaState, 0,
2342
args->downTime, args->eventTime);
2344
mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2346
if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2347
flags |= AKEY_EVENT_FLAG_WOKE_HERE;
2354
if (mInputFilterEnabled) {
2357
policyFlags |= POLICY_FLAG_FILTERED;
2358
if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2359
return; // event was consumed by the filter
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);
2371
needWake = enqueueInboundEventLocked(newEntry);
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, "
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));
2406
if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
2410
uint32_t policyFlags = args->policyFlags;
2411
policyFlags |= POLICY_FLAG_TRUSTED;
2412
mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
2418
if (mInputFilterEnabled) {
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);
2428
policyFlags |= POLICY_FLAG_FILTERED;
2429
if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2430
return; // event was consumed by the filter
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);
2443
needWake = enqueueInboundEventLocked(newEntry);
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);
2459
uint32_t policyFlags = args->policyFlags;
2460
policyFlags |= POLICY_FLAG_TRUSTED;
2461
mPolicy->notifySwitch(args->eventTime,
2462
args->switchCode, args->switchValue, policyFlags);
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);
2473
AutoMutex _l(mLock);
2475
DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2476
needWake = enqueueInboundEventLocked(newEntry);
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);
2493
nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2495
policyFlags |= POLICY_FLAG_INJECTED;
2496
if (hasInjectionPermission(injectorPid, injectorUid)) {
2497
policyFlags |= POLICY_FLAG_TRUSTED;
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;
2510
int32_t flags = keyEvent->getFlags();
2511
if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2512
policyFlags |= POLICY_FLAG_VIRTUAL;
2515
if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2516
mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2519
if (policyFlags & POLICY_FLAG_WOKE_HERE) {
2520
flags |= AKEY_EVENT_FLAG_WOKE_HERE;
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;
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;
2542
if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2543
nsecs_t eventTime = motionEvent->getEventTime();
2544
mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
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;
2577
ALOGW("Cannot inject event of type %d", event->getType());
2578
return INPUT_EVENT_INJECTION_FAILED;
2581
InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2582
if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2583
injectionState->injectionIsAsync = true;
2586
injectionState->refCount += 1;
2587
lastInjectedEntry->injectionState = injectionState;
2589
bool needWake = false;
2590
for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2591
EventEntry* nextEntry = entry->next;
2592
needWake |= enqueueInboundEventLocked(entry);
2602
int32_t injectionResult;
2604
AutoMutex _l(mLock);
2606
if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2607
injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2610
injectionResult = injectionState->injectionResult;
2611
if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2615
nsecs_t remainingTimeout = endTime - now();
2616
if (remainingTimeout <= 0) {
2618
ALOGD("injectInputEvent - Timed out waiting for injection result "
2619
"to become available.");
2621
injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2625
mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2628
if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2629
&& syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2630
while (injectionState->pendingForegroundDispatches != 0) {
2632
ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2633
injectionState->pendingForegroundDispatches);
2635
nsecs_t remainingTimeout = endTime - now();
2636
if (remainingTimeout <= 0) {
2638
ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2639
"dispatches to finish.");
2641
injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2645
mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2650
injectionState->release();
2654
ALOGD("injectInputEvent - Finished with result %d. "
2655
"injectorPid=%d, injectorUid=%d",
2656
injectionResult, injectorPid, injectorUid);
2659
return injectionResult;
2662
bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2663
return injectorUid == 0
2664
|| mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2667
void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2668
InjectionState* injectionState = entry->injectionState;
2669
if (injectionState) {
2671
ALOGD("Setting input event injection result to %d. "
2672
"injectorPid=%d, injectorUid=%d",
2673
injectionResult, injectionState->injectorPid, injectionState->injectorUid);
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.");
2683
case INPUT_EVENT_INJECTION_FAILED:
2684
ALOGW("Asynchronous input event injection failed.");
2686
case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2687
ALOGW("Asynchronous input event injection permission denied.");
2689
case INPUT_EVENT_INJECTION_TIMED_OUT:
2690
ALOGW("Asynchronous input event injection timed out.");
2695
injectionState->injectionResult = injectionResult;
2696
mInjectionResultAvailableCondition.broadcast();
2700
void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2701
InjectionState* injectionState = entry->injectionState;
2702
if (injectionState) {
2703
injectionState->pendingForegroundDispatches += 1;
2707
void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2708
InjectionState* injectionState = entry->injectionState;
2709
if (injectionState) {
2710
injectionState->pendingForegroundDispatches -= 1;
2712
if (injectionState->pendingForegroundDispatches == 0) {
2713
mInjectionSyncFinishedCondition.broadcast();
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;
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) {
2741
void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
2743
ALOGD("setInputWindows");
2746
AutoMutex _l(mLock);
2748
Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
2749
mWindowHandles = inputWindowHandles;
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--);
2759
if (windowHandle->getInfo()->hasFocus) {
2760
newFocusedWindowHandle = windowHandle;
2762
if (windowHandle == mLastHoverWindowHandle) {
2763
foundHoveredWindow = true;
2767
if (!foundHoveredWindow) {
2768
mLastHoverWindowHandle = NULL;
2771
if (mFocusedWindowHandle != newFocusedWindowHandle) {
2772
if (mFocusedWindowHandle != NULL) {
2774
ALOGD("Focus left window: %s",
2775
mFocusedWindowHandle->getName().string());
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);
2785
if (newFocusedWindowHandle != NULL) {
2787
ALOGD("Focus entered window: %s",
2788
newFocusedWindowHandle->getName().string());
2791
mFocusedWindowHandle = newFocusedWindowHandle;
2794
for (size_t i = 0; i < mTouchState.windows.size(); i++) {
2795
TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
2796
if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
2798
ALOGD("Touched window was removed: %s",
2799
touchedWindow.windowHandle->getName().string());
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);
2809
mTouchState.windows.removeAt(i--);
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)) {
2821
ALOGD("Window went away: %s", oldWindowHandle->getName().string());
2823
oldWindowHandle->releaseInfo();
2828
// Wake up poll loop since it may need to make new input dispatching choices.
2832
void InputDispatcher::setFocusedApplication(
2833
const sp<InputApplicationHandle>& inputApplicationHandle) {
2835
ALOGD("setFocusedApplication");
2838
AutoMutex _l(mLock);
2840
if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
2841
if (mFocusedApplicationHandle != inputApplicationHandle) {
2842
if (mFocusedApplicationHandle != NULL) {
2843
resetANRTimeoutsLocked();
2844
mFocusedApplicationHandle->releaseInfo();
2846
mFocusedApplicationHandle = inputApplicationHandle;
2848
} else if (mFocusedApplicationHandle != NULL) {
2849
resetANRTimeoutsLocked();
2850
mFocusedApplicationHandle->releaseInfo();
2851
mFocusedApplicationHandle.clear();
2855
//logDispatchStateLocked();
2859
// Wake up poll loop since it may need to make new input dispatching choices.
2863
void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2865
ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2870
AutoMutex _l(mLock);
2872
if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
2873
if (mDispatchFrozen && !frozen) {
2874
resetANRTimeoutsLocked();
2877
if (mDispatchEnabled && !enabled) {
2878
resetAndDropEverythingLocked("dispatcher is being disabled");
2881
mDispatchEnabled = enabled;
2882
mDispatchFrozen = frozen;
2889
//logDispatchStateLocked();
2894
// Wake up poll loop since it may need to make new input dispatching choices.
2899
void InputDispatcher::setInputFilterEnabled(bool enabled) {
2901
ALOGD("setInputFilterEnabled: enabled=%d", enabled);
2905
AutoMutex _l(mLock);
2907
if (mInputFilterEnabled == enabled) {
2911
mInputFilterEnabled = enabled;
2912
resetAndDropEverythingLocked("input filter is being enabled or disabled");
2915
// Wake up poll loop since there might be work to do to drop everything.
2919
bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2920
const sp<InputChannel>& toChannel) {
2922
ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
2923
fromChannel->getName().string(), toChannel->getName().string());
2926
AutoMutex _l(mLock);
2928
sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2929
sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
2930
if (fromWindowHandle == NULL || toWindowHandle == NULL) {
2932
ALOGD("Cannot transfer focus because from or to window not found.");
2936
if (fromWindowHandle == toWindowHandle) {
2938
ALOGD("Trivial transfer to same window.");
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;
2950
mTouchState.windows.removeAt(i);
2952
int32_t newTargetFlags = oldTargetFlags
2953
& (InputTarget::FLAG_FOREGROUND
2954
| InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
2955
mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
2964
ALOGD("Focus transfer failed because from window did not have focus.");
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);
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);
2982
logDispatchStateLocked();
2986
// Wake up poll loop since it may need to make new input dispatching choices.
2991
void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
2993
ALOGD("Resetting and dropping all events (%s).", reason);
2996
CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
2997
synthesizeCancelationEventsForAllConnectionsLocked(options);
2999
resetKeyRepeatLocked();
3000
releasePendingEventLocked();
3001
drainInboundQueueLocked();
3002
resetANRTimeoutsLocked();
3004
mTouchState.reset();
3005
mLastHoverWindowHandle.clear();
3008
void InputDispatcher::logDispatchStateLocked() {
3010
dumpDispatchStateLocked(dump);
3012
char* text = dump.lockBuffer(dump.size());
3014
while (*start != '\0') {
3015
char* end = strchr(start, '\n');
3024
void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
3025
dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3026
dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
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);
3034
dump.append(INDENT "FocusedApplication: <null>\n");
3036
dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
3037
mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
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);
3053
dump.append(INDENT "TouchedWindows: <none>\n");
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();
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, "
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,
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);
3084
dump.append(INDENT "Windows: <none>\n");
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());
3094
dump.append(INDENT "MonitoringChannels: <none>\n");
3097
nsecs_t currentTime = now();
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);
3108
dump.append(INDENT "InboundQueue: <empty>\n");
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));
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);
3133
dump.append(INDENT3 "OutboundQueue: <empty>\n");
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);
3150
dump.append(INDENT3 "WaitQueue: <empty>\n");
3154
dump.append(INDENT "Connections: <none>\n");
3157
if (isAppSwitchPendingLocked()) {
3158
dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
3159
(mAppSwitchDueTime - now()) / 1000000.0);
3161
dump.append(INDENT "AppSwitch: not pending\n");
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);
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(),
3179
AutoMutex _l(mLock);
3181
if (getConnectionIndexLocked(inputChannel) >= 0) {
3182
ALOGW("Attempted to register already registered input channel '%s'",
3183
inputChannel->getName().string());
3187
sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3189
int fd = inputChannel->getFd();
3190
mConnectionsByFd.add(fd, connection);
3193
mMonitoringChannels.push(inputChannel);
3196
mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3198
runCommandsLockedInterruptible();
3203
status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3204
#if DEBUG_REGISTRATION
3205
ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
3209
AutoMutex _l(mLock);
3211
status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3217
// Wake the poll loop because removing the connection may have changed the current
3218
// synchronization state.
3223
status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3225
ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3226
if (connectionIndex < 0) {
3227
ALOGW("Attempted to unregister already unregistered input channel '%s'",
3228
inputChannel->getName().string());
3232
sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3233
mConnectionsByFd.removeItemsAt(connectionIndex);
3235
if (connection->monitor) {
3236
removeMonitorChannelLocked(inputChannel);
3239
mLooper->removeFd(inputChannel->getFd());
3241
nsecs_t currentTime = now();
3242
abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3244
runCommandsLockedInterruptible();
3246
connection->status = Connection::STATUS_ZOMBIE;
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);
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;
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;
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());
3286
CommandEntry* commandEntry = postCommandLocked(
3287
& InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3288
commandEntry->connection = connection;
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);
3302
// Capture a record of the InputDispatcher state at the time of the ANR.
3303
time_t t = time(NULL);
3305
localtime_r(&t, &tm);
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);
3318
CommandEntry* commandEntry = postCommandLocked(
3319
& InputDispatcher::doNotifyANRLockedInterruptible);
3320
commandEntry->inputApplicationHandle = applicationHandle;
3321
commandEntry->inputWindowHandle = windowHandle;
3324
void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3325
CommandEntry* commandEntry) {
3328
mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3333
void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3334
CommandEntry* commandEntry) {
3335
sp<Connection> connection = commandEntry->connection;
3337
if (connection->status != Connection::STATUS_ZOMBIE) {
3340
mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3346
void InputDispatcher::doNotifyANRLockedInterruptible(
3347
CommandEntry* commandEntry) {
3350
nsecs_t newTimeout = mPolicy->notifyANR(
3351
commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
3355
resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3356
commandEntry->inputWindowHandle != NULL
3357
? commandEntry->inputWindowHandle->getInputChannel() : NULL);
3360
void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3361
CommandEntry* commandEntry) {
3362
KeyEntry* entry = commandEntry->keyEntry;
3365
initializeKeyEvent(&event, entry);
3369
nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3370
&event, entry->policyFlags);
3375
entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3376
} else if (!delay) {
3377
entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3379
entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3380
entry->interceptKeyWakeupTime = now() + delay;
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;
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) {
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());
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);
3414
restartEvent = false;
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
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);
3428
releaseDispatchEntryLocked(dispatchEntry);
3432
// Start the next dispatch cycle for this connection.
3433
startDispatchCycleLocked(now(), connection);
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);
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);
3461
initializeKeyEvent(&event, keyEntry);
3462
event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3466
mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3467
&event, keyEntry->policyFlags, &event);
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);
3480
connection->inputState.removeFallbackKey(originalKeyCode);
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);
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);
3507
initializeKeyEvent(&event, keyEntry);
3511
bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3512
&event, keyEntry->policyFlags, &event);
3516
if (connection->status != Connection::STATUS_NORMAL) {
3517
connection->inputState.removeFallbackKey(originalKeyCode);
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.
3525
fallbackKeyCode = event.getKeyCode();
3527
fallbackKeyCode = AKEYCODE_UNKNOWN;
3529
connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3532
ALOG_ASSERT(fallbackKeyCode != -1);
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
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);
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);
3553
CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3554
"canceling fallback, policy no longer desires it");
3555
options.keyCode = fallbackKeyCode;
3556
synthesizeCancelationEventsForConnectionLocked(connection, options);
3559
fallbackKeyCode = AKEYCODE_UNKNOWN;
3560
if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3561
connection->inputState.setFallbackKey(originalKeyCode,
3566
#if DEBUG_OUTBOUND_EVENT_DETAILS
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));
3575
ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3576
fallbackKeys.size(), msg.string());
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;
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);
3598
return true; // restart the event
3600
#if DEBUG_OUTBOUND_EVENT_DETAILS
3601
ALOGD("Unhandled key event: No fallback key.");
3609
bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3610
DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3614
void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3617
mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
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);
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.
3633
void InputDispatcher::traceInboundQueueLengthLocked() {
3634
if (ATRACE_ENABLED()) {
3635
ATRACE_INT("iq", mInboundQueue.count());
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());
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());
3655
void InputDispatcher::dump(String8& dump) {
3656
AutoMutex _l(mLock);
3658
dump.append("Input Dispatcher State:\n");
3659
dumpDispatchStateLocked(dump);
3661
if (!mLastANRState.isEmpty()) {
3662
dump.append("\nInput Dispatcher State at time of last ANR:\n");
3663
dump.append(mLastANRState);
3667
void InputDispatcher::monitor() {
3668
// Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3671
mDispatcherIsAliveCondition.wait(mLock);
3676
// --- InputDispatcher::Queue ---
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) {
3688
// --- InputDispatcher::InjectionState ---
3690
InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3692
injectorPid(injectorPid), injectorUid(injectorUid),
3693
injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3694
pendingForegroundDispatches(0) {
3697
InputDispatcher::InjectionState::~InjectionState() {
3700
void InputDispatcher::InjectionState::release() {
3702
if (refCount == 0) {
3705
ALOG_ASSERT(refCount > 0);
3710
// --- InputDispatcher::EventEntry ---
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) {
3717
InputDispatcher::EventEntry::~EventEntry() {
3718
releaseInjectionState();
3721
void InputDispatcher::EventEntry::release() {
3723
if (refCount == 0) {
3726
ALOG_ASSERT(refCount > 0);
3730
void InputDispatcher::EventEntry::releaseInjectionState() {
3731
if (injectionState) {
3732
injectionState->release();
3733
injectionState = NULL;
3738
// --- InputDispatcher::ConfigurationChangedEntry ---
3740
InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3741
EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3744
InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3747
void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
3748
msg.append("ConfigurationChangedEvent()");
3752
// --- InputDispatcher::DeviceResetEntry ---
3754
InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3755
EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3756
deviceId(deviceId) {
3759
InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3762
void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
3763
msg.appendFormat("DeviceResetEvent(deviceId=%d)", deviceId);
3767
// --- InputDispatcher::KeyEntry ---
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) {
3781
InputDispatcher::KeyEntry::~KeyEntry() {
3784
void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
3785
msg.appendFormat("KeyEvent(action=%d, deviceId=%d, source=0x%08x)",
3786
action, deviceId, source);
3789
void InputDispatcher::KeyEntry::recycle() {
3790
releaseInjectionState();
3792
dispatchInProgress = false;
3793
syntheticRepeat = false;
3794
interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
3795
interceptKeyWakeupTime = 0;
3799
// --- InputDispatcher::MotionEntry ---
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]);
3819
InputDispatcher::MotionEntry::~MotionEntry() {
3822
void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
3823
msg.appendFormat("MotionEvent(action=%d, deviceId=%d, source=0x%08x)",
3824
action, deviceId, source);
3828
// --- InputDispatcher::DispatchEntry ---
3830
volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3832
InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3833
int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
3835
eventEntry(eventEntry), targetFlags(targetFlags),
3836
xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
3837
deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
3838
eventEntry->refCount += 1;
3841
InputDispatcher::DispatchEntry::~DispatchEntry() {
3842
eventEntry->release();
3845
uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3846
// Sequence number 0 is reserved and will never be returned.
3849
seq = android_atomic_inc(&sNextSeqAtomic);
3855
// --- InputDispatcher::InputState ---
3857
InputDispatcher::InputState::InputState() {
3860
InputDispatcher::InputState::~InputState() {
3863
bool InputDispatcher::InputState::isNeutral() const {
3864
return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
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) {
3879
bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
3880
int32_t action, int32_t flags) {
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);
3892
ssize_t index = findKeyMemento(entry);
3894
mKeyMementos.removeAt(index);
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.
3904
* So for now, allow inconsistent key up events to be dispatched.
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);
3916
case AKEY_EVENT_ACTION_DOWN: {
3917
ssize_t index = findKeyMemento(entry);
3919
mKeyMementos.removeAt(index);
3921
addKeyMemento(entry, flags);
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*/);
3938
mMotionMementos.removeAt(index);
3941
#if DEBUG_OUTBOUND_EVENT_DETAILS
3942
ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
3944
entry->deviceId, entry->source, actionMasked);
3949
case AMOTION_EVENT_ACTION_DOWN: {
3950
ssize_t index = findMotionMemento(entry, false /*hovering*/);
3952
mMotionMementos.removeAt(index);
3954
addMotionMemento(entry, flags, false /*hovering*/);
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*/);
3963
MotionMemento& memento = mMotionMementos.editItemAt(index);
3964
memento.setPointers(entry);
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.
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);
3981
case AMOTION_EVENT_ACTION_HOVER_EXIT: {
3982
ssize_t index = findMotionMemento(entry, true /*hovering*/);
3984
mMotionMementos.removeAt(index);
3987
#if DEBUG_OUTBOUND_EVENT_DETAILS
3988
ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
3989
entry->deviceId, entry->source);
3994
case AMOTION_EVENT_ACTION_HOVER_ENTER:
3995
case AMOTION_EVENT_ACTION_HOVER_MOVE: {
3996
ssize_t index = findMotionMemento(entry, true /*hovering*/);
3998
mMotionMementos.removeAt(index);
4000
addMotionMemento(entry, flags, true /*hovering*/);
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) {
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) {
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;
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;
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]);
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));
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,
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));
4098
void InputDispatcher::InputState::clear() {
4099
mKeyMementos.clear();
4100
mMotionMementos.clear();
4101
mFallbackKeys.clear();
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);
4117
other.mMotionMementos.push(memento);
4122
int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4123
ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4124
return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4127
void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4128
int32_t fallbackKeyCode) {
4129
ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4131
mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4133
mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4137
void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4138
mFallbackKeys.removeItem(originalKeyCode);
4141
bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4142
const CancelationOptions& options) {
4143
if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4147
if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4151
switch (options.mode) {
4152
case CancelationOptions::CANCEL_ALL_EVENTS:
4153
case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4155
case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4156
return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4162
bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4163
const CancelationOptions& options) {
4164
if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4168
switch (options.mode) {
4169
case CancelationOptions::CANCEL_ALL_EVENTS:
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);
4181
// --- InputDispatcher::Connection ---
4183
InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4184
const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4185
status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4187
inputPublisher(inputChannel), inputPublisherBlocked(false) {
4190
InputDispatcher::Connection::~Connection() {
4193
const char* InputDispatcher::Connection::getWindowName() const {
4194
if (inputWindowHandle != NULL) {
4195
return inputWindowHandle->getName().string();
4203
const char* InputDispatcher::Connection::getStatusLabel() const {
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) {
4229
// --- InputDispatcher::CommandEntry ---
4231
InputDispatcher::CommandEntry::CommandEntry(Command command) :
4232
command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4233
seq(0), handled(false) {
4236
InputDispatcher::CommandEntry::~CommandEntry() {
4240
// --- InputDispatcher::TouchState ---
4242
InputDispatcher::TouchState::TouchState() :
4243
down(false), split(false), deviceId(-1), source(0) {
4246
InputDispatcher::TouchState::~TouchState() {
4249
void InputDispatcher::TouchState::reset() {
4257
void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4259
split = other.split;
4260
deviceId = other.deviceId;
4261
source = other.source;
4262
windows = other.windows;
4265
void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4266
int32_t targetFlags, BitSet32 pointerIds) {
4267
if (targetFlags & InputTarget::FLAG_SPLIT) {
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;
4278
touchedWindow.pointerIds.value |= pointerIds.value;
4285
TouchedWindow& touchedWindow = windows.editTop();
4286
touchedWindow.windowHandle = windowHandle;
4287
touchedWindow.targetFlags = targetFlags;
4288
touchedWindow.pointerIds = pointerIds;
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);
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;
4309
windows.removeAt(i);
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;
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)) {
4335
haveSlipperyForegroundWindow = true;
4338
return haveSlipperyForegroundWindow;
4342
// --- InputDispatcherThread ---
4344
InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4345
Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4348
InputDispatcherThread::~InputDispatcherThread() {
4351
bool InputDispatcherThread::threadLoop() {
4352
mDispatcher->dispatchOnce();
4356
} // namespace android