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