blob: ffaa7e72fbbe8e21fd24bcae395d492ca776c11e [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) {
862 return true;
863 }
864
865 // TODO: support sending secondary display events to input monitors
866 if (isMainDisplay(entry->displayId)) {
867 addMonitoringTargetsLocked(inputTargets);
868 }
869
870 // Dispatch the motion.
871 if (conflictingPointerActions) {
872 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
873 "conflicting pointer actions");
874 synthesizeCancelationEventsForAllConnectionsLocked(options);
875 }
876 dispatchEventLocked(currentTime, entry, inputTargets);
877 return true;
878}
879
880
881void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
882#if DEBUG_OUTBOUND_EVENT_DETAILS
883 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100884 "action=0x%x, actionButton=0x%x, flags=0x%x, "
885 "metaState=0x%x, buttonState=0x%x,"
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
887 prefix,
888 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +0100889 entry->action, entry->actionButton entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 entry->metaState, entry->buttonState,
891 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
892 entry->downTime);
893
894 for (uint32_t i = 0; i < entry->pointerCount; i++) {
895 ALOGD(" Pointer %d: id=%d, toolType=%d, "
896 "x=%f, y=%f, pressure=%f, size=%f, "
897 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
898 "orientation=%f",
899 i, entry->pointerProperties[i].id,
900 entry->pointerProperties[i].toolType,
901 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
902 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
903 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
904 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
905 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
906 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
907 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
908 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
909 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
910 }
911#endif
912}
913
914void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
915 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
916#if DEBUG_DISPATCH_CYCLE
917 ALOGD("dispatchEventToCurrentInputTargets");
918#endif
919
920 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
921
922 pokeUserActivityLocked(eventEntry);
923
924 for (size_t i = 0; i < inputTargets.size(); i++) {
925 const InputTarget& inputTarget = inputTargets.itemAt(i);
926
927 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
928 if (connectionIndex >= 0) {
929 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
930 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
931 } else {
932#if DEBUG_FOCUS
933 ALOGD("Dropping event delivery to target with channel '%s' because it "
934 "is no longer registered with the input dispatcher.",
935 inputTarget.inputChannel->getName().string());
936#endif
937 }
938 }
939}
940
941int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
942 const EventEntry* entry,
943 const sp<InputApplicationHandle>& applicationHandle,
944 const sp<InputWindowHandle>& windowHandle,
945 nsecs_t* nextWakeupTime, const char* reason) {
946 if (applicationHandle == NULL && windowHandle == NULL) {
947 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
948#if DEBUG_FOCUS
949 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
950#endif
951 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
952 mInputTargetWaitStartTime = currentTime;
953 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
954 mInputTargetWaitTimeoutExpired = false;
955 mInputTargetWaitApplicationHandle.clear();
956 }
957 } else {
958 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
959#if DEBUG_FOCUS
960 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
961 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
962 reason);
963#endif
964 nsecs_t timeout;
965 if (windowHandle != NULL) {
966 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
967 } else if (applicationHandle != NULL) {
968 timeout = applicationHandle->getDispatchingTimeout(
969 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
970 } else {
971 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
972 }
973
974 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
975 mInputTargetWaitStartTime = currentTime;
976 mInputTargetWaitTimeoutTime = currentTime + timeout;
977 mInputTargetWaitTimeoutExpired = false;
978 mInputTargetWaitApplicationHandle.clear();
979
980 if (windowHandle != NULL) {
981 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
982 }
983 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
984 mInputTargetWaitApplicationHandle = applicationHandle;
985 }
986 }
987 }
988
989 if (mInputTargetWaitTimeoutExpired) {
990 return INPUT_EVENT_INJECTION_TIMED_OUT;
991 }
992
993 if (currentTime >= mInputTargetWaitTimeoutTime) {
994 onANRLocked(currentTime, applicationHandle, windowHandle,
995 entry->eventTime, mInputTargetWaitStartTime, reason);
996
997 // Force poll loop to wake up immediately on next iteration once we get the
998 // ANR response back from the policy.
999 *nextWakeupTime = LONG_LONG_MIN;
1000 return INPUT_EVENT_INJECTION_PENDING;
1001 } else {
1002 // Force poll loop to wake up when timeout is due.
1003 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1004 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1005 }
1006 return INPUT_EVENT_INJECTION_PENDING;
1007 }
1008}
1009
1010void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1011 const sp<InputChannel>& inputChannel) {
1012 if (newTimeout > 0) {
1013 // Extend the timeout.
1014 mInputTargetWaitTimeoutTime = now() + newTimeout;
1015 } else {
1016 // Give up.
1017 mInputTargetWaitTimeoutExpired = true;
1018
1019 // Input state will not be realistic. Mark it out of sync.
1020 if (inputChannel.get()) {
1021 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1022 if (connectionIndex >= 0) {
1023 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1024 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1025
1026 if (windowHandle != NULL) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001027 const InputWindowInfo* info = windowHandle->getInfo();
1028 if (info) {
1029 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId);
1030 if (stateIndex >= 0) {
1031 mTouchStatesByDisplay.editValueAt(stateIndex).removeWindow(
1032 windowHandle);
1033 }
1034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 }
1036
1037 if (connection->status == Connection::STATUS_NORMAL) {
1038 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1039 "application not responding");
1040 synthesizeCancelationEventsForConnectionLocked(connection, options);
1041 }
1042 }
1043 }
1044 }
1045}
1046
1047nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1048 nsecs_t currentTime) {
1049 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1050 return currentTime - mInputTargetWaitStartTime;
1051 }
1052 return 0;
1053}
1054
1055void InputDispatcher::resetANRTimeoutsLocked() {
1056#if DEBUG_FOCUS
1057 ALOGD("Resetting ANR timeouts.");
1058#endif
1059
1060 // Reset input target wait timeout.
1061 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1062 mInputTargetWaitApplicationHandle.clear();
1063}
1064
1065int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1066 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1067 int32_t injectionResult;
Jeff Brownffb49772014-10-10 19:01:34 -07001068 String8 reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069
1070 // If there is no currently focused window and no focused application
1071 // then drop the event.
1072 if (mFocusedWindowHandle == NULL) {
1073 if (mFocusedApplicationHandle != NULL) {
1074 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1075 mFocusedApplicationHandle, NULL, nextWakeupTime,
1076 "Waiting because no window has focus but there is a "
1077 "focused application that may eventually add a window "
1078 "when it finishes starting up.");
1079 goto Unresponsive;
1080 }
1081
1082 ALOGI("Dropping event because there is no focused window or focused application.");
1083 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1084 goto Failed;
1085 }
1086
1087 // Check permissions.
1088 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
1089 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1090 goto Failed;
1091 }
1092
Jeff Brownffb49772014-10-10 19:01:34 -07001093 // Check whether the window is ready for more input.
1094 reason = checkWindowReadyForMoreInputLocked(currentTime,
1095 mFocusedWindowHandle, entry, "focused");
1096 if (!reason.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brownffb49772014-10-10 19:01:34 -07001098 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, reason.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 goto Unresponsive;
1100 }
1101
1102 // Success! Output targets.
1103 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1104 addWindowTargetLocked(mFocusedWindowHandle,
1105 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1106 inputTargets);
1107
1108 // Done.
1109Failed:
1110Unresponsive:
1111 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1112 updateDispatchStatisticsLocked(currentTime, entry,
1113 injectionResult, timeSpentWaitingForApplication);
1114#if DEBUG_FOCUS
1115 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1116 "timeSpentWaitingForApplication=%0.1fms",
1117 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1118#endif
1119 return injectionResult;
1120}
1121
1122int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1123 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1124 bool* outConflictingPointerActions) {
1125 enum InjectionPermission {
1126 INJECTION_PERMISSION_UNKNOWN,
1127 INJECTION_PERMISSION_GRANTED,
1128 INJECTION_PERMISSION_DENIED
1129 };
1130
1131 nsecs_t startTime = now();
1132
1133 // For security reasons, we defer updating the touch state until we are sure that
1134 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135 int32_t displayId = entry->displayId;
1136 int32_t action = entry->action;
1137 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1138
1139 // Update the touch state as needed based on the properties of the touch event.
1140 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1141 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1142 sp<InputWindowHandle> newHoverWindowHandle;
1143
Jeff Brownf086ddb2014-02-11 14:28:48 -08001144 // Copy current touch state into mTempTouchState.
1145 // This state is always reset at the end of this function, so if we don't find state
1146 // for the specified display then our initial state will be empty.
1147 const TouchState* oldState = NULL;
1148 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1149 if (oldStateIndex >= 0) {
1150 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1151 mTempTouchState.copyFrom(*oldState);
1152 }
1153
1154 bool isSplit = mTempTouchState.split;
1155 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1156 && (mTempTouchState.deviceId != entry->deviceId
1157 || mTempTouchState.source != entry->source
1158 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1160 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1161 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1162 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1163 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1164 || isHoverAction);
1165 bool wrongDevice = false;
1166 if (newGesture) {
1167 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001168 if (switchedDevice && mTempTouchState.down && !down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169#if DEBUG_FOCUS
1170 ALOGD("Dropping event because a pointer for a different device is already down.");
1171#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1173 switchedDevice = false;
1174 wrongDevice = true;
1175 goto Failed;
1176 }
1177 mTempTouchState.reset();
1178 mTempTouchState.down = down;
1179 mTempTouchState.deviceId = entry->deviceId;
1180 mTempTouchState.source = entry->source;
1181 mTempTouchState.displayId = displayId;
1182 isSplit = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 }
1184
1185 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1186 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1187
1188 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1189 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1190 getAxisValue(AMOTION_EVENT_AXIS_X));
1191 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1192 getAxisValue(AMOTION_EVENT_AXIS_Y));
1193 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 bool isTouchModal = false;
1195
1196 // Traverse windows from front to back to find touched window and outside targets.
1197 size_t numWindows = mWindowHandles.size();
1198 for (size_t i = 0; i < numWindows; i++) {
1199 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1200 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1201 if (windowInfo->displayId != displayId) {
1202 continue; // wrong display
1203 }
1204
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 int32_t flags = windowInfo->layoutParamsFlags;
1206 if (windowInfo->visible) {
1207 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1208 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1209 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1210 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001211 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212 break; // found touched window, exit window loop
1213 }
1214 }
1215
1216 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1217 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
1218 int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
1219 if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
1220 outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1221 }
1222
1223 mTempTouchState.addOrUpdateWindow(
1224 windowHandle, outsideTargetFlags, BitSet32(0));
1225 }
1226 }
1227 }
1228
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 // Figure out whether splitting will be allowed for this window.
1230 if (newTouchedWindowHandle != NULL
1231 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1232 // New window supports splitting.
1233 isSplit = true;
1234 } else if (isSplit) {
1235 // New window does not support splitting but we have already split events.
1236 // Ignore the new window.
1237 newTouchedWindowHandle = NULL;
1238 }
1239
1240 // Handle the case where we did not find a window.
1241 if (newTouchedWindowHandle == NULL) {
1242 // Try to assign the pointer to the first foreground window we find, if there is one.
1243 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1244 if (newTouchedWindowHandle == NULL) {
1245 ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y);
1246 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1247 goto Failed;
1248 }
1249 }
1250
1251 // Set target flags.
1252 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1253 if (isSplit) {
1254 targetFlags |= InputTarget::FLAG_SPLIT;
1255 }
1256 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1257 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1258 }
1259
1260 // Update hover state.
1261 if (isHoverAction) {
1262 newHoverWindowHandle = newTouchedWindowHandle;
1263 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1264 newHoverWindowHandle = mLastHoverWindowHandle;
1265 }
1266
1267 // Update the temporary touch state.
1268 BitSet32 pointerIds;
1269 if (isSplit) {
1270 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1271 pointerIds.markBit(pointerId);
1272 }
1273 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1274 } else {
1275 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1276
1277 // If the pointer is not currently down, then ignore the event.
1278 if (! mTempTouchState.down) {
1279#if DEBUG_FOCUS
1280 ALOGD("Dropping event because the pointer is not down or we previously "
1281 "dropped the pointer down event.");
1282#endif
1283 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1284 goto Failed;
1285 }
1286
1287 // Check whether touches should slip outside of the current foreground window.
1288 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1289 && entry->pointerCount == 1
1290 && mTempTouchState.isSlippery()) {
1291 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1292 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1293
1294 sp<InputWindowHandle> oldTouchedWindowHandle =
1295 mTempTouchState.getFirstForegroundWindowHandle();
1296 sp<InputWindowHandle> newTouchedWindowHandle =
1297 findTouchedWindowAtLocked(displayId, x, y);
1298 if (oldTouchedWindowHandle != newTouchedWindowHandle
1299 && newTouchedWindowHandle != NULL) {
1300#if DEBUG_FOCUS
1301 ALOGD("Touch is slipping out of window %s into window %s.",
1302 oldTouchedWindowHandle->getName().string(),
1303 newTouchedWindowHandle->getName().string());
1304#endif
1305 // Make a slippery exit from the old window.
1306 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1307 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1308
1309 // Make a slippery entrance into the new window.
1310 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1311 isSplit = true;
1312 }
1313
1314 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1315 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1316 if (isSplit) {
1317 targetFlags |= InputTarget::FLAG_SPLIT;
1318 }
1319 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1320 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1321 }
1322
1323 BitSet32 pointerIds;
1324 if (isSplit) {
1325 pointerIds.markBit(entry->pointerProperties[0].id);
1326 }
1327 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1328 }
1329 }
1330 }
1331
1332 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1333 // Let the previous window know that the hover sequence is over.
1334 if (mLastHoverWindowHandle != NULL) {
1335#if DEBUG_HOVER
1336 ALOGD("Sending hover exit event to window %s.",
1337 mLastHoverWindowHandle->getName().string());
1338#endif
1339 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1340 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1341 }
1342
1343 // Let the new window know that the hover sequence is starting.
1344 if (newHoverWindowHandle != NULL) {
1345#if DEBUG_HOVER
1346 ALOGD("Sending hover enter event to window %s.",
1347 newHoverWindowHandle->getName().string());
1348#endif
1349 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1350 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1351 }
1352 }
1353
1354 // Check permission to inject into all touched foreground windows and ensure there
1355 // is at least one touched foreground window.
1356 {
1357 bool haveForegroundWindow = false;
1358 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1359 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1360 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1361 haveForegroundWindow = true;
1362 if (! checkInjectionPermission(touchedWindow.windowHandle,
1363 entry->injectionState)) {
1364 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1365 injectionPermission = INJECTION_PERMISSION_DENIED;
1366 goto Failed;
1367 }
1368 }
1369 }
1370 if (! haveForegroundWindow) {
1371#if DEBUG_FOCUS
1372 ALOGD("Dropping event because there is no touched foreground window to receive it.");
1373#endif
1374 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1375 goto Failed;
1376 }
1377
1378 // Permission granted to injection into all touched foreground windows.
1379 injectionPermission = INJECTION_PERMISSION_GRANTED;
1380 }
1381
1382 // Check whether windows listening for outside touches are owned by the same UID. If it is
1383 // set the policy flag that we will not reveal coordinate information to this window.
1384 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1385 sp<InputWindowHandle> foregroundWindowHandle =
1386 mTempTouchState.getFirstForegroundWindowHandle();
1387 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1388 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1389 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1390 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1391 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1392 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1393 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1394 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1395 }
1396 }
1397 }
1398 }
1399
1400 // Ensure all touched foreground windows are ready for new input.
1401 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1402 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1403 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001404 // Check whether the window is ready for more input.
1405 String8 reason = checkWindowReadyForMoreInputLocked(currentTime,
1406 touchedWindow.windowHandle, entry, "touched");
1407 if (!reason.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brownffb49772014-10-10 19:01:34 -07001409 NULL, touchedWindow.windowHandle, nextWakeupTime, reason.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001410 goto Unresponsive;
1411 }
1412 }
1413 }
1414
1415 // If this is the first pointer going down and the touched window has a wallpaper
1416 // then also add the touched wallpaper windows so they are locked in for the duration
1417 // of the touch gesture.
1418 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1419 // engine only supports touch events. We would need to add a mechanism similar
1420 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1421 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1422 sp<InputWindowHandle> foregroundWindowHandle =
1423 mTempTouchState.getFirstForegroundWindowHandle();
1424 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
1425 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1426 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1427 const InputWindowInfo* info = windowHandle->getInfo();
1428 if (info->displayId == displayId
1429 && windowHandle->getInfo()->layoutParamsType
1430 == InputWindowInfo::TYPE_WALLPAPER) {
1431 mTempTouchState.addOrUpdateWindow(windowHandle,
1432 InputTarget::FLAG_WINDOW_IS_OBSCURED
1433 | InputTarget::FLAG_DISPATCH_AS_IS,
1434 BitSet32(0));
1435 }
1436 }
1437 }
1438 }
1439
1440 // Success! Output targets.
1441 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1442
1443 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1444 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1445 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1446 touchedWindow.pointerIds, inputTargets);
1447 }
1448
1449 // Drop the outside or hover touch windows since we will not care about them
1450 // in the next iteration.
1451 mTempTouchState.filterNonAsIsTouchWindows();
1452
1453Failed:
1454 // Check injection permission once and for all.
1455 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
1456 if (checkInjectionPermission(NULL, entry->injectionState)) {
1457 injectionPermission = INJECTION_PERMISSION_GRANTED;
1458 } else {
1459 injectionPermission = INJECTION_PERMISSION_DENIED;
1460 }
1461 }
1462
1463 // Update final pieces of touch state if the injector had permission.
1464 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1465 if (!wrongDevice) {
1466 if (switchedDevice) {
1467#if DEBUG_FOCUS
1468 ALOGD("Conflicting pointer actions: Switched to a different device.");
1469#endif
1470 *outConflictingPointerActions = true;
1471 }
1472
1473 if (isHoverAction) {
1474 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001475 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476#if DEBUG_FOCUS
1477 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1478#endif
1479 *outConflictingPointerActions = true;
1480 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001481 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1483 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001484 mTempTouchState.deviceId = entry->deviceId;
1485 mTempTouchState.source = entry->source;
1486 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 }
1488 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1489 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1490 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001491 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1493 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001494 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495#if DEBUG_FOCUS
1496 ALOGD("Conflicting pointer actions: Down received while already down.");
1497#endif
1498 *outConflictingPointerActions = true;
1499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1501 // One pointer went up.
1502 if (isSplit) {
1503 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1504 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1505
1506 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1507 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1508 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1509 touchedWindow.pointerIds.clearBit(pointerId);
1510 if (touchedWindow.pointerIds.isEmpty()) {
1511 mTempTouchState.windows.removeAt(i);
1512 continue;
1513 }
1514 }
1515 i += 1;
1516 }
1517 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001518 }
1519
1520 // Save changes unless the action was scroll in which case the temporary touch
1521 // state was only valid for this one action.
1522 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1523 if (mTempTouchState.displayId >= 0) {
1524 if (oldStateIndex >= 0) {
1525 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1526 } else {
1527 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1528 }
1529 } else if (oldStateIndex >= 0) {
1530 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 }
1533
1534 // Update hover state.
1535 mLastHoverWindowHandle = newHoverWindowHandle;
1536 }
1537 } else {
1538#if DEBUG_FOCUS
1539 ALOGD("Not updating touch focus because injection was denied.");
1540#endif
1541 }
1542
1543Unresponsive:
1544 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1545 mTempTouchState.reset();
1546
1547 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1548 updateDispatchStatisticsLocked(currentTime, entry,
1549 injectionResult, timeSpentWaitingForApplication);
1550#if DEBUG_FOCUS
1551 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1552 "timeSpentWaitingForApplication=%0.1fms",
1553 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1554#endif
1555 return injectionResult;
1556}
1557
1558void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1559 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1560 inputTargets.push();
1561
1562 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1563 InputTarget& target = inputTargets.editTop();
1564 target.inputChannel = windowInfo->inputChannel;
1565 target.flags = targetFlags;
1566 target.xOffset = - windowInfo->frameLeft;
1567 target.yOffset = - windowInfo->frameTop;
1568 target.scaleFactor = windowInfo->scaleFactor;
1569 target.pointerIds = pointerIds;
1570}
1571
1572void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
1573 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1574 inputTargets.push();
1575
1576 InputTarget& target = inputTargets.editTop();
1577 target.inputChannel = mMonitoringChannels[i];
1578 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1579 target.xOffset = 0;
1580 target.yOffset = 0;
1581 target.pointerIds.clear();
1582 target.scaleFactor = 1.0f;
1583 }
1584}
1585
1586bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1587 const InjectionState* injectionState) {
1588 if (injectionState
1589 && (windowHandle == NULL
1590 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1591 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1592 if (windowHandle != NULL) {
1593 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1594 "owned by uid %d",
1595 injectionState->injectorPid, injectionState->injectorUid,
1596 windowHandle->getName().string(),
1597 windowHandle->getInfo()->ownerUid);
1598 } else {
1599 ALOGW("Permission denied: injecting event from pid %d uid %d",
1600 injectionState->injectorPid, injectionState->injectorUid);
1601 }
1602 return false;
1603 }
1604 return true;
1605}
1606
1607bool InputDispatcher::isWindowObscuredAtPointLocked(
1608 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1609 int32_t displayId = windowHandle->getInfo()->displayId;
1610 size_t numWindows = mWindowHandles.size();
1611 for (size_t i = 0; i < numWindows; i++) {
1612 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1613 if (otherHandle == windowHandle) {
1614 break;
1615 }
1616
1617 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1618 if (otherInfo->displayId == displayId
1619 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1620 && otherInfo->frameContainsPoint(x, y)) {
1621 return true;
1622 }
1623 }
1624 return false;
1625}
1626
Jeff Brownffb49772014-10-10 19:01:34 -07001627String8 InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
1628 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1629 const char* targetType) {
1630 // If the window is paused then keep waiting.
1631 if (windowHandle->getInfo()->paused) {
1632 return String8::format("Waiting because the %s window is paused.", targetType);
1633 }
1634
1635 // If the window's connection is not registered then keep waiting.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brownffb49772014-10-10 19:01:34 -07001637 if (connectionIndex < 0) {
1638 return String8::format("Waiting because the %s window's input channel is not "
1639 "registered with the input dispatcher. The window may be in the process "
1640 "of being removed.", targetType);
1641 }
1642
1643 // If the connection is dead then keep waiting.
1644 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1645 if (connection->status != Connection::STATUS_NORMAL) {
1646 return String8::format("Waiting because the %s window's input connection is %s."
1647 "The window may be in the process of being removed.", targetType,
1648 connection->getStatusLabel());
1649 }
1650
1651 // If the connection is backed up then keep waiting.
1652 if (connection->inputPublisherBlocked) {
1653 return String8::format("Waiting because the %s window's input channel is full. "
1654 "Outbound queue length: %d. Wait queue length: %d.",
1655 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1656 }
1657
1658 // Ensure that the dispatch queues aren't too far backed up for this event.
1659 if (eventEntry->type == EventEntry::TYPE_KEY) {
1660 // If the event is a key event, then we must wait for all previous events to
1661 // complete before delivering it because previous events may have the
1662 // side-effect of transferring focus to a different window and we want to
1663 // ensure that the following keys are sent to the new window.
1664 //
1665 // Suppose the user touches a button in a window then immediately presses "A".
1666 // If the button causes a pop-up window to appear then we want to ensure that
1667 // the "A" key is delivered to the new pop-up window. This is because users
1668 // often anticipate pending UI changes when typing on a keyboard.
1669 // To obtain this behavior, we must serialize key events with respect to all
1670 // prior input events.
1671 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
1672 return String8::format("Waiting to send key event because the %s window has not "
1673 "finished processing all of the input events that were previously "
1674 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1675 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 }
Jeff Brownffb49772014-10-10 19:01:34 -07001677 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 // Touch events can always be sent to a window immediately because the user intended
1679 // to touch whatever was visible at the time. Even if focus changes or a new
1680 // window appears moments later, the touch event was meant to be delivered to
1681 // whatever window happened to be on screen at the time.
1682 //
1683 // Generic motion events, such as trackball or joystick events are a little trickier.
1684 // Like key events, generic motion events are delivered to the focused window.
1685 // Unlike key events, generic motion events don't tend to transfer focus to other
1686 // windows and it is not important for them to be serialized. So we prefer to deliver
1687 // generic motion events as soon as possible to improve efficiency and reduce lag
1688 // through batching.
1689 //
1690 // The one case where we pause input event delivery is when the wait queue is piling
1691 // up with lots of events because the application is not responding.
1692 // This condition ensures that ANRs are detected reliably.
1693 if (!connection->waitQueue.isEmpty()
1694 && currentTime >= connection->waitQueue.head->deliveryTime
1695 + STREAM_AHEAD_EVENT_TIMEOUT) {
Jeff Brownffb49772014-10-10 19:01:34 -07001696 return String8::format("Waiting to send non-key event because the %s window has not "
1697 "finished processing certain input events that were delivered to it over "
1698 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1699 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1700 connection->waitQueue.count(),
1701 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702 }
1703 }
Jeff Brownffb49772014-10-10 19:01:34 -07001704 return String8::empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001705}
1706
1707String8 InputDispatcher::getApplicationWindowLabelLocked(
1708 const sp<InputApplicationHandle>& applicationHandle,
1709 const sp<InputWindowHandle>& windowHandle) {
1710 if (applicationHandle != NULL) {
1711 if (windowHandle != NULL) {
1712 String8 label(applicationHandle->getName());
1713 label.append(" - ");
1714 label.append(windowHandle->getName());
1715 return label;
1716 } else {
1717 return applicationHandle->getName();
1718 }
1719 } else if (windowHandle != NULL) {
1720 return windowHandle->getName();
1721 } else {
1722 return String8("<unknown application or window>");
1723 }
1724}
1725
1726void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
1727 if (mFocusedWindowHandle != NULL) {
1728 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1729 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1730#if DEBUG_DISPATCH_CYCLE
1731 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.string());
1732#endif
1733 return;
1734 }
1735 }
1736
1737 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1738 switch (eventEntry->type) {
1739 case EventEntry::TYPE_MOTION: {
1740 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1741 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1742 return;
1743 }
1744
1745 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1746 eventType = USER_ACTIVITY_EVENT_TOUCH;
1747 }
1748 break;
1749 }
1750 case EventEntry::TYPE_KEY: {
1751 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1752 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1753 return;
1754 }
1755 eventType = USER_ACTIVITY_EVENT_BUTTON;
1756 break;
1757 }
1758 }
1759
1760 CommandEntry* commandEntry = postCommandLocked(
1761 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1762 commandEntry->eventTime = eventEntry->eventTime;
1763 commandEntry->userActivityEventType = eventType;
1764}
1765
1766void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1767 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1768#if DEBUG_DISPATCH_CYCLE
1769 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1770 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1771 "pointerIds=0x%x",
1772 connection->getInputChannelName(), inputTarget->flags,
1773 inputTarget->xOffset, inputTarget->yOffset,
1774 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1775#endif
1776
1777 // Skip this event if the connection status is not normal.
1778 // We don't want to enqueue additional outbound events if the connection is broken.
1779 if (connection->status != Connection::STATUS_NORMAL) {
1780#if DEBUG_DISPATCH_CYCLE
1781 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
1782 connection->getInputChannelName(), connection->getStatusLabel());
1783#endif
1784 return;
1785 }
1786
1787 // Split a motion event if needed.
1788 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1789 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1790
1791 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1792 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1793 MotionEntry* splitMotionEntry = splitMotionEvent(
1794 originalMotionEntry, inputTarget->pointerIds);
1795 if (!splitMotionEntry) {
1796 return; // split event was dropped
1797 }
1798#if DEBUG_FOCUS
1799 ALOGD("channel '%s' ~ Split motion event.",
1800 connection->getInputChannelName());
1801 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1802#endif
1803 enqueueDispatchEntriesLocked(currentTime, connection,
1804 splitMotionEntry, inputTarget);
1805 splitMotionEntry->release();
1806 return;
1807 }
1808 }
1809
1810 // Not splitting. Enqueue dispatch entries for the event as is.
1811 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1812}
1813
1814void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1815 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1816 bool wasEmpty = connection->outboundQueue.isEmpty();
1817
1818 // Enqueue dispatch entries for the requested modes.
1819 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1820 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1821 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1822 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1823 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1824 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1825 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1826 InputTarget::FLAG_DISPATCH_AS_IS);
1827 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1828 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1829 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1830 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1831
1832 // If the outbound queue was previously empty, start the dispatch cycle going.
1833 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1834 startDispatchCycleLocked(currentTime, connection);
1835 }
1836}
1837
1838void InputDispatcher::enqueueDispatchEntryLocked(
1839 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1840 int32_t dispatchMode) {
1841 int32_t inputTargetFlags = inputTarget->flags;
1842 if (!(inputTargetFlags & dispatchMode)) {
1843 return;
1844 }
1845 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1846
1847 // This is a new event.
1848 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1849 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1850 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1851 inputTarget->scaleFactor);
1852
1853 // Apply target flags and update the connection's input state.
1854 switch (eventEntry->type) {
1855 case EventEntry::TYPE_KEY: {
1856 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1857 dispatchEntry->resolvedAction = keyEntry->action;
1858 dispatchEntry->resolvedFlags = keyEntry->flags;
1859
1860 if (!connection->inputState.trackKey(keyEntry,
1861 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1862#if DEBUG_DISPATCH_CYCLE
1863 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
1864 connection->getInputChannelName());
1865#endif
1866 delete dispatchEntry;
1867 return; // skip the inconsistent event
1868 }
1869 break;
1870 }
1871
1872 case EventEntry::TYPE_MOTION: {
1873 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1874 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1875 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1876 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1877 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1878 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1879 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1880 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1881 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1882 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1883 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1884 } else {
1885 dispatchEntry->resolvedAction = motionEntry->action;
1886 }
1887 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1888 && !connection->inputState.isHovering(
1889 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
1890#if DEBUG_DISPATCH_CYCLE
1891 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
1892 connection->getInputChannelName());
1893#endif
1894 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1895 }
1896
1897 dispatchEntry->resolvedFlags = motionEntry->flags;
1898 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1899 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1900 }
1901
1902 if (!connection->inputState.trackMotion(motionEntry,
1903 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1904#if DEBUG_DISPATCH_CYCLE
1905 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
1906 connection->getInputChannelName());
1907#endif
1908 delete dispatchEntry;
1909 return; // skip the inconsistent event
1910 }
1911 break;
1912 }
1913 }
1914
1915 // Remember that we are waiting for this dispatch to complete.
1916 if (dispatchEntry->hasForegroundTarget()) {
1917 incrementPendingForegroundDispatchesLocked(eventEntry);
1918 }
1919
1920 // Enqueue the dispatch entry.
1921 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1922 traceOutboundQueueLengthLocked(connection);
1923}
1924
1925void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
1926 const sp<Connection>& connection) {
1927#if DEBUG_DISPATCH_CYCLE
1928 ALOGD("channel '%s' ~ startDispatchCycle",
1929 connection->getInputChannelName());
1930#endif
1931
1932 while (connection->status == Connection::STATUS_NORMAL
1933 && !connection->outboundQueue.isEmpty()) {
1934 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
1935 dispatchEntry->deliveryTime = currentTime;
1936
1937 // Publish the event.
1938 status_t status;
1939 EventEntry* eventEntry = dispatchEntry->eventEntry;
1940 switch (eventEntry->type) {
1941 case EventEntry::TYPE_KEY: {
1942 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1943
1944 // Publish the key event.
1945 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
1946 keyEntry->deviceId, keyEntry->source,
1947 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1948 keyEntry->keyCode, keyEntry->scanCode,
1949 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1950 keyEntry->eventTime);
1951 break;
1952 }
1953
1954 case EventEntry::TYPE_MOTION: {
1955 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1956
1957 PointerCoords scaledCoords[MAX_POINTERS];
1958 const PointerCoords* usingCoords = motionEntry->pointerCoords;
1959
1960 // Set the X and Y offset depending on the input source.
1961 float xOffset, yOffset, scaleFactor;
1962 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1963 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
1964 scaleFactor = dispatchEntry->scaleFactor;
1965 xOffset = dispatchEntry->xOffset * scaleFactor;
1966 yOffset = dispatchEntry->yOffset * scaleFactor;
1967 if (scaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001968 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001969 scaledCoords[i] = motionEntry->pointerCoords[i];
1970 scaledCoords[i].scale(scaleFactor);
1971 }
1972 usingCoords = scaledCoords;
1973 }
1974 } else {
1975 xOffset = 0.0f;
1976 yOffset = 0.0f;
1977 scaleFactor = 1.0f;
1978
1979 // We don't want the dispatch target to know.
1980 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001981 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982 scaledCoords[i].clear();
1983 }
1984 usingCoords = scaledCoords;
1985 }
1986 }
1987
1988 // Publish the motion event.
1989 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
1990 motionEntry->deviceId, motionEntry->source,
Michael Wright7b159c92015-05-14 14:48:03 +01001991 dispatchEntry->resolvedAction, motionEntry->actionButton,
1992 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
1993 motionEntry->metaState, motionEntry->buttonState,
1994 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995 motionEntry->downTime, motionEntry->eventTime,
1996 motionEntry->pointerCount, motionEntry->pointerProperties,
1997 usingCoords);
1998 break;
1999 }
2000
2001 default:
2002 ALOG_ASSERT(false);
2003 return;
2004 }
2005
2006 // Check the result.
2007 if (status) {
2008 if (status == WOULD_BLOCK) {
2009 if (connection->waitQueue.isEmpty()) {
2010 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2011 "This is unexpected because the wait queue is empty, so the pipe "
2012 "should be empty and we shouldn't have any problems writing an "
2013 "event to it, status=%d", connection->getInputChannelName(), status);
2014 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2015 } else {
2016 // Pipe is full and we are waiting for the app to finish process some events
2017 // before sending more events to it.
2018#if DEBUG_DISPATCH_CYCLE
2019 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2020 "waiting for the application to catch up",
2021 connection->getInputChannelName());
2022#endif
2023 connection->inputPublisherBlocked = true;
2024 }
2025 } else {
2026 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2027 "status=%d", connection->getInputChannelName(), status);
2028 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2029 }
2030 return;
2031 }
2032
2033 // Re-enqueue the event on the wait queue.
2034 connection->outboundQueue.dequeue(dispatchEntry);
2035 traceOutboundQueueLengthLocked(connection);
2036 connection->waitQueue.enqueueAtTail(dispatchEntry);
2037 traceWaitQueueLengthLocked(connection);
2038 }
2039}
2040
2041void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2042 const sp<Connection>& connection, uint32_t seq, bool handled) {
2043#if DEBUG_DISPATCH_CYCLE
2044 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2045 connection->getInputChannelName(), seq, toString(handled));
2046#endif
2047
2048 connection->inputPublisherBlocked = false;
2049
2050 if (connection->status == Connection::STATUS_BROKEN
2051 || connection->status == Connection::STATUS_ZOMBIE) {
2052 return;
2053 }
2054
2055 // Notify other system components and prepare to start the next dispatch cycle.
2056 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2057}
2058
2059void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2060 const sp<Connection>& connection, bool notify) {
2061#if DEBUG_DISPATCH_CYCLE
2062 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
2063 connection->getInputChannelName(), toString(notify));
2064#endif
2065
2066 // Clear the dispatch queues.
2067 drainDispatchQueueLocked(&connection->outboundQueue);
2068 traceOutboundQueueLengthLocked(connection);
2069 drainDispatchQueueLocked(&connection->waitQueue);
2070 traceWaitQueueLengthLocked(connection);
2071
2072 // The connection appears to be unrecoverably broken.
2073 // Ignore already broken or zombie connections.
2074 if (connection->status == Connection::STATUS_NORMAL) {
2075 connection->status = Connection::STATUS_BROKEN;
2076
2077 if (notify) {
2078 // Notify other system components.
2079 onDispatchCycleBrokenLocked(currentTime, connection);
2080 }
2081 }
2082}
2083
2084void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2085 while (!queue->isEmpty()) {
2086 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2087 releaseDispatchEntryLocked(dispatchEntry);
2088 }
2089}
2090
2091void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2092 if (dispatchEntry->hasForegroundTarget()) {
2093 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2094 }
2095 delete dispatchEntry;
2096}
2097
2098int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2099 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2100
2101 { // acquire lock
2102 AutoMutex _l(d->mLock);
2103
2104 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2105 if (connectionIndex < 0) {
2106 ALOGE("Received spurious receive callback for unknown input channel. "
2107 "fd=%d, events=0x%x", fd, events);
2108 return 0; // remove the callback
2109 }
2110
2111 bool notify;
2112 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2113 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2114 if (!(events & ALOOPER_EVENT_INPUT)) {
2115 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2116 "events=0x%x", connection->getInputChannelName(), events);
2117 return 1;
2118 }
2119
2120 nsecs_t currentTime = now();
2121 bool gotOne = false;
2122 status_t status;
2123 for (;;) {
2124 uint32_t seq;
2125 bool handled;
2126 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2127 if (status) {
2128 break;
2129 }
2130 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2131 gotOne = true;
2132 }
2133 if (gotOne) {
2134 d->runCommandsLockedInterruptible();
2135 if (status == WOULD_BLOCK) {
2136 return 1;
2137 }
2138 }
2139
2140 notify = status != DEAD_OBJECT || !connection->monitor;
2141 if (notify) {
2142 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2143 connection->getInputChannelName(), status);
2144 }
2145 } else {
2146 // Monitor channels are never explicitly unregistered.
2147 // We do it automatically when the remote endpoint is closed so don't warn
2148 // about them.
2149 notify = !connection->monitor;
2150 if (notify) {
2151 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
2152 "events=0x%x", connection->getInputChannelName(), events);
2153 }
2154 }
2155
2156 // Unregister the channel.
2157 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2158 return 0; // remove the callback
2159 } // release lock
2160}
2161
2162void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2163 const CancelationOptions& options) {
2164 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2165 synthesizeCancelationEventsForConnectionLocked(
2166 mConnectionsByFd.valueAt(i), options);
2167 }
2168}
2169
2170void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2171 const sp<InputChannel>& channel, const CancelationOptions& options) {
2172 ssize_t index = getConnectionIndexLocked(channel);
2173 if (index >= 0) {
2174 synthesizeCancelationEventsForConnectionLocked(
2175 mConnectionsByFd.valueAt(index), options);
2176 }
2177}
2178
2179void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2180 const sp<Connection>& connection, const CancelationOptions& options) {
2181 if (connection->status == Connection::STATUS_BROKEN) {
2182 return;
2183 }
2184
2185 nsecs_t currentTime = now();
2186
2187 Vector<EventEntry*> cancelationEvents;
2188 connection->inputState.synthesizeCancelationEvents(currentTime,
2189 cancelationEvents, options);
2190
2191 if (!cancelationEvents.isEmpty()) {
2192#if DEBUG_OUTBOUND_EVENT_DETAILS
2193 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
2194 "with reality: %s, mode=%d.",
2195 connection->getInputChannelName(), cancelationEvents.size(),
2196 options.reason, options.mode);
2197#endif
2198 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2199 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2200 switch (cancelationEventEntry->type) {
2201 case EventEntry::TYPE_KEY:
2202 logOutboundKeyDetailsLocked("cancel - ",
2203 static_cast<KeyEntry*>(cancelationEventEntry));
2204 break;
2205 case EventEntry::TYPE_MOTION:
2206 logOutboundMotionDetailsLocked("cancel - ",
2207 static_cast<MotionEntry*>(cancelationEventEntry));
2208 break;
2209 }
2210
2211 InputTarget target;
2212 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2213 if (windowHandle != NULL) {
2214 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2215 target.xOffset = -windowInfo->frameLeft;
2216 target.yOffset = -windowInfo->frameTop;
2217 target.scaleFactor = windowInfo->scaleFactor;
2218 } else {
2219 target.xOffset = 0;
2220 target.yOffset = 0;
2221 target.scaleFactor = 1.0f;
2222 }
2223 target.inputChannel = connection->inputChannel;
2224 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2225
2226 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2227 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2228
2229 cancelationEventEntry->release();
2230 }
2231
2232 startDispatchCycleLocked(currentTime, connection);
2233 }
2234}
2235
2236InputDispatcher::MotionEntry*
2237InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2238 ALOG_ASSERT(pointerIds.value != 0);
2239
2240 uint32_t splitPointerIndexMap[MAX_POINTERS];
2241 PointerProperties splitPointerProperties[MAX_POINTERS];
2242 PointerCoords splitPointerCoords[MAX_POINTERS];
2243
2244 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2245 uint32_t splitPointerCount = 0;
2246
2247 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2248 originalPointerIndex++) {
2249 const PointerProperties& pointerProperties =
2250 originalMotionEntry->pointerProperties[originalPointerIndex];
2251 uint32_t pointerId = uint32_t(pointerProperties.id);
2252 if (pointerIds.hasBit(pointerId)) {
2253 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2254 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2255 splitPointerCoords[splitPointerCount].copyFrom(
2256 originalMotionEntry->pointerCoords[originalPointerIndex]);
2257 splitPointerCount += 1;
2258 }
2259 }
2260
2261 if (splitPointerCount != pointerIds.count()) {
2262 // This is bad. We are missing some of the pointers that we expected to deliver.
2263 // Most likely this indicates that we received an ACTION_MOVE events that has
2264 // different pointer ids than we expected based on the previous ACTION_DOWN
2265 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2266 // in this way.
2267 ALOGW("Dropping split motion event because the pointer count is %d but "
2268 "we expected there to be %d pointers. This probably means we received "
2269 "a broken sequence of pointer ids from the input device.",
2270 splitPointerCount, pointerIds.count());
2271 return NULL;
2272 }
2273
2274 int32_t action = originalMotionEntry->action;
2275 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2276 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2277 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2278 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2279 const PointerProperties& pointerProperties =
2280 originalMotionEntry->pointerProperties[originalPointerIndex];
2281 uint32_t pointerId = uint32_t(pointerProperties.id);
2282 if (pointerIds.hasBit(pointerId)) {
2283 if (pointerIds.count() == 1) {
2284 // The first/last pointer went down/up.
2285 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2286 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2287 } else {
2288 // A secondary pointer went down/up.
2289 uint32_t splitPointerIndex = 0;
2290 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2291 splitPointerIndex += 1;
2292 }
2293 action = maskedAction | (splitPointerIndex
2294 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2295 }
2296 } else {
2297 // An unrelated pointer changed.
2298 action = AMOTION_EVENT_ACTION_MOVE;
2299 }
2300 }
2301
2302 MotionEntry* splitMotionEntry = new MotionEntry(
2303 originalMotionEntry->eventTime,
2304 originalMotionEntry->deviceId,
2305 originalMotionEntry->source,
2306 originalMotionEntry->policyFlags,
2307 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002308 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 originalMotionEntry->flags,
2310 originalMotionEntry->metaState,
2311 originalMotionEntry->buttonState,
2312 originalMotionEntry->edgeFlags,
2313 originalMotionEntry->xPrecision,
2314 originalMotionEntry->yPrecision,
2315 originalMotionEntry->downTime,
2316 originalMotionEntry->displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002317 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318
2319 if (originalMotionEntry->injectionState) {
2320 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2321 splitMotionEntry->injectionState->refCount += 1;
2322 }
2323
2324 return splitMotionEntry;
2325}
2326
2327void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2328#if DEBUG_INBOUND_EVENT_DETAILS
2329 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
2330#endif
2331
2332 bool needWake;
2333 { // acquire lock
2334 AutoMutex _l(mLock);
2335
2336 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2337 needWake = enqueueInboundEventLocked(newEntry);
2338 } // release lock
2339
2340 if (needWake) {
2341 mLooper->wake();
2342 }
2343}
2344
2345void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2346#if DEBUG_INBOUND_EVENT_DETAILS
2347 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
2348 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
2349 args->eventTime, args->deviceId, args->source, args->policyFlags,
2350 args->action, args->flags, args->keyCode, args->scanCode,
2351 args->metaState, args->downTime);
2352#endif
2353 if (!validateKeyEvent(args->action)) {
2354 return;
2355 }
2356
2357 uint32_t policyFlags = args->policyFlags;
2358 int32_t flags = args->flags;
2359 int32_t metaState = args->metaState;
2360 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2361 policyFlags |= POLICY_FLAG_VIRTUAL;
2362 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2363 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002364 if (policyFlags & POLICY_FLAG_FUNCTION) {
2365 metaState |= AMETA_FUNCTION_ON;
2366 }
2367
2368 policyFlags |= POLICY_FLAG_TRUSTED;
2369
Michael Wright78f24442014-08-06 15:55:28 -07002370 int32_t keyCode = args->keyCode;
2371 if (metaState & AMETA_META_ON && args->action == AKEY_EVENT_ACTION_DOWN) {
2372 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2373 if (keyCode == AKEYCODE_DEL) {
2374 newKeyCode = AKEYCODE_BACK;
2375 } else if (keyCode == AKEYCODE_ENTER) {
2376 newKeyCode = AKEYCODE_HOME;
2377 }
2378 if (newKeyCode != AKEYCODE_UNKNOWN) {
2379 AutoMutex _l(mLock);
2380 struct KeyReplacement replacement = {keyCode, args->deviceId};
2381 mReplacedKeys.add(replacement, newKeyCode);
2382 keyCode = newKeyCode;
2383 metaState &= ~AMETA_META_ON;
2384 }
2385 } else if (args->action == AKEY_EVENT_ACTION_UP) {
2386 // In order to maintain a consistent stream of up and down events, check to see if the key
2387 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2388 // even if the modifier was released between the down and the up events.
2389 AutoMutex _l(mLock);
2390 struct KeyReplacement replacement = {keyCode, args->deviceId};
2391 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2392 if (index >= 0) {
2393 keyCode = mReplacedKeys.valueAt(index);
2394 mReplacedKeys.removeItemsAt(index);
2395 metaState &= ~AMETA_META_ON;
2396 }
2397 }
2398
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 KeyEvent event;
2400 event.initialize(args->deviceId, args->source, args->action,
Michael Wright78f24442014-08-06 15:55:28 -07002401 flags, keyCode, args->scanCode, metaState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 args->downTime, args->eventTime);
2403
2404 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2405
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 bool needWake;
2407 { // acquire lock
2408 mLock.lock();
2409
2410 if (shouldSendKeyToInputFilterLocked(args)) {
2411 mLock.unlock();
2412
2413 policyFlags |= POLICY_FLAG_FILTERED;
2414 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2415 return; // event was consumed by the filter
2416 }
2417
2418 mLock.lock();
2419 }
2420
2421 int32_t repeatCount = 0;
2422 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2423 args->deviceId, args->source, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002424 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002425 metaState, repeatCount, args->downTime);
2426
2427 needWake = enqueueInboundEventLocked(newEntry);
2428 mLock.unlock();
2429 } // release lock
2430
2431 if (needWake) {
2432 mLooper->wake();
2433 }
2434}
2435
2436bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2437 return mInputFilterEnabled;
2438}
2439
2440void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2441#if DEBUG_INBOUND_EVENT_DETAILS
2442 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002443 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
2444 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445 args->eventTime, args->deviceId, args->source, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002446 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2448 for (uint32_t i = 0; i < args->pointerCount; i++) {
2449 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2450 "x=%f, y=%f, pressure=%f, size=%f, "
2451 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2452 "orientation=%f",
2453 i, args->pointerProperties[i].id,
2454 args->pointerProperties[i].toolType,
2455 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2456 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2457 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2458 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2459 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2460 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2461 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2462 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2463 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2464 }
2465#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002466 if (!validateMotionEvent(args->action, args->actionButton,
2467 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 return;
2469 }
2470
2471 uint32_t policyFlags = args->policyFlags;
2472 policyFlags |= POLICY_FLAG_TRUSTED;
2473 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
2474
2475 bool needWake;
2476 { // acquire lock
2477 mLock.lock();
2478
2479 if (shouldSendMotionToInputFilterLocked(args)) {
2480 mLock.unlock();
2481
2482 MotionEvent event;
Michael Wright7b159c92015-05-14 14:48:03 +01002483 event.initialize(args->deviceId, args->source, args->action, args->actionButton,
2484 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2485 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 args->downTime, args->eventTime,
2487 args->pointerCount, args->pointerProperties, args->pointerCoords);
2488
2489 policyFlags |= POLICY_FLAG_FILTERED;
2490 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2491 return; // event was consumed by the filter
2492 }
2493
2494 mLock.lock();
2495 }
2496
2497 // Just enqueue a new motion event.
2498 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2499 args->deviceId, args->source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002500 args->action, args->actionButton, args->flags,
2501 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2503 args->displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002504 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505
2506 needWake = enqueueInboundEventLocked(newEntry);
2507 mLock.unlock();
2508 } // release lock
2509
2510 if (needWake) {
2511 mLooper->wake();
2512 }
2513}
2514
2515bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2516 // TODO: support sending secondary display events to input filter
2517 return mInputFilterEnabled && isMainDisplay(args->displayId);
2518}
2519
2520void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2521#if DEBUG_INBOUND_EVENT_DETAILS
2522 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x",
2523 args->eventTime, args->policyFlags,
2524 args->switchValues, args->switchMask);
2525#endif
2526
2527 uint32_t policyFlags = args->policyFlags;
2528 policyFlags |= POLICY_FLAG_TRUSTED;
2529 mPolicy->notifySwitch(args->eventTime,
2530 args->switchValues, args->switchMask, policyFlags);
2531}
2532
2533void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2534#if DEBUG_INBOUND_EVENT_DETAILS
2535 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
2536 args->eventTime, args->deviceId);
2537#endif
2538
2539 bool needWake;
2540 { // acquire lock
2541 AutoMutex _l(mLock);
2542
2543 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2544 needWake = enqueueInboundEventLocked(newEntry);
2545 } // release lock
2546
2547 if (needWake) {
2548 mLooper->wake();
2549 }
2550}
2551
Jeff Brownf086ddb2014-02-11 14:28:48 -08002552int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2554 uint32_t policyFlags) {
2555#if DEBUG_INBOUND_EVENT_DETAILS
2556 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
2557 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2558 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
2559#endif
2560
2561 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2562
2563 policyFlags |= POLICY_FLAG_INJECTED;
2564 if (hasInjectionPermission(injectorPid, injectorUid)) {
2565 policyFlags |= POLICY_FLAG_TRUSTED;
2566 }
2567
2568 EventEntry* firstInjectedEntry;
2569 EventEntry* lastInjectedEntry;
2570 switch (event->getType()) {
2571 case AINPUT_EVENT_TYPE_KEY: {
2572 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2573 int32_t action = keyEvent->getAction();
2574 if (! validateKeyEvent(action)) {
2575 return INPUT_EVENT_INJECTION_FAILED;
2576 }
2577
2578 int32_t flags = keyEvent->getFlags();
2579 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2580 policyFlags |= POLICY_FLAG_VIRTUAL;
2581 }
2582
2583 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2584 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2585 }
2586
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 mLock.lock();
2588 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
2589 keyEvent->getDeviceId(), keyEvent->getSource(),
2590 policyFlags, action, flags,
2591 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
2592 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2593 lastInjectedEntry = firstInjectedEntry;
2594 break;
2595 }
2596
2597 case AINPUT_EVENT_TYPE_MOTION: {
2598 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 int32_t action = motionEvent->getAction();
2600 size_t pointerCount = motionEvent->getPointerCount();
2601 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002602 int32_t actionButton = motionEvent->getActionButton();
2603 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604 return INPUT_EVENT_INJECTION_FAILED;
2605 }
2606
2607 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2608 nsecs_t eventTime = motionEvent->getEventTime();
2609 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2610 }
2611
2612 mLock.lock();
2613 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2614 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2615 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
2616 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002617 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 motionEvent->getMetaState(), motionEvent->getButtonState(),
2619 motionEvent->getEdgeFlags(),
2620 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2621 motionEvent->getDownTime(), displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002622 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2623 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624 lastInjectedEntry = firstInjectedEntry;
2625 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2626 sampleEventTimes += 1;
2627 samplePointerCoords += pointerCount;
2628 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2629 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002630 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631 motionEvent->getMetaState(), motionEvent->getButtonState(),
2632 motionEvent->getEdgeFlags(),
2633 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2634 motionEvent->getDownTime(), displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002635 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2636 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 lastInjectedEntry->next = nextInjectedEntry;
2638 lastInjectedEntry = nextInjectedEntry;
2639 }
2640 break;
2641 }
2642
2643 default:
2644 ALOGW("Cannot inject event of type %d", event->getType());
2645 return INPUT_EVENT_INJECTION_FAILED;
2646 }
2647
2648 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2649 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2650 injectionState->injectionIsAsync = true;
2651 }
2652
2653 injectionState->refCount += 1;
2654 lastInjectedEntry->injectionState = injectionState;
2655
2656 bool needWake = false;
2657 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2658 EventEntry* nextEntry = entry->next;
2659 needWake |= enqueueInboundEventLocked(entry);
2660 entry = nextEntry;
2661 }
2662
2663 mLock.unlock();
2664
2665 if (needWake) {
2666 mLooper->wake();
2667 }
2668
2669 int32_t injectionResult;
2670 { // acquire lock
2671 AutoMutex _l(mLock);
2672
2673 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2674 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2675 } else {
2676 for (;;) {
2677 injectionResult = injectionState->injectionResult;
2678 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2679 break;
2680 }
2681
2682 nsecs_t remainingTimeout = endTime - now();
2683 if (remainingTimeout <= 0) {
2684#if DEBUG_INJECTION
2685 ALOGD("injectInputEvent - Timed out waiting for injection result "
2686 "to become available.");
2687#endif
2688 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2689 break;
2690 }
2691
2692 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2693 }
2694
2695 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2696 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2697 while (injectionState->pendingForegroundDispatches != 0) {
2698#if DEBUG_INJECTION
2699 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2700 injectionState->pendingForegroundDispatches);
2701#endif
2702 nsecs_t remainingTimeout = endTime - now();
2703 if (remainingTimeout <= 0) {
2704#if DEBUG_INJECTION
2705 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2706 "dispatches to finish.");
2707#endif
2708 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2709 break;
2710 }
2711
2712 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2713 }
2714 }
2715 }
2716
2717 injectionState->release();
2718 } // release lock
2719
2720#if DEBUG_INJECTION
2721 ALOGD("injectInputEvent - Finished with result %d. "
2722 "injectorPid=%d, injectorUid=%d",
2723 injectionResult, injectorPid, injectorUid);
2724#endif
2725
2726 return injectionResult;
2727}
2728
2729bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2730 return injectorUid == 0
2731 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2732}
2733
2734void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2735 InjectionState* injectionState = entry->injectionState;
2736 if (injectionState) {
2737#if DEBUG_INJECTION
2738 ALOGD("Setting input event injection result to %d. "
2739 "injectorPid=%d, injectorUid=%d",
2740 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2741#endif
2742
2743 if (injectionState->injectionIsAsync
2744 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2745 // Log the outcome since the injector did not wait for the injection result.
2746 switch (injectionResult) {
2747 case INPUT_EVENT_INJECTION_SUCCEEDED:
2748 ALOGV("Asynchronous input event injection succeeded.");
2749 break;
2750 case INPUT_EVENT_INJECTION_FAILED:
2751 ALOGW("Asynchronous input event injection failed.");
2752 break;
2753 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2754 ALOGW("Asynchronous input event injection permission denied.");
2755 break;
2756 case INPUT_EVENT_INJECTION_TIMED_OUT:
2757 ALOGW("Asynchronous input event injection timed out.");
2758 break;
2759 }
2760 }
2761
2762 injectionState->injectionResult = injectionResult;
2763 mInjectionResultAvailableCondition.broadcast();
2764 }
2765}
2766
2767void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2768 InjectionState* injectionState = entry->injectionState;
2769 if (injectionState) {
2770 injectionState->pendingForegroundDispatches += 1;
2771 }
2772}
2773
2774void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2775 InjectionState* injectionState = entry->injectionState;
2776 if (injectionState) {
2777 injectionState->pendingForegroundDispatches -= 1;
2778
2779 if (injectionState->pendingForegroundDispatches == 0) {
2780 mInjectionSyncFinishedCondition.broadcast();
2781 }
2782 }
2783}
2784
2785sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2786 const sp<InputChannel>& inputChannel) const {
2787 size_t numWindows = mWindowHandles.size();
2788 for (size_t i = 0; i < numWindows; i++) {
2789 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2790 if (windowHandle->getInputChannel() == inputChannel) {
2791 return windowHandle;
2792 }
2793 }
2794 return NULL;
2795}
2796
2797bool InputDispatcher::hasWindowHandleLocked(
2798 const sp<InputWindowHandle>& windowHandle) const {
2799 size_t numWindows = mWindowHandles.size();
2800 for (size_t i = 0; i < numWindows; i++) {
2801 if (mWindowHandles.itemAt(i) == windowHandle) {
2802 return true;
2803 }
2804 }
2805 return false;
2806}
2807
2808void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
2809#if DEBUG_FOCUS
2810 ALOGD("setInputWindows");
2811#endif
2812 { // acquire lock
2813 AutoMutex _l(mLock);
2814
2815 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
2816 mWindowHandles = inputWindowHandles;
2817
2818 sp<InputWindowHandle> newFocusedWindowHandle;
2819 bool foundHoveredWindow = false;
2820 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2821 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2822 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
2823 mWindowHandles.removeAt(i--);
2824 continue;
2825 }
2826 if (windowHandle->getInfo()->hasFocus) {
2827 newFocusedWindowHandle = windowHandle;
2828 }
2829 if (windowHandle == mLastHoverWindowHandle) {
2830 foundHoveredWindow = true;
2831 }
2832 }
2833
2834 if (!foundHoveredWindow) {
2835 mLastHoverWindowHandle = NULL;
2836 }
2837
2838 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2839 if (mFocusedWindowHandle != NULL) {
2840#if DEBUG_FOCUS
2841 ALOGD("Focus left window: %s",
2842 mFocusedWindowHandle->getName().string());
2843#endif
2844 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2845 if (focusedInputChannel != NULL) {
2846 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2847 "focus left window");
2848 synthesizeCancelationEventsForInputChannelLocked(
2849 focusedInputChannel, options);
2850 }
2851 }
2852 if (newFocusedWindowHandle != NULL) {
2853#if DEBUG_FOCUS
2854 ALOGD("Focus entered window: %s",
2855 newFocusedWindowHandle->getName().string());
2856#endif
2857 }
2858 mFocusedWindowHandle = newFocusedWindowHandle;
2859 }
2860
Jeff Brownf086ddb2014-02-11 14:28:48 -08002861 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
2862 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
2863 for (size_t i = 0; i < state.windows.size(); i++) {
2864 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
2865 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866#if DEBUG_FOCUS
Jeff Brownf086ddb2014-02-11 14:28:48 -08002867 ALOGD("Touched window was removed: %s",
2868 touchedWindow.windowHandle->getName().string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002869#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08002870 sp<InputChannel> touchedInputChannel =
2871 touchedWindow.windowHandle->getInputChannel();
2872 if (touchedInputChannel != NULL) {
2873 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2874 "touched window was removed");
2875 synthesizeCancelationEventsForInputChannelLocked(
2876 touchedInputChannel, options);
2877 }
2878 state.windows.removeAt(i--);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002879 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880 }
2881 }
2882
2883 // Release information for windows that are no longer present.
2884 // This ensures that unused input channels are released promptly.
2885 // Otherwise, they might stick around until the window handle is destroyed
2886 // which might not happen until the next GC.
2887 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2888 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2889 if (!hasWindowHandleLocked(oldWindowHandle)) {
2890#if DEBUG_FOCUS
2891 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
2892#endif
2893 oldWindowHandle->releaseInfo();
2894 }
2895 }
2896 } // release lock
2897
2898 // Wake up poll loop since it may need to make new input dispatching choices.
2899 mLooper->wake();
2900}
2901
2902void InputDispatcher::setFocusedApplication(
2903 const sp<InputApplicationHandle>& inputApplicationHandle) {
2904#if DEBUG_FOCUS
2905 ALOGD("setFocusedApplication");
2906#endif
2907 { // acquire lock
2908 AutoMutex _l(mLock);
2909
2910 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
2911 if (mFocusedApplicationHandle != inputApplicationHandle) {
2912 if (mFocusedApplicationHandle != NULL) {
2913 resetANRTimeoutsLocked();
2914 mFocusedApplicationHandle->releaseInfo();
2915 }
2916 mFocusedApplicationHandle = inputApplicationHandle;
2917 }
2918 } else if (mFocusedApplicationHandle != NULL) {
2919 resetANRTimeoutsLocked();
2920 mFocusedApplicationHandle->releaseInfo();
2921 mFocusedApplicationHandle.clear();
2922 }
2923
2924#if DEBUG_FOCUS
2925 //logDispatchStateLocked();
2926#endif
2927 } // release lock
2928
2929 // Wake up poll loop since it may need to make new input dispatching choices.
2930 mLooper->wake();
2931}
2932
2933void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2934#if DEBUG_FOCUS
2935 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2936#endif
2937
2938 bool changed;
2939 { // acquire lock
2940 AutoMutex _l(mLock);
2941
2942 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
2943 if (mDispatchFrozen && !frozen) {
2944 resetANRTimeoutsLocked();
2945 }
2946
2947 if (mDispatchEnabled && !enabled) {
2948 resetAndDropEverythingLocked("dispatcher is being disabled");
2949 }
2950
2951 mDispatchEnabled = enabled;
2952 mDispatchFrozen = frozen;
2953 changed = true;
2954 } else {
2955 changed = false;
2956 }
2957
2958#if DEBUG_FOCUS
2959 //logDispatchStateLocked();
2960#endif
2961 } // release lock
2962
2963 if (changed) {
2964 // Wake up poll loop since it may need to make new input dispatching choices.
2965 mLooper->wake();
2966 }
2967}
2968
2969void InputDispatcher::setInputFilterEnabled(bool enabled) {
2970#if DEBUG_FOCUS
2971 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
2972#endif
2973
2974 { // acquire lock
2975 AutoMutex _l(mLock);
2976
2977 if (mInputFilterEnabled == enabled) {
2978 return;
2979 }
2980
2981 mInputFilterEnabled = enabled;
2982 resetAndDropEverythingLocked("input filter is being enabled or disabled");
2983 } // release lock
2984
2985 // Wake up poll loop since there might be work to do to drop everything.
2986 mLooper->wake();
2987}
2988
2989bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
2990 const sp<InputChannel>& toChannel) {
2991#if DEBUG_FOCUS
2992 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
2993 fromChannel->getName().string(), toChannel->getName().string());
2994#endif
2995 { // acquire lock
2996 AutoMutex _l(mLock);
2997
2998 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
2999 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3000 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
3001#if DEBUG_FOCUS
3002 ALOGD("Cannot transfer focus because from or to window not found.");
3003#endif
3004 return false;
3005 }
3006 if (fromWindowHandle == toWindowHandle) {
3007#if DEBUG_FOCUS
3008 ALOGD("Trivial transfer to same window.");
3009#endif
3010 return true;
3011 }
3012 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3013#if DEBUG_FOCUS
3014 ALOGD("Cannot transfer focus because windows are on different displays.");
3015#endif
3016 return false;
3017 }
3018
3019 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003020 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3021 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3022 for (size_t i = 0; i < state.windows.size(); i++) {
3023 const TouchedWindow& touchedWindow = state.windows[i];
3024 if (touchedWindow.windowHandle == fromWindowHandle) {
3025 int32_t oldTargetFlags = touchedWindow.targetFlags;
3026 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027
Jeff Brownf086ddb2014-02-11 14:28:48 -08003028 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029
Jeff Brownf086ddb2014-02-11 14:28:48 -08003030 int32_t newTargetFlags = oldTargetFlags
3031 & (InputTarget::FLAG_FOREGROUND
3032 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3033 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034
Jeff Brownf086ddb2014-02-11 14:28:48 -08003035 found = true;
3036 goto Found;
3037 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038 }
3039 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003040Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041
3042 if (! found) {
3043#if DEBUG_FOCUS
3044 ALOGD("Focus transfer failed because from window did not have focus.");
3045#endif
3046 return false;
3047 }
3048
3049 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3050 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3051 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3052 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3053 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3054
3055 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3056 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3057 "transferring touch focus from this window to another window");
3058 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3059 }
3060
3061#if DEBUG_FOCUS
3062 logDispatchStateLocked();
3063#endif
3064 } // release lock
3065
3066 // Wake up poll loop since it may need to make new input dispatching choices.
3067 mLooper->wake();
3068 return true;
3069}
3070
3071void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3072#if DEBUG_FOCUS
3073 ALOGD("Resetting and dropping all events (%s).", reason);
3074#endif
3075
3076 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3077 synthesizeCancelationEventsForAllConnectionsLocked(options);
3078
3079 resetKeyRepeatLocked();
3080 releasePendingEventLocked();
3081 drainInboundQueueLocked();
3082 resetANRTimeoutsLocked();
3083
Jeff Brownf086ddb2014-02-11 14:28:48 -08003084 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003086 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087}
3088
3089void InputDispatcher::logDispatchStateLocked() {
3090 String8 dump;
3091 dumpDispatchStateLocked(dump);
3092
3093 char* text = dump.lockBuffer(dump.size());
3094 char* start = text;
3095 while (*start != '\0') {
3096 char* end = strchr(start, '\n');
3097 if (*end == '\n') {
3098 *(end++) = '\0';
3099 }
3100 ALOGD("%s", start);
3101 start = end;
3102 }
3103}
3104
3105void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
3106 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3107 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
3108
3109 if (mFocusedApplicationHandle != NULL) {
3110 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
3111 mFocusedApplicationHandle->getName().string(),
3112 mFocusedApplicationHandle->getDispatchingTimeout(
3113 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3114 } else {
3115 dump.append(INDENT "FocusedApplication: <null>\n");
3116 }
3117 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
3118 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
3119
Jeff Brownf086ddb2014-02-11 14:28:48 -08003120 if (!mTouchStatesByDisplay.isEmpty()) {
3121 dump.appendFormat(INDENT "TouchStatesByDisplay:\n");
3122 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3123 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
3124 dump.appendFormat(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
3125 state.displayId, toString(state.down), toString(state.split),
3126 state.deviceId, state.source);
3127 if (!state.windows.isEmpty()) {
3128 dump.append(INDENT3 "Windows:\n");
3129 for (size_t i = 0; i < state.windows.size(); i++) {
3130 const TouchedWindow& touchedWindow = state.windows[i];
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003131 dump.appendFormat(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003132 i, touchedWindow.windowHandle->getName().string(),
3133 touchedWindow.pointerIds.value,
3134 touchedWindow.targetFlags);
3135 }
3136 } else {
3137 dump.append(INDENT3 "Windows: <none>\n");
3138 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139 }
3140 } else {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003141 dump.append(INDENT "TouchStates: <no displays touched>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 }
3143
3144 if (!mWindowHandles.isEmpty()) {
3145 dump.append(INDENT "Windows:\n");
3146 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3147 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3148 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3149
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003150 dump.appendFormat(INDENT2 "%zu: name='%s', displayId=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3152 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3153 "frame=[%d,%d][%d,%d], scale=%f, "
3154 "touchableRegion=",
3155 i, windowInfo->name.string(), windowInfo->displayId,
3156 toString(windowInfo->paused),
3157 toString(windowInfo->hasFocus),
3158 toString(windowInfo->hasWallpaper),
3159 toString(windowInfo->visible),
3160 toString(windowInfo->canReceiveKeys),
3161 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3162 windowInfo->layer,
3163 windowInfo->frameLeft, windowInfo->frameTop,
3164 windowInfo->frameRight, windowInfo->frameBottom,
3165 windowInfo->scaleFactor);
3166 dumpRegion(dump, windowInfo->touchableRegion);
3167 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3168 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3169 windowInfo->ownerPid, windowInfo->ownerUid,
3170 windowInfo->dispatchingTimeout / 1000000.0);
3171 }
3172 } else {
3173 dump.append(INDENT "Windows: <none>\n");
3174 }
3175
3176 if (!mMonitoringChannels.isEmpty()) {
3177 dump.append(INDENT "MonitoringChannels:\n");
3178 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3179 const sp<InputChannel>& channel = mMonitoringChannels[i];
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003180 dump.appendFormat(INDENT2 "%zu: '%s'\n", i, channel->getName().string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
3182 } else {
3183 dump.append(INDENT "MonitoringChannels: <none>\n");
3184 }
3185
3186 nsecs_t currentTime = now();
3187
3188 // Dump recently dispatched or dropped events from oldest to newest.
3189 if (!mRecentQueue.isEmpty()) {
3190 dump.appendFormat(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
3191 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
3192 dump.append(INDENT2);
3193 entry->appendDescription(dump);
3194 dump.appendFormat(", age=%0.1fms\n",
3195 (currentTime - entry->eventTime) * 0.000001f);
3196 }
3197 } else {
3198 dump.append(INDENT "RecentQueue: <empty>\n");
3199 }
3200
3201 // Dump event currently being dispatched.
3202 if (mPendingEvent) {
3203 dump.append(INDENT "PendingEvent:\n");
3204 dump.append(INDENT2);
3205 mPendingEvent->appendDescription(dump);
3206 dump.appendFormat(", age=%0.1fms\n",
3207 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3208 } else {
3209 dump.append(INDENT "PendingEvent: <none>\n");
3210 }
3211
3212 // Dump inbound events from oldest to newest.
3213 if (!mInboundQueue.isEmpty()) {
3214 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3215 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3216 dump.append(INDENT2);
3217 entry->appendDescription(dump);
3218 dump.appendFormat(", age=%0.1fms\n",
3219 (currentTime - entry->eventTime) * 0.000001f);
3220 }
3221 } else {
3222 dump.append(INDENT "InboundQueue: <empty>\n");
3223 }
3224
Michael Wright78f24442014-08-06 15:55:28 -07003225 if (!mReplacedKeys.isEmpty()) {
3226 dump.append(INDENT "ReplacedKeys:\n");
3227 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3228 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3229 int32_t newKeyCode = mReplacedKeys.valueAt(i);
3230 dump.appendFormat(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
3231 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3232 }
3233 } else {
3234 dump.append(INDENT "ReplacedKeys: <empty>\n");
3235 }
3236
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 if (!mConnectionsByFd.isEmpty()) {
3238 dump.append(INDENT "Connections:\n");
3239 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3240 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003241 dump.appendFormat(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3243 i, connection->getInputChannelName(), connection->getWindowName(),
3244 connection->getStatusLabel(), toString(connection->monitor),
3245 toString(connection->inputPublisherBlocked));
3246
3247 if (!connection->outboundQueue.isEmpty()) {
3248 dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
3249 connection->outboundQueue.count());
3250 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3251 entry = entry->next) {
3252 dump.append(INDENT4);
3253 entry->eventEntry->appendDescription(dump);
3254 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
3255 entry->targetFlags, entry->resolvedAction,
3256 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3257 }
3258 } else {
3259 dump.append(INDENT3 "OutboundQueue: <empty>\n");
3260 }
3261
3262 if (!connection->waitQueue.isEmpty()) {
3263 dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
3264 connection->waitQueue.count());
3265 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3266 entry = entry->next) {
3267 dump.append(INDENT4);
3268 entry->eventEntry->appendDescription(dump);
3269 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
3270 "age=%0.1fms, wait=%0.1fms\n",
3271 entry->targetFlags, entry->resolvedAction,
3272 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3273 (currentTime - entry->deliveryTime) * 0.000001f);
3274 }
3275 } else {
3276 dump.append(INDENT3 "WaitQueue: <empty>\n");
3277 }
3278 }
3279 } else {
3280 dump.append(INDENT "Connections: <none>\n");
3281 }
3282
3283 if (isAppSwitchPendingLocked()) {
3284 dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
3285 (mAppSwitchDueTime - now()) / 1000000.0);
3286 } else {
3287 dump.append(INDENT "AppSwitch: not pending\n");
3288 }
3289
3290 dump.append(INDENT "Configuration:\n");
3291 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
3292 mConfig.keyRepeatDelay * 0.000001f);
3293 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3294 mConfig.keyRepeatTimeout * 0.000001f);
3295}
3296
3297status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3298 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
3299#if DEBUG_REGISTRATION
3300 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3301 toString(monitor));
3302#endif
3303
3304 { // acquire lock
3305 AutoMutex _l(mLock);
3306
3307 if (getConnectionIndexLocked(inputChannel) >= 0) {
3308 ALOGW("Attempted to register already registered input channel '%s'",
3309 inputChannel->getName().string());
3310 return BAD_VALUE;
3311 }
3312
3313 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3314
3315 int fd = inputChannel->getFd();
3316 mConnectionsByFd.add(fd, connection);
3317
3318 if (monitor) {
3319 mMonitoringChannels.push(inputChannel);
3320 }
3321
3322 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3323 } // release lock
3324
3325 // Wake the looper because some connections have changed.
3326 mLooper->wake();
3327 return OK;
3328}
3329
3330status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3331#if DEBUG_REGISTRATION
3332 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
3333#endif
3334
3335 { // acquire lock
3336 AutoMutex _l(mLock);
3337
3338 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3339 if (status) {
3340 return status;
3341 }
3342 } // release lock
3343
3344 // Wake the poll loop because removing the connection may have changed the current
3345 // synchronization state.
3346 mLooper->wake();
3347 return OK;
3348}
3349
3350status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3351 bool notify) {
3352 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3353 if (connectionIndex < 0) {
3354 ALOGW("Attempted to unregister already unregistered input channel '%s'",
3355 inputChannel->getName().string());
3356 return BAD_VALUE;
3357 }
3358
3359 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3360 mConnectionsByFd.removeItemsAt(connectionIndex);
3361
3362 if (connection->monitor) {
3363 removeMonitorChannelLocked(inputChannel);
3364 }
3365
3366 mLooper->removeFd(inputChannel->getFd());
3367
3368 nsecs_t currentTime = now();
3369 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3370
3371 connection->status = Connection::STATUS_ZOMBIE;
3372 return OK;
3373}
3374
3375void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3376 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3377 if (mMonitoringChannels[i] == inputChannel) {
3378 mMonitoringChannels.removeAt(i);
3379 break;
3380 }
3381 }
3382}
3383
3384ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
3385 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3386 if (connectionIndex >= 0) {
3387 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3388 if (connection->inputChannel.get() == inputChannel.get()) {
3389 return connectionIndex;
3390 }
3391 }
3392
3393 return -1;
3394}
3395
3396void InputDispatcher::onDispatchCycleFinishedLocked(
3397 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3398 CommandEntry* commandEntry = postCommandLocked(
3399 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3400 commandEntry->connection = connection;
3401 commandEntry->eventTime = currentTime;
3402 commandEntry->seq = seq;
3403 commandEntry->handled = handled;
3404}
3405
3406void InputDispatcher::onDispatchCycleBrokenLocked(
3407 nsecs_t currentTime, const sp<Connection>& connection) {
3408 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3409 connection->getInputChannelName());
3410
3411 CommandEntry* commandEntry = postCommandLocked(
3412 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3413 commandEntry->connection = connection;
3414}
3415
3416void InputDispatcher::onANRLocked(
3417 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3418 const sp<InputWindowHandle>& windowHandle,
3419 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3420 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3421 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3422 ALOGI("Application is not responding: %s. "
3423 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
3424 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
3425 dispatchLatency, waitDuration, reason);
3426
3427 // Capture a record of the InputDispatcher state at the time of the ANR.
3428 time_t t = time(NULL);
3429 struct tm tm;
3430 localtime_r(&t, &tm);
3431 char timestr[64];
3432 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3433 mLastANRState.clear();
3434 mLastANRState.append(INDENT "ANR:\n");
3435 mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
3436 mLastANRState.appendFormat(INDENT2 "Window: %s\n",
3437 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
3438 mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3439 mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3440 mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
3441 dumpDispatchStateLocked(mLastANRState);
3442
3443 CommandEntry* commandEntry = postCommandLocked(
3444 & InputDispatcher::doNotifyANRLockedInterruptible);
3445 commandEntry->inputApplicationHandle = applicationHandle;
3446 commandEntry->inputWindowHandle = windowHandle;
3447 commandEntry->reason = reason;
3448}
3449
3450void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3451 CommandEntry* commandEntry) {
3452 mLock.unlock();
3453
3454 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3455
3456 mLock.lock();
3457}
3458
3459void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3460 CommandEntry* commandEntry) {
3461 sp<Connection> connection = commandEntry->connection;
3462
3463 if (connection->status != Connection::STATUS_ZOMBIE) {
3464 mLock.unlock();
3465
3466 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3467
3468 mLock.lock();
3469 }
3470}
3471
3472void InputDispatcher::doNotifyANRLockedInterruptible(
3473 CommandEntry* commandEntry) {
3474 mLock.unlock();
3475
3476 nsecs_t newTimeout = mPolicy->notifyANR(
3477 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3478 commandEntry->reason);
3479
3480 mLock.lock();
3481
3482 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3483 commandEntry->inputWindowHandle != NULL
3484 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
3485}
3486
3487void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3488 CommandEntry* commandEntry) {
3489 KeyEntry* entry = commandEntry->keyEntry;
3490
3491 KeyEvent event;
3492 initializeKeyEvent(&event, entry);
3493
3494 mLock.unlock();
3495
3496 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3497 &event, entry->policyFlags);
3498
3499 mLock.lock();
3500
3501 if (delay < 0) {
3502 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3503 } else if (!delay) {
3504 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3505 } else {
3506 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3507 entry->interceptKeyWakeupTime = now() + delay;
3508 }
3509 entry->release();
3510}
3511
3512void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3513 CommandEntry* commandEntry) {
3514 sp<Connection> connection = commandEntry->connection;
3515 nsecs_t finishTime = commandEntry->eventTime;
3516 uint32_t seq = commandEntry->seq;
3517 bool handled = commandEntry->handled;
3518
3519 // Handle post-event policy actions.
3520 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3521 if (dispatchEntry) {
3522 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3523 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
3524 String8 msg;
3525 msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
3526 connection->getWindowName(), eventDuration * 0.000001f);
3527 dispatchEntry->eventEntry->appendDescription(msg);
3528 ALOGI("%s", msg.string());
3529 }
3530
3531 bool restartEvent;
3532 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3533 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3534 restartEvent = afterKeyEventLockedInterruptible(connection,
3535 dispatchEntry, keyEntry, handled);
3536 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3537 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3538 restartEvent = afterMotionEventLockedInterruptible(connection,
3539 dispatchEntry, motionEntry, handled);
3540 } else {
3541 restartEvent = false;
3542 }
3543
3544 // Dequeue the event and start the next cycle.
3545 // Note that because the lock might have been released, it is possible that the
3546 // contents of the wait queue to have been drained, so we need to double-check
3547 // a few things.
3548 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3549 connection->waitQueue.dequeue(dispatchEntry);
3550 traceWaitQueueLengthLocked(connection);
3551 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3552 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3553 traceOutboundQueueLengthLocked(connection);
3554 } else {
3555 releaseDispatchEntryLocked(dispatchEntry);
3556 }
3557 }
3558
3559 // Start the next dispatch cycle for this connection.
3560 startDispatchCycleLocked(now(), connection);
3561 }
3562}
3563
3564bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3565 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3566 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3567 // Get the fallback key state.
3568 // Clear it out after dispatching the UP.
3569 int32_t originalKeyCode = keyEntry->keyCode;
3570 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3571 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3572 connection->inputState.removeFallbackKey(originalKeyCode);
3573 }
3574
3575 if (handled || !dispatchEntry->hasForegroundTarget()) {
3576 // If the application handles the original key for which we previously
3577 // generated a fallback or if the window is not a foreground window,
3578 // then cancel the associated fallback key, if any.
3579 if (fallbackKeyCode != -1) {
3580 // Dispatch the unhandled key to the policy with the cancel flag.
3581#if DEBUG_OUTBOUND_EVENT_DETAILS
3582 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3583 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3584 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3585 keyEntry->policyFlags);
3586#endif
3587 KeyEvent event;
3588 initializeKeyEvent(&event, keyEntry);
3589 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3590
3591 mLock.unlock();
3592
3593 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3594 &event, keyEntry->policyFlags, &event);
3595
3596 mLock.lock();
3597
3598 // Cancel the fallback key.
3599 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3600 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3601 "application handled the original non-fallback key "
3602 "or is no longer a foreground target, "
3603 "canceling previously dispatched fallback key");
3604 options.keyCode = fallbackKeyCode;
3605 synthesizeCancelationEventsForConnectionLocked(connection, options);
3606 }
3607 connection->inputState.removeFallbackKey(originalKeyCode);
3608 }
3609 } else {
3610 // If the application did not handle a non-fallback key, first check
3611 // that we are in a good state to perform unhandled key event processing
3612 // Then ask the policy what to do with it.
3613 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3614 && keyEntry->repeatCount == 0;
3615 if (fallbackKeyCode == -1 && !initialDown) {
3616#if DEBUG_OUTBOUND_EVENT_DETAILS
3617 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3618 "since this is not an initial down. "
3619 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3620 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3621 keyEntry->policyFlags);
3622#endif
3623 return false;
3624 }
3625
3626 // Dispatch the unhandled key to the policy.
3627#if DEBUG_OUTBOUND_EVENT_DETAILS
3628 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
3629 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3630 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3631 keyEntry->policyFlags);
3632#endif
3633 KeyEvent event;
3634 initializeKeyEvent(&event, keyEntry);
3635
3636 mLock.unlock();
3637
3638 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3639 &event, keyEntry->policyFlags, &event);
3640
3641 mLock.lock();
3642
3643 if (connection->status != Connection::STATUS_NORMAL) {
3644 connection->inputState.removeFallbackKey(originalKeyCode);
3645 return false;
3646 }
3647
3648 // Latch the fallback keycode for this key on an initial down.
3649 // The fallback keycode cannot change at any other point in the lifecycle.
3650 if (initialDown) {
3651 if (fallback) {
3652 fallbackKeyCode = event.getKeyCode();
3653 } else {
3654 fallbackKeyCode = AKEYCODE_UNKNOWN;
3655 }
3656 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3657 }
3658
3659 ALOG_ASSERT(fallbackKeyCode != -1);
3660
3661 // Cancel the fallback key if the policy decides not to send it anymore.
3662 // We will continue to dispatch the key to the policy but we will no
3663 // longer dispatch a fallback key to the application.
3664 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3665 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3666#if DEBUG_OUTBOUND_EVENT_DETAILS
3667 if (fallback) {
3668 ALOGD("Unhandled key event: Policy requested to send key %d"
3669 "as a fallback for %d, but on the DOWN it had requested "
3670 "to send %d instead. Fallback canceled.",
3671 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3672 } else {
3673 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
3674 "but on the DOWN it had requested to send %d. "
3675 "Fallback canceled.",
3676 originalKeyCode, fallbackKeyCode);
3677 }
3678#endif
3679
3680 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3681 "canceling fallback, policy no longer desires it");
3682 options.keyCode = fallbackKeyCode;
3683 synthesizeCancelationEventsForConnectionLocked(connection, options);
3684
3685 fallback = false;
3686 fallbackKeyCode = AKEYCODE_UNKNOWN;
3687 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3688 connection->inputState.setFallbackKey(originalKeyCode,
3689 fallbackKeyCode);
3690 }
3691 }
3692
3693#if DEBUG_OUTBOUND_EVENT_DETAILS
3694 {
3695 String8 msg;
3696 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3697 connection->inputState.getFallbackKeys();
3698 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3699 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3700 fallbackKeys.valueAt(i));
3701 }
3702 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3703 fallbackKeys.size(), msg.string());
3704 }
3705#endif
3706
3707 if (fallback) {
3708 // Restart the dispatch cycle using the fallback key.
3709 keyEntry->eventTime = event.getEventTime();
3710 keyEntry->deviceId = event.getDeviceId();
3711 keyEntry->source = event.getSource();
3712 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3713 keyEntry->keyCode = fallbackKeyCode;
3714 keyEntry->scanCode = event.getScanCode();
3715 keyEntry->metaState = event.getMetaState();
3716 keyEntry->repeatCount = event.getRepeatCount();
3717 keyEntry->downTime = event.getDownTime();
3718 keyEntry->syntheticRepeat = false;
3719
3720#if DEBUG_OUTBOUND_EVENT_DETAILS
3721 ALOGD("Unhandled key event: Dispatching fallback key. "
3722 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3723 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3724#endif
3725 return true; // restart the event
3726 } else {
3727#if DEBUG_OUTBOUND_EVENT_DETAILS
3728 ALOGD("Unhandled key event: No fallback key.");
3729#endif
3730 }
3731 }
3732 }
3733 return false;
3734}
3735
3736bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3737 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3738 return false;
3739}
3740
3741void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3742 mLock.unlock();
3743
3744 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
3745
3746 mLock.lock();
3747}
3748
3749void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3750 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3751 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3752 entry->downTime, entry->eventTime);
3753}
3754
3755void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3756 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3757 // TODO Write some statistics about how long we spend waiting.
3758}
3759
3760void InputDispatcher::traceInboundQueueLengthLocked() {
3761 if (ATRACE_ENABLED()) {
3762 ATRACE_INT("iq", mInboundQueue.count());
3763 }
3764}
3765
3766void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3767 if (ATRACE_ENABLED()) {
3768 char counterName[40];
3769 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3770 ATRACE_INT(counterName, connection->outboundQueue.count());
3771 }
3772}
3773
3774void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3775 if (ATRACE_ENABLED()) {
3776 char counterName[40];
3777 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3778 ATRACE_INT(counterName, connection->waitQueue.count());
3779 }
3780}
3781
3782void InputDispatcher::dump(String8& dump) {
3783 AutoMutex _l(mLock);
3784
3785 dump.append("Input Dispatcher State:\n");
3786 dumpDispatchStateLocked(dump);
3787
3788 if (!mLastANRState.isEmpty()) {
3789 dump.append("\nInput Dispatcher State at time of last ANR:\n");
3790 dump.append(mLastANRState);
3791 }
3792}
3793
3794void InputDispatcher::monitor() {
3795 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3796 mLock.lock();
3797 mLooper->wake();
3798 mDispatcherIsAliveCondition.wait(mLock);
3799 mLock.unlock();
3800}
3801
3802
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803// --- InputDispatcher::InjectionState ---
3804
3805InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3806 refCount(1),
3807 injectorPid(injectorPid), injectorUid(injectorUid),
3808 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3809 pendingForegroundDispatches(0) {
3810}
3811
3812InputDispatcher::InjectionState::~InjectionState() {
3813}
3814
3815void InputDispatcher::InjectionState::release() {
3816 refCount -= 1;
3817 if (refCount == 0) {
3818 delete this;
3819 } else {
3820 ALOG_ASSERT(refCount > 0);
3821 }
3822}
3823
3824
3825// --- InputDispatcher::EventEntry ---
3826
3827InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3828 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3829 injectionState(NULL), dispatchInProgress(false) {
3830}
3831
3832InputDispatcher::EventEntry::~EventEntry() {
3833 releaseInjectionState();
3834}
3835
3836void InputDispatcher::EventEntry::release() {
3837 refCount -= 1;
3838 if (refCount == 0) {
3839 delete this;
3840 } else {
3841 ALOG_ASSERT(refCount > 0);
3842 }
3843}
3844
3845void InputDispatcher::EventEntry::releaseInjectionState() {
3846 if (injectionState) {
3847 injectionState->release();
3848 injectionState = NULL;
3849 }
3850}
3851
3852
3853// --- InputDispatcher::ConfigurationChangedEntry ---
3854
3855InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3856 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3857}
3858
3859InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3860}
3861
3862void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
3863 msg.append("ConfigurationChangedEvent(), policyFlags=0x%08x",
3864 policyFlags);
3865}
3866
3867
3868// --- InputDispatcher::DeviceResetEntry ---
3869
3870InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3871 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3872 deviceId(deviceId) {
3873}
3874
3875InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3876}
3877
3878void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
3879 msg.appendFormat("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
3880 deviceId, policyFlags);
3881}
3882
3883
3884// --- InputDispatcher::KeyEntry ---
3885
3886InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
3887 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
3888 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3889 int32_t repeatCount, nsecs_t downTime) :
3890 EventEntry(TYPE_KEY, eventTime, policyFlags),
3891 deviceId(deviceId), source(source), action(action), flags(flags),
3892 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3893 repeatCount(repeatCount), downTime(downTime),
3894 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3895 interceptKeyWakeupTime(0) {
3896}
3897
3898InputDispatcher::KeyEntry::~KeyEntry() {
3899}
3900
3901void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
3902 msg.appendFormat("KeyEvent(deviceId=%d, source=0x%08x, action=%d, "
3903 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
3904 "repeatCount=%d), policyFlags=0x%08x",
3905 deviceId, source, action, flags, keyCode, scanCode, metaState,
3906 repeatCount, policyFlags);
3907}
3908
3909void InputDispatcher::KeyEntry::recycle() {
3910 releaseInjectionState();
3911
3912 dispatchInProgress = false;
3913 syntheticRepeat = false;
3914 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
3915 interceptKeyWakeupTime = 0;
3916}
3917
3918
3919// --- InputDispatcher::MotionEntry ---
3920
Michael Wright7b159c92015-05-14 14:48:03 +01003921InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
3922 uint32_t source, uint32_t policyFlags, int32_t action, int32_t actionButton,
3923 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3924 float xPrecision, float yPrecision, nsecs_t downTime,
3925 int32_t displayId, uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08003926 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
3927 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928 EventEntry(TYPE_MOTION, eventTime, policyFlags),
3929 eventTime(eventTime),
Michael Wright7b159c92015-05-14 14:48:03 +01003930 deviceId(deviceId), source(source), action(action), actionButton(actionButton),
3931 flags(flags), metaState(metaState), buttonState(buttonState),
3932 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933 downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
3934 for (uint32_t i = 0; i < pointerCount; i++) {
3935 this->pointerProperties[i].copyFrom(pointerProperties[i]);
3936 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003937 if (xOffset || yOffset) {
3938 this->pointerCoords[i].applyOffset(xOffset, yOffset);
3939 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 }
3941}
3942
3943InputDispatcher::MotionEntry::~MotionEntry() {
3944}
3945
3946void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
Michael Wright7b159c92015-05-14 14:48:03 +01003947 msg.appendFormat("MotionEvent(deviceId=%d, source=0x%08x, action=%d, actionButton=0x%08x, "
3948 "flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
3949 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, displayId=%d, pointers=[",
3950 deviceId, source, action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 xPrecision, yPrecision, displayId);
3952 for (uint32_t i = 0; i < pointerCount; i++) {
3953 if (i) {
3954 msg.append(", ");
3955 }
3956 msg.appendFormat("%d: (%.1f, %.1f)", pointerProperties[i].id,
3957 pointerCoords[i].getX(), pointerCoords[i].getY());
3958 }
3959 msg.appendFormat("]), policyFlags=0x%08x", policyFlags);
3960}
3961
3962
3963// --- InputDispatcher::DispatchEntry ---
3964
3965volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
3966
3967InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
3968 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
3969 seq(nextSeq()),
3970 eventEntry(eventEntry), targetFlags(targetFlags),
3971 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
3972 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
3973 eventEntry->refCount += 1;
3974}
3975
3976InputDispatcher::DispatchEntry::~DispatchEntry() {
3977 eventEntry->release();
3978}
3979
3980uint32_t InputDispatcher::DispatchEntry::nextSeq() {
3981 // Sequence number 0 is reserved and will never be returned.
3982 uint32_t seq;
3983 do {
3984 seq = android_atomic_inc(&sNextSeqAtomic);
3985 } while (!seq);
3986 return seq;
3987}
3988
3989
3990// --- InputDispatcher::InputState ---
3991
3992InputDispatcher::InputState::InputState() {
3993}
3994
3995InputDispatcher::InputState::~InputState() {
3996}
3997
3998bool InputDispatcher::InputState::isNeutral() const {
3999 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4000}
4001
4002bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4003 int32_t displayId) const {
4004 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4005 const MotionMemento& memento = mMotionMementos.itemAt(i);
4006 if (memento.deviceId == deviceId
4007 && memento.source == source
4008 && memento.displayId == displayId
4009 && memento.hovering) {
4010 return true;
4011 }
4012 }
4013 return false;
4014}
4015
4016bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4017 int32_t action, int32_t flags) {
4018 switch (action) {
4019 case AKEY_EVENT_ACTION_UP: {
4020 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4021 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4022 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4023 mFallbackKeys.removeItemsAt(i);
4024 } else {
4025 i += 1;
4026 }
4027 }
4028 }
4029 ssize_t index = findKeyMemento(entry);
4030 if (index >= 0) {
4031 mKeyMementos.removeAt(index);
4032 return true;
4033 }
4034 /* FIXME: We can't just drop the key up event because that prevents creating
4035 * popup windows that are automatically shown when a key is held and then
4036 * dismissed when the key is released. The problem is that the popup will
4037 * not have received the original key down, so the key up will be considered
4038 * to be inconsistent with its observed state. We could perhaps handle this
4039 * by synthesizing a key down but that will cause other problems.
4040 *
4041 * So for now, allow inconsistent key up events to be dispatched.
4042 *
4043#if DEBUG_OUTBOUND_EVENT_DETAILS
4044 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4045 "keyCode=%d, scanCode=%d",
4046 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4047#endif
4048 return false;
4049 */
4050 return true;
4051 }
4052
4053 case AKEY_EVENT_ACTION_DOWN: {
4054 ssize_t index = findKeyMemento(entry);
4055 if (index >= 0) {
4056 mKeyMementos.removeAt(index);
4057 }
4058 addKeyMemento(entry, flags);
4059 return true;
4060 }
4061
4062 default:
4063 return true;
4064 }
4065}
4066
4067bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4068 int32_t action, int32_t flags) {
4069 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4070 switch (actionMasked) {
4071 case AMOTION_EVENT_ACTION_UP:
4072 case AMOTION_EVENT_ACTION_CANCEL: {
4073 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4074 if (index >= 0) {
4075 mMotionMementos.removeAt(index);
4076 return true;
4077 }
4078#if DEBUG_OUTBOUND_EVENT_DETAILS
4079 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4080 "actionMasked=%d",
4081 entry->deviceId, entry->source, actionMasked);
4082#endif
4083 return false;
4084 }
4085
4086 case AMOTION_EVENT_ACTION_DOWN: {
4087 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4088 if (index >= 0) {
4089 mMotionMementos.removeAt(index);
4090 }
4091 addMotionMemento(entry, flags, false /*hovering*/);
4092 return true;
4093 }
4094
4095 case AMOTION_EVENT_ACTION_POINTER_UP:
4096 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4097 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004098 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4099 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4100 // generate cancellation events for these since they're based in relative rather than
4101 // absolute units.
4102 return true;
4103 }
4104
Michael Wrightd02c5b62014-02-10 15:10:22 -08004105 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004106
4107 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4108 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4109 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4110 // other value and we need to track the motion so we can send cancellation events for
4111 // anything generating fallback events (e.g. DPad keys for joystick movements).
4112 if (index >= 0) {
4113 if (entry->pointerCoords[0].isEmpty()) {
4114 mMotionMementos.removeAt(index);
4115 } else {
4116 MotionMemento& memento = mMotionMementos.editItemAt(index);
4117 memento.setPointers(entry);
4118 }
4119 } else if (!entry->pointerCoords[0].isEmpty()) {
4120 addMotionMemento(entry, flags, false /*hovering*/);
4121 }
4122
4123 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4124 return true;
4125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 if (index >= 0) {
4127 MotionMemento& memento = mMotionMementos.editItemAt(index);
4128 memento.setPointers(entry);
4129 return true;
4130 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131#if DEBUG_OUTBOUND_EVENT_DETAILS
4132 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
4133 "deviceId=%d, source=%08x, actionMasked=%d",
4134 entry->deviceId, entry->source, actionMasked);
4135#endif
4136 return false;
4137 }
4138
4139 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4140 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4141 if (index >= 0) {
4142 mMotionMementos.removeAt(index);
4143 return true;
4144 }
4145#if DEBUG_OUTBOUND_EVENT_DETAILS
4146 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4147 entry->deviceId, entry->source);
4148#endif
4149 return false;
4150 }
4151
4152 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4153 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4154 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4155 if (index >= 0) {
4156 mMotionMementos.removeAt(index);
4157 }
4158 addMotionMemento(entry, flags, true /*hovering*/);
4159 return true;
4160 }
4161
4162 default:
4163 return true;
4164 }
4165}
4166
4167ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4168 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4169 const KeyMemento& memento = mKeyMementos.itemAt(i);
4170 if (memento.deviceId == entry->deviceId
4171 && memento.source == entry->source
4172 && memento.keyCode == entry->keyCode
4173 && memento.scanCode == entry->scanCode) {
4174 return i;
4175 }
4176 }
4177 return -1;
4178}
4179
4180ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4181 bool hovering) const {
4182 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4183 const MotionMemento& memento = mMotionMementos.itemAt(i);
4184 if (memento.deviceId == entry->deviceId
4185 && memento.source == entry->source
4186 && memento.displayId == entry->displayId
4187 && memento.hovering == hovering) {
4188 return i;
4189 }
4190 }
4191 return -1;
4192}
4193
4194void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4195 mKeyMementos.push();
4196 KeyMemento& memento = mKeyMementos.editTop();
4197 memento.deviceId = entry->deviceId;
4198 memento.source = entry->source;
4199 memento.keyCode = entry->keyCode;
4200 memento.scanCode = entry->scanCode;
4201 memento.metaState = entry->metaState;
4202 memento.flags = flags;
4203 memento.downTime = entry->downTime;
4204 memento.policyFlags = entry->policyFlags;
4205}
4206
4207void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4208 int32_t flags, bool hovering) {
4209 mMotionMementos.push();
4210 MotionMemento& memento = mMotionMementos.editTop();
4211 memento.deviceId = entry->deviceId;
4212 memento.source = entry->source;
4213 memento.flags = flags;
4214 memento.xPrecision = entry->xPrecision;
4215 memento.yPrecision = entry->yPrecision;
4216 memento.downTime = entry->downTime;
4217 memento.displayId = entry->displayId;
4218 memento.setPointers(entry);
4219 memento.hovering = hovering;
4220 memento.policyFlags = entry->policyFlags;
4221}
4222
4223void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4224 pointerCount = entry->pointerCount;
4225 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4226 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4227 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4228 }
4229}
4230
4231void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4232 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4233 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4234 const KeyMemento& memento = mKeyMementos.itemAt(i);
4235 if (shouldCancelKey(memento, options)) {
4236 outEvents.push(new KeyEntry(currentTime,
4237 memento.deviceId, memento.source, memento.policyFlags,
4238 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4239 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4240 }
4241 }
4242
4243 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4244 const MotionMemento& memento = mMotionMementos.itemAt(i);
4245 if (shouldCancelMotion(memento, options)) {
4246 outEvents.push(new MotionEntry(currentTime,
4247 memento.deviceId, memento.source, memento.policyFlags,
4248 memento.hovering
4249 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4250 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004251 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252 memento.xPrecision, memento.yPrecision, memento.downTime,
4253 memento.displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004254 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4255 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 }
4257 }
4258}
4259
4260void InputDispatcher::InputState::clear() {
4261 mKeyMementos.clear();
4262 mMotionMementos.clear();
4263 mFallbackKeys.clear();
4264}
4265
4266void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4267 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4268 const MotionMemento& memento = mMotionMementos.itemAt(i);
4269 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4270 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4271 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4272 if (memento.deviceId == otherMemento.deviceId
4273 && memento.source == otherMemento.source
4274 && memento.displayId == otherMemento.displayId) {
4275 other.mMotionMementos.removeAt(j);
4276 } else {
4277 j += 1;
4278 }
4279 }
4280 other.mMotionMementos.push(memento);
4281 }
4282 }
4283}
4284
4285int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4286 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4287 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4288}
4289
4290void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4291 int32_t fallbackKeyCode) {
4292 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4293 if (index >= 0) {
4294 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4295 } else {
4296 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4297 }
4298}
4299
4300void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4301 mFallbackKeys.removeItem(originalKeyCode);
4302}
4303
4304bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4305 const CancelationOptions& options) {
4306 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4307 return false;
4308 }
4309
4310 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4311 return false;
4312 }
4313
4314 switch (options.mode) {
4315 case CancelationOptions::CANCEL_ALL_EVENTS:
4316 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4317 return true;
4318 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4319 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4320 default:
4321 return false;
4322 }
4323}
4324
4325bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4326 const CancelationOptions& options) {
4327 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4328 return false;
4329 }
4330
4331 switch (options.mode) {
4332 case CancelationOptions::CANCEL_ALL_EVENTS:
4333 return true;
4334 case CancelationOptions::CANCEL_POINTER_EVENTS:
4335 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4336 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4337 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4338 default:
4339 return false;
4340 }
4341}
4342
4343
4344// --- InputDispatcher::Connection ---
4345
4346InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4347 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4348 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4349 monitor(monitor),
4350 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4351}
4352
4353InputDispatcher::Connection::~Connection() {
4354}
4355
4356const char* InputDispatcher::Connection::getWindowName() const {
4357 if (inputWindowHandle != NULL) {
4358 return inputWindowHandle->getName().string();
4359 }
4360 if (monitor) {
4361 return "monitor";
4362 }
4363 return "?";
4364}
4365
4366const char* InputDispatcher::Connection::getStatusLabel() const {
4367 switch (status) {
4368 case STATUS_NORMAL:
4369 return "NORMAL";
4370
4371 case STATUS_BROKEN:
4372 return "BROKEN";
4373
4374 case STATUS_ZOMBIE:
4375 return "ZOMBIE";
4376
4377 default:
4378 return "UNKNOWN";
4379 }
4380}
4381
4382InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4383 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4384 if (entry->seq == seq) {
4385 return entry;
4386 }
4387 }
4388 return NULL;
4389}
4390
4391
4392// --- InputDispatcher::CommandEntry ---
4393
4394InputDispatcher::CommandEntry::CommandEntry(Command command) :
4395 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4396 seq(0), handled(false) {
4397}
4398
4399InputDispatcher::CommandEntry::~CommandEntry() {
4400}
4401
4402
4403// --- InputDispatcher::TouchState ---
4404
4405InputDispatcher::TouchState::TouchState() :
4406 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
4407}
4408
4409InputDispatcher::TouchState::~TouchState() {
4410}
4411
4412void InputDispatcher::TouchState::reset() {
4413 down = false;
4414 split = false;
4415 deviceId = -1;
4416 source = 0;
4417 displayId = -1;
4418 windows.clear();
4419}
4420
4421void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4422 down = other.down;
4423 split = other.split;
4424 deviceId = other.deviceId;
4425 source = other.source;
4426 displayId = other.displayId;
4427 windows = other.windows;
4428}
4429
4430void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4431 int32_t targetFlags, BitSet32 pointerIds) {
4432 if (targetFlags & InputTarget::FLAG_SPLIT) {
4433 split = true;
4434 }
4435
4436 for (size_t i = 0; i < windows.size(); i++) {
4437 TouchedWindow& touchedWindow = windows.editItemAt(i);
4438 if (touchedWindow.windowHandle == windowHandle) {
4439 touchedWindow.targetFlags |= targetFlags;
4440 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4441 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4442 }
4443 touchedWindow.pointerIds.value |= pointerIds.value;
4444 return;
4445 }
4446 }
4447
4448 windows.push();
4449
4450 TouchedWindow& touchedWindow = windows.editTop();
4451 touchedWindow.windowHandle = windowHandle;
4452 touchedWindow.targetFlags = targetFlags;
4453 touchedWindow.pointerIds = pointerIds;
4454}
4455
4456void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4457 for (size_t i = 0; i < windows.size(); i++) {
4458 if (windows.itemAt(i).windowHandle == windowHandle) {
4459 windows.removeAt(i);
4460 return;
4461 }
4462 }
4463}
4464
4465void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4466 for (size_t i = 0 ; i < windows.size(); ) {
4467 TouchedWindow& window = windows.editItemAt(i);
4468 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4469 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4470 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4471 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4472 i += 1;
4473 } else {
4474 windows.removeAt(i);
4475 }
4476 }
4477}
4478
4479sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4480 for (size_t i = 0; i < windows.size(); i++) {
4481 const TouchedWindow& window = windows.itemAt(i);
4482 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4483 return window.windowHandle;
4484 }
4485 }
4486 return NULL;
4487}
4488
4489bool InputDispatcher::TouchState::isSlippery() const {
4490 // Must have exactly one foreground window.
4491 bool haveSlipperyForegroundWindow = false;
4492 for (size_t i = 0; i < windows.size(); i++) {
4493 const TouchedWindow& window = windows.itemAt(i);
4494 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4495 if (haveSlipperyForegroundWindow
4496 || !(window.windowHandle->getInfo()->layoutParamsFlags
4497 & InputWindowInfo::FLAG_SLIPPERY)) {
4498 return false;
4499 }
4500 haveSlipperyForegroundWindow = true;
4501 }
4502 }
4503 return haveSlipperyForegroundWindow;
4504}
4505
4506
4507// --- InputDispatcherThread ---
4508
4509InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4510 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4511}
4512
4513InputDispatcherThread::~InputDispatcherThread() {
4514}
4515
4516bool InputDispatcherThread::threadLoop() {
4517 mDispatcher->dispatchOnce();
4518 return true;
4519}
4520
4521} // namespace android