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