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