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