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