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