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