blob: 69067d225bb2345cfb027aef00109f199826beb2 [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
688 ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
689#endif
690
691 // Reset key repeating in case a keyboard device was added or removed or something.
692 resetKeyRepeatLocked();
693
694 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
695 CommandEntry* commandEntry = postCommandLocked(
696 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
697 commandEntry->eventTime = entry->eventTime;
698 return true;
699}
700
701bool InputDispatcher::dispatchDeviceResetLocked(
702 nsecs_t currentTime, DeviceResetEntry* entry) {
703#if DEBUG_OUTBOUND_EVENT_DETAILS
704 ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
705#endif
706
707 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
708 "device was reset");
709 options.deviceId = entry->deviceId;
710 synthesizeCancelationEventsForAllConnectionsLocked(options);
711 return true;
712}
713
714bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
715 DropReason* dropReason, nsecs_t* nextWakeupTime) {
716 // Preprocessing.
717 if (! entry->dispatchInProgress) {
718 if (entry->repeatCount == 0
719 && entry->action == AKEY_EVENT_ACTION_DOWN
720 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
721 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
722 if (mKeyRepeatState.lastKeyEntry
723 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
724 // We have seen two identical key downs in a row which indicates that the device
725 // driver is automatically generating key repeats itself. We take note of the
726 // repeat here, but we disable our own next key repeat timer since it is clear that
727 // we will not need to synthesize key repeats ourselves.
728 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
729 resetKeyRepeatLocked();
730 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
731 } else {
732 // Not a repeat. Save key down state in case we do see a repeat later.
733 resetKeyRepeatLocked();
734 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
735 }
736 mKeyRepeatState.lastKeyEntry = entry;
737 entry->refCount += 1;
738 } else if (! entry->syntheticRepeat) {
739 resetKeyRepeatLocked();
740 }
741
742 if (entry->repeatCount == 1) {
743 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
744 } else {
745 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
746 }
747
748 entry->dispatchInProgress = true;
749
750 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
751 }
752
753 // Handle case where the policy asked us to try again later last time.
754 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
755 if (currentTime < entry->interceptKeyWakeupTime) {
756 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
757 *nextWakeupTime = entry->interceptKeyWakeupTime;
758 }
759 return false; // wait until next wakeup
760 }
761 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
762 entry->interceptKeyWakeupTime = 0;
763 }
764
765 // Give the policy a chance to intercept the key.
766 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
767 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
768 CommandEntry* commandEntry = postCommandLocked(
769 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
770 if (mFocusedWindowHandle != NULL) {
771 commandEntry->inputWindowHandle = mFocusedWindowHandle;
772 }
773 commandEntry->keyEntry = entry;
774 entry->refCount += 1;
775 return false; // wait for the command to run
776 } else {
777 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
778 }
779 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
780 if (*dropReason == DROP_REASON_NOT_DROPPED) {
781 *dropReason = DROP_REASON_POLICY;
782 }
783 }
784
785 // Clean up if dropping the event.
786 if (*dropReason != DROP_REASON_NOT_DROPPED) {
787 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
788 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
789 return true;
790 }
791
792 // Identify targets.
793 Vector<InputTarget> inputTargets;
794 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
795 entry, inputTargets, nextWakeupTime);
796 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
797 return false;
798 }
799
800 setInjectionResultLocked(entry, injectionResult);
801 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
802 return true;
803 }
804
805 addMonitoringTargetsLocked(inputTargets);
806
807 // Dispatch the key.
808 dispatchEventLocked(currentTime, entry, inputTargets);
809 return true;
810}
811
812void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
813#if DEBUG_OUTBOUND_EVENT_DETAILS
814 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
815 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
816 "repeatCount=%d, downTime=%lld",
817 prefix,
818 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
819 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
820 entry->repeatCount, entry->downTime);
821#endif
822}
823
824bool InputDispatcher::dispatchMotionLocked(
825 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
826 // Preprocessing.
827 if (! entry->dispatchInProgress) {
828 entry->dispatchInProgress = true;
829
830 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
831 }
832
833 // Clean up if dropping the event.
834 if (*dropReason != DROP_REASON_NOT_DROPPED) {
835 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
836 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
837 return true;
838 }
839
840 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
841
842 // Identify targets.
843 Vector<InputTarget> inputTargets;
844
845 bool conflictingPointerActions = false;
846 int32_t injectionResult;
847 if (isPointerEvent) {
848 // Pointer event. (eg. touchscreen)
849 injectionResult = findTouchedWindowTargetsLocked(currentTime,
850 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
851 } else {
852 // Non touch event. (eg. trackball)
853 injectionResult = findFocusedWindowTargetsLocked(currentTime,
854 entry, inputTargets, nextWakeupTime);
855 }
856 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
857 return false;
858 }
859
860 setInjectionResultLocked(entry, injectionResult);
861 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100862 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
863 CancelationOptions::Mode mode(isPointerEvent ?
864 CancelationOptions::CANCEL_POINTER_EVENTS :
865 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
866 CancelationOptions options(mode, "input event injection failed");
867 synthesizeCancelationEventsForMonitorsLocked(options);
868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 return true;
870 }
871
Tarandeep Singh48aeb512017-07-17 11:22:52 -0700872 addMonitoringTargetsLocked(inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873
874 // Dispatch the motion.
875 if (conflictingPointerActions) {
876 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
877 "conflicting pointer actions");
878 synthesizeCancelationEventsForAllConnectionsLocked(options);
879 }
880 dispatchEventLocked(currentTime, entry, inputTargets);
881 return true;
882}
883
884
885void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
886#if DEBUG_OUTBOUND_EVENT_DETAILS
887 ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100888 "action=0x%x, actionButton=0x%x, flags=0x%x, "
889 "metaState=0x%x, buttonState=0x%x,"
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
891 prefix,
892 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100893 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 entry->metaState, entry->buttonState,
895 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
896 entry->downTime);
897
898 for (uint32_t i = 0; i < entry->pointerCount; i++) {
899 ALOGD(" Pointer %d: id=%d, toolType=%d, "
900 "x=%f, y=%f, pressure=%f, size=%f, "
901 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800902 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 i, entry->pointerProperties[i].id,
904 entry->pointerProperties[i].toolType,
905 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
906 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
907 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
908 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
909 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
910 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
911 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
912 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800913 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914 }
915#endif
916}
917
918void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
919 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
920#if DEBUG_DISPATCH_CYCLE
921 ALOGD("dispatchEventToCurrentInputTargets");
922#endif
923
924 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
925
926 pokeUserActivityLocked(eventEntry);
927
928 for (size_t i = 0; i < inputTargets.size(); i++) {
929 const InputTarget& inputTarget = inputTargets.itemAt(i);
930
931 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
932 if (connectionIndex >= 0) {
933 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
934 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
935 } else {
936#if DEBUG_FOCUS
937 ALOGD("Dropping event delivery to target with channel '%s' because it "
938 "is no longer registered with the input dispatcher.",
939 inputTarget.inputChannel->getName().string());
940#endif
941 }
942 }
943}
944
945int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
946 const EventEntry* entry,
947 const sp<InputApplicationHandle>& applicationHandle,
948 const sp<InputWindowHandle>& windowHandle,
949 nsecs_t* nextWakeupTime, const char* reason) {
950 if (applicationHandle == NULL && windowHandle == NULL) {
951 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
952#if DEBUG_FOCUS
953 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
954#endif
955 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
956 mInputTargetWaitStartTime = currentTime;
957 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
958 mInputTargetWaitTimeoutExpired = false;
959 mInputTargetWaitApplicationHandle.clear();
960 }
961 } else {
962 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
963#if DEBUG_FOCUS
964 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
965 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
966 reason);
967#endif
968 nsecs_t timeout;
969 if (windowHandle != NULL) {
970 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
971 } else if (applicationHandle != NULL) {
972 timeout = applicationHandle->getDispatchingTimeout(
973 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
974 } else {
975 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
976 }
977
978 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
979 mInputTargetWaitStartTime = currentTime;
980 mInputTargetWaitTimeoutTime = currentTime + timeout;
981 mInputTargetWaitTimeoutExpired = false;
982 mInputTargetWaitApplicationHandle.clear();
983
984 if (windowHandle != NULL) {
985 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
986 }
987 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
988 mInputTargetWaitApplicationHandle = applicationHandle;
989 }
990 }
991 }
992
993 if (mInputTargetWaitTimeoutExpired) {
994 return INPUT_EVENT_INJECTION_TIMED_OUT;
995 }
996
997 if (currentTime >= mInputTargetWaitTimeoutTime) {
998 onANRLocked(currentTime, applicationHandle, windowHandle,
999 entry->eventTime, mInputTargetWaitStartTime, reason);
1000
1001 // Force poll loop to wake up immediately on next iteration once we get the
1002 // ANR response back from the policy.
1003 *nextWakeupTime = LONG_LONG_MIN;
1004 return INPUT_EVENT_INJECTION_PENDING;
1005 } else {
1006 // Force poll loop to wake up when timeout is due.
1007 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1008 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1009 }
1010 return INPUT_EVENT_INJECTION_PENDING;
1011 }
1012}
1013
1014void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1015 const sp<InputChannel>& inputChannel) {
1016 if (newTimeout > 0) {
1017 // Extend the timeout.
1018 mInputTargetWaitTimeoutTime = now() + newTimeout;
1019 } else {
1020 // Give up.
1021 mInputTargetWaitTimeoutExpired = true;
1022
1023 // Input state will not be realistic. Mark it out of sync.
1024 if (inputChannel.get()) {
1025 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1026 if (connectionIndex >= 0) {
1027 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1028 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1029
1030 if (windowHandle != NULL) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001031 const InputWindowInfo* info = windowHandle->getInfo();
1032 if (info) {
1033 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId);
1034 if (stateIndex >= 0) {
1035 mTouchStatesByDisplay.editValueAt(stateIndex).removeWindow(
1036 windowHandle);
1037 }
1038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 }
1040
1041 if (connection->status == Connection::STATUS_NORMAL) {
1042 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1043 "application not responding");
1044 synthesizeCancelationEventsForConnectionLocked(connection, options);
1045 }
1046 }
1047 }
1048 }
1049}
1050
1051nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1052 nsecs_t currentTime) {
1053 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1054 return currentTime - mInputTargetWaitStartTime;
1055 }
1056 return 0;
1057}
1058
1059void InputDispatcher::resetANRTimeoutsLocked() {
1060#if DEBUG_FOCUS
1061 ALOGD("Resetting ANR timeouts.");
1062#endif
1063
1064 // Reset input target wait timeout.
1065 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1066 mInputTargetWaitApplicationHandle.clear();
1067}
1068
1069int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1070 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1071 int32_t injectionResult;
Jeff Brownffb49772014-10-10 19:01:34 -07001072 String8 reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073
1074 // If there is no currently focused window and no focused application
1075 // then drop the event.
1076 if (mFocusedWindowHandle == NULL) {
1077 if (mFocusedApplicationHandle != NULL) {
1078 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1079 mFocusedApplicationHandle, NULL, nextWakeupTime,
1080 "Waiting because no window has focus but there is a "
1081 "focused application that may eventually add a window "
1082 "when it finishes starting up.");
1083 goto Unresponsive;
1084 }
1085
1086 ALOGI("Dropping event because there is no focused window or focused application.");
1087 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1088 goto Failed;
1089 }
1090
1091 // Check permissions.
1092 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
1093 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1094 goto Failed;
1095 }
1096
Jeff Brownffb49772014-10-10 19:01:34 -07001097 // Check whether the window is ready for more input.
1098 reason = checkWindowReadyForMoreInputLocked(currentTime,
1099 mFocusedWindowHandle, entry, "focused");
1100 if (!reason.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brownffb49772014-10-10 19:01:34 -07001102 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, reason.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103 goto Unresponsive;
1104 }
1105
1106 // Success! Output targets.
1107 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1108 addWindowTargetLocked(mFocusedWindowHandle,
1109 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1110 inputTargets);
1111
1112 // Done.
1113Failed:
1114Unresponsive:
1115 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1116 updateDispatchStatisticsLocked(currentTime, entry,
1117 injectionResult, timeSpentWaitingForApplication);
1118#if DEBUG_FOCUS
1119 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1120 "timeSpentWaitingForApplication=%0.1fms",
1121 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1122#endif
1123 return injectionResult;
1124}
1125
1126int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1127 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1128 bool* outConflictingPointerActions) {
1129 enum InjectionPermission {
1130 INJECTION_PERMISSION_UNKNOWN,
1131 INJECTION_PERMISSION_GRANTED,
1132 INJECTION_PERMISSION_DENIED
1133 };
1134
1135 nsecs_t startTime = now();
1136
1137 // For security reasons, we defer updating the touch state until we are sure that
1138 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139 int32_t displayId = entry->displayId;
1140 int32_t action = entry->action;
1141 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1142
1143 // Update the touch state as needed based on the properties of the touch event.
1144 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1145 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1146 sp<InputWindowHandle> newHoverWindowHandle;
1147
Jeff Brownf086ddb2014-02-11 14:28:48 -08001148 // Copy current touch state into mTempTouchState.
1149 // This state is always reset at the end of this function, so if we don't find state
1150 // for the specified display then our initial state will be empty.
1151 const TouchState* oldState = NULL;
1152 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1153 if (oldStateIndex >= 0) {
1154 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1155 mTempTouchState.copyFrom(*oldState);
1156 }
1157
1158 bool isSplit = mTempTouchState.split;
1159 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1160 && (mTempTouchState.deviceId != entry->deviceId
1161 || mTempTouchState.source != entry->source
1162 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1164 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1165 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1166 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1167 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1168 || isHoverAction);
1169 bool wrongDevice = false;
1170 if (newGesture) {
1171 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001172 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173#if DEBUG_FOCUS
1174 ALOGD("Dropping event because a pointer for a different device is already down.");
1175#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001176 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1178 switchedDevice = false;
1179 wrongDevice = true;
1180 goto Failed;
1181 }
1182 mTempTouchState.reset();
1183 mTempTouchState.down = down;
1184 mTempTouchState.deviceId = entry->deviceId;
1185 mTempTouchState.source = entry->source;
1186 mTempTouchState.displayId = displayId;
1187 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001188 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1189#if DEBUG_FOCUS
1190 ALOGI("Dropping move event because a pointer for a different device is already active.");
1191#endif
1192 // TODO: test multiple simultaneous input streams.
1193 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1194 switchedDevice = false;
1195 wrongDevice = true;
1196 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 }
1198
1199 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1200 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1201
1202 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1203 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1204 getAxisValue(AMOTION_EVENT_AXIS_X));
1205 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1206 getAxisValue(AMOTION_EVENT_AXIS_Y));
1207 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 bool isTouchModal = false;
1209
1210 // Traverse windows from front to back to find touched window and outside targets.
1211 size_t numWindows = mWindowHandles.size();
1212 for (size_t i = 0; i < numWindows; i++) {
1213 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1214 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1215 if (windowInfo->displayId != displayId) {
1216 continue; // wrong display
1217 }
1218
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 int32_t flags = windowInfo->layoutParamsFlags;
1220 if (windowInfo->visible) {
1221 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1222 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1223 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1224 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001225 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 break; // found touched window, exit window loop
1227 }
1228 }
1229
1230 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1231 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001233 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 }
1235 }
1236 }
1237
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 // Figure out whether splitting will be allowed for this window.
1239 if (newTouchedWindowHandle != NULL
1240 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1241 // New window supports splitting.
1242 isSplit = true;
1243 } else if (isSplit) {
1244 // New window does not support splitting but we have already split events.
1245 // Ignore the new window.
1246 newTouchedWindowHandle = NULL;
1247 }
1248
1249 // Handle the case where we did not find a window.
1250 if (newTouchedWindowHandle == NULL) {
1251 // Try to assign the pointer to the first foreground window we find, if there is one.
1252 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1253 if (newTouchedWindowHandle == NULL) {
1254 ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y);
1255 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1256 goto Failed;
1257 }
1258 }
1259
1260 // Set target flags.
1261 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1262 if (isSplit) {
1263 targetFlags |= InputTarget::FLAG_SPLIT;
1264 }
1265 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1266 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001267 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1268 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269 }
1270
1271 // Update hover state.
1272 if (isHoverAction) {
1273 newHoverWindowHandle = newTouchedWindowHandle;
1274 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1275 newHoverWindowHandle = mLastHoverWindowHandle;
1276 }
1277
1278 // Update the temporary touch state.
1279 BitSet32 pointerIds;
1280 if (isSplit) {
1281 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1282 pointerIds.markBit(pointerId);
1283 }
1284 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1285 } else {
1286 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1287
1288 // If the pointer is not currently down, then ignore the event.
1289 if (! mTempTouchState.down) {
1290#if DEBUG_FOCUS
1291 ALOGD("Dropping event because the pointer is not down or we previously "
1292 "dropped the pointer down event.");
1293#endif
1294 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1295 goto Failed;
1296 }
1297
1298 // Check whether touches should slip outside of the current foreground window.
1299 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1300 && entry->pointerCount == 1
1301 && mTempTouchState.isSlippery()) {
1302 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1303 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1304
1305 sp<InputWindowHandle> oldTouchedWindowHandle =
1306 mTempTouchState.getFirstForegroundWindowHandle();
1307 sp<InputWindowHandle> newTouchedWindowHandle =
1308 findTouchedWindowAtLocked(displayId, x, y);
1309 if (oldTouchedWindowHandle != newTouchedWindowHandle
1310 && newTouchedWindowHandle != NULL) {
1311#if DEBUG_FOCUS
1312 ALOGD("Touch is slipping out of window %s into window %s.",
1313 oldTouchedWindowHandle->getName().string(),
1314 newTouchedWindowHandle->getName().string());
1315#endif
1316 // Make a slippery exit from the old window.
1317 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1318 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1319
1320 // Make a slippery entrance into the new window.
1321 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1322 isSplit = true;
1323 }
1324
1325 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1326 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1327 if (isSplit) {
1328 targetFlags |= InputTarget::FLAG_SPLIT;
1329 }
1330 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1331 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1332 }
1333
1334 BitSet32 pointerIds;
1335 if (isSplit) {
1336 pointerIds.markBit(entry->pointerProperties[0].id);
1337 }
1338 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1339 }
1340 }
1341 }
1342
1343 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1344 // Let the previous window know that the hover sequence is over.
1345 if (mLastHoverWindowHandle != NULL) {
1346#if DEBUG_HOVER
1347 ALOGD("Sending hover exit event to window %s.",
1348 mLastHoverWindowHandle->getName().string());
1349#endif
1350 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1351 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1352 }
1353
1354 // Let the new window know that the hover sequence is starting.
1355 if (newHoverWindowHandle != NULL) {
1356#if DEBUG_HOVER
1357 ALOGD("Sending hover enter event to window %s.",
1358 newHoverWindowHandle->getName().string());
1359#endif
1360 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1361 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1362 }
1363 }
1364
1365 // Check permission to inject into all touched foreground windows and ensure there
1366 // is at least one touched foreground window.
1367 {
1368 bool haveForegroundWindow = false;
1369 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1370 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1371 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1372 haveForegroundWindow = true;
1373 if (! checkInjectionPermission(touchedWindow.windowHandle,
1374 entry->injectionState)) {
1375 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1376 injectionPermission = INJECTION_PERMISSION_DENIED;
1377 goto Failed;
1378 }
1379 }
1380 }
1381 if (! haveForegroundWindow) {
1382#if DEBUG_FOCUS
1383 ALOGD("Dropping event because there is no touched foreground window to receive it.");
1384#endif
1385 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1386 goto Failed;
1387 }
1388
1389 // Permission granted to injection into all touched foreground windows.
1390 injectionPermission = INJECTION_PERMISSION_GRANTED;
1391 }
1392
1393 // Check whether windows listening for outside touches are owned by the same UID. If it is
1394 // set the policy flag that we will not reveal coordinate information to this window.
1395 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1396 sp<InputWindowHandle> foregroundWindowHandle =
1397 mTempTouchState.getFirstForegroundWindowHandle();
1398 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1399 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1400 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1401 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1402 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1403 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1404 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1405 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1406 }
1407 }
1408 }
1409 }
1410
1411 // Ensure all touched foreground windows are ready for new input.
1412 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1413 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1414 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001415 // Check whether the window is ready for more input.
1416 String8 reason = checkWindowReadyForMoreInputLocked(currentTime,
1417 touchedWindow.windowHandle, entry, "touched");
1418 if (!reason.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Jeff Brownffb49772014-10-10 19:01:34 -07001420 NULL, touchedWindow.windowHandle, nextWakeupTime, reason.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 goto Unresponsive;
1422 }
1423 }
1424 }
1425
1426 // If this is the first pointer going down and the touched window has a wallpaper
1427 // then also add the touched wallpaper windows so they are locked in for the duration
1428 // of the touch gesture.
1429 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1430 // engine only supports touch events. We would need to add a mechanism similar
1431 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1432 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1433 sp<InputWindowHandle> foregroundWindowHandle =
1434 mTempTouchState.getFirstForegroundWindowHandle();
1435 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
1436 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1437 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1438 const InputWindowInfo* info = windowHandle->getInfo();
1439 if (info->displayId == displayId
1440 && windowHandle->getInfo()->layoutParamsType
1441 == InputWindowInfo::TYPE_WALLPAPER) {
1442 mTempTouchState.addOrUpdateWindow(windowHandle,
1443 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001444 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445 | InputTarget::FLAG_DISPATCH_AS_IS,
1446 BitSet32(0));
1447 }
1448 }
1449 }
1450 }
1451
1452 // Success! Output targets.
1453 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1454
1455 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1456 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1457 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1458 touchedWindow.pointerIds, inputTargets);
1459 }
1460
1461 // Drop the outside or hover touch windows since we will not care about them
1462 // in the next iteration.
1463 mTempTouchState.filterNonAsIsTouchWindows();
1464
1465Failed:
1466 // Check injection permission once and for all.
1467 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
1468 if (checkInjectionPermission(NULL, entry->injectionState)) {
1469 injectionPermission = INJECTION_PERMISSION_GRANTED;
1470 } else {
1471 injectionPermission = INJECTION_PERMISSION_DENIED;
1472 }
1473 }
1474
1475 // Update final pieces of touch state if the injector had permission.
1476 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1477 if (!wrongDevice) {
1478 if (switchedDevice) {
1479#if DEBUG_FOCUS
1480 ALOGD("Conflicting pointer actions: Switched to a different device.");
1481#endif
1482 *outConflictingPointerActions = true;
1483 }
1484
1485 if (isHoverAction) {
1486 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001487 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488#if DEBUG_FOCUS
1489 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1490#endif
1491 *outConflictingPointerActions = true;
1492 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001493 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1495 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001496 mTempTouchState.deviceId = entry->deviceId;
1497 mTempTouchState.source = entry->source;
1498 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499 }
1500 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1501 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1502 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001503 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1505 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001506 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507#if DEBUG_FOCUS
1508 ALOGD("Conflicting pointer actions: Down received while already down.");
1509#endif
1510 *outConflictingPointerActions = true;
1511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1513 // One pointer went up.
1514 if (isSplit) {
1515 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1516 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1517
1518 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1519 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1520 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1521 touchedWindow.pointerIds.clearBit(pointerId);
1522 if (touchedWindow.pointerIds.isEmpty()) {
1523 mTempTouchState.windows.removeAt(i);
1524 continue;
1525 }
1526 }
1527 i += 1;
1528 }
1529 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001530 }
1531
1532 // Save changes unless the action was scroll in which case the temporary touch
1533 // state was only valid for this one action.
1534 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1535 if (mTempTouchState.displayId >= 0) {
1536 if (oldStateIndex >= 0) {
1537 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1538 } else {
1539 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1540 }
1541 } else if (oldStateIndex >= 0) {
1542 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001544 }
1545
1546 // Update hover state.
1547 mLastHoverWindowHandle = newHoverWindowHandle;
1548 }
1549 } else {
1550#if DEBUG_FOCUS
1551 ALOGD("Not updating touch focus because injection was denied.");
1552#endif
1553 }
1554
1555Unresponsive:
1556 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1557 mTempTouchState.reset();
1558
1559 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1560 updateDispatchStatisticsLocked(currentTime, entry,
1561 injectionResult, timeSpentWaitingForApplication);
1562#if DEBUG_FOCUS
1563 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1564 "timeSpentWaitingForApplication=%0.1fms",
1565 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1566#endif
1567 return injectionResult;
1568}
1569
1570void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1571 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1572 inputTargets.push();
1573
1574 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1575 InputTarget& target = inputTargets.editTop();
1576 target.inputChannel = windowInfo->inputChannel;
1577 target.flags = targetFlags;
1578 target.xOffset = - windowInfo->frameLeft;
1579 target.yOffset = - windowInfo->frameTop;
1580 target.scaleFactor = windowInfo->scaleFactor;
1581 target.pointerIds = pointerIds;
1582}
1583
1584void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
1585 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1586 inputTargets.push();
1587
1588 InputTarget& target = inputTargets.editTop();
1589 target.inputChannel = mMonitoringChannels[i];
1590 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1591 target.xOffset = 0;
1592 target.yOffset = 0;
1593 target.pointerIds.clear();
1594 target.scaleFactor = 1.0f;
1595 }
1596}
1597
1598bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1599 const InjectionState* injectionState) {
1600 if (injectionState
1601 && (windowHandle == NULL
1602 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1603 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1604 if (windowHandle != NULL) {
1605 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1606 "owned by uid %d",
1607 injectionState->injectorPid, injectionState->injectorUid,
1608 windowHandle->getName().string(),
1609 windowHandle->getInfo()->ownerUid);
1610 } else {
1611 ALOGW("Permission denied: injecting event from pid %d uid %d",
1612 injectionState->injectorPid, injectionState->injectorUid);
1613 }
1614 return false;
1615 }
1616 return true;
1617}
1618
1619bool InputDispatcher::isWindowObscuredAtPointLocked(
1620 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1621 int32_t displayId = windowHandle->getInfo()->displayId;
1622 size_t numWindows = mWindowHandles.size();
1623 for (size_t i = 0; i < numWindows; i++) {
1624 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1625 if (otherHandle == windowHandle) {
1626 break;
1627 }
1628
1629 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1630 if (otherInfo->displayId == displayId
1631 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1632 && otherInfo->frameContainsPoint(x, y)) {
1633 return true;
1634 }
1635 }
1636 return false;
1637}
1638
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001639
1640bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1641 int32_t displayId = windowHandle->getInfo()->displayId;
1642 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1643 size_t numWindows = mWindowHandles.size();
1644 for (size_t i = 0; i < numWindows; i++) {
1645 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1646 if (otherHandle == windowHandle) {
1647 break;
1648 }
1649
1650 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1651 if (otherInfo->displayId == displayId
1652 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1653 && otherInfo->overlaps(windowInfo)) {
1654 return true;
1655 }
1656 }
1657 return false;
1658}
1659
Jeff Brownffb49772014-10-10 19:01:34 -07001660String8 InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
1661 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1662 const char* targetType) {
1663 // If the window is paused then keep waiting.
1664 if (windowHandle->getInfo()->paused) {
1665 return String8::format("Waiting because the %s window is paused.", targetType);
1666 }
1667
1668 // If the window's connection is not registered then keep waiting.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brownffb49772014-10-10 19:01:34 -07001670 if (connectionIndex < 0) {
1671 return String8::format("Waiting because the %s window's input channel is not "
1672 "registered with the input dispatcher. The window may be in the process "
1673 "of being removed.", targetType);
1674 }
1675
1676 // If the connection is dead then keep waiting.
1677 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1678 if (connection->status != Connection::STATUS_NORMAL) {
1679 return String8::format("Waiting because the %s window's input connection is %s."
1680 "The window may be in the process of being removed.", targetType,
1681 connection->getStatusLabel());
1682 }
1683
1684 // If the connection is backed up then keep waiting.
1685 if (connection->inputPublisherBlocked) {
1686 return String8::format("Waiting because the %s window's input channel is full. "
1687 "Outbound queue length: %d. Wait queue length: %d.",
1688 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1689 }
1690
1691 // Ensure that the dispatch queues aren't too far backed up for this event.
1692 if (eventEntry->type == EventEntry::TYPE_KEY) {
1693 // If the event is a key event, then we must wait for all previous events to
1694 // complete before delivering it because previous events may have the
1695 // side-effect of transferring focus to a different window and we want to
1696 // ensure that the following keys are sent to the new window.
1697 //
1698 // Suppose the user touches a button in a window then immediately presses "A".
1699 // If the button causes a pop-up window to appear then we want to ensure that
1700 // the "A" key is delivered to the new pop-up window. This is because users
1701 // often anticipate pending UI changes when typing on a keyboard.
1702 // To obtain this behavior, we must serialize key events with respect to all
1703 // prior input events.
1704 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
1705 return String8::format("Waiting to send key event because the %s window has not "
1706 "finished processing all of the input events that were previously "
1707 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1708 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 }
Jeff Brownffb49772014-10-10 19:01:34 -07001710 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 // Touch events can always be sent to a window immediately because the user intended
1712 // to touch whatever was visible at the time. Even if focus changes or a new
1713 // window appears moments later, the touch event was meant to be delivered to
1714 // whatever window happened to be on screen at the time.
1715 //
1716 // Generic motion events, such as trackball or joystick events are a little trickier.
1717 // Like key events, generic motion events are delivered to the focused window.
1718 // Unlike key events, generic motion events don't tend to transfer focus to other
1719 // windows and it is not important for them to be serialized. So we prefer to deliver
1720 // generic motion events as soon as possible to improve efficiency and reduce lag
1721 // through batching.
1722 //
1723 // The one case where we pause input event delivery is when the wait queue is piling
1724 // up with lots of events because the application is not responding.
1725 // This condition ensures that ANRs are detected reliably.
1726 if (!connection->waitQueue.isEmpty()
1727 && currentTime >= connection->waitQueue.head->deliveryTime
1728 + STREAM_AHEAD_EVENT_TIMEOUT) {
Jeff Brownffb49772014-10-10 19:01:34 -07001729 return String8::format("Waiting to send non-key event because the %s window has not "
1730 "finished processing certain input events that were delivered to it over "
1731 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1732 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1733 connection->waitQueue.count(),
1734 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001735 }
1736 }
Jeff Brownffb49772014-10-10 19:01:34 -07001737 return String8::empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738}
1739
1740String8 InputDispatcher::getApplicationWindowLabelLocked(
1741 const sp<InputApplicationHandle>& applicationHandle,
1742 const sp<InputWindowHandle>& windowHandle) {
1743 if (applicationHandle != NULL) {
1744 if (windowHandle != NULL) {
1745 String8 label(applicationHandle->getName());
1746 label.append(" - ");
1747 label.append(windowHandle->getName());
1748 return label;
1749 } else {
1750 return applicationHandle->getName();
1751 }
1752 } else if (windowHandle != NULL) {
1753 return windowHandle->getName();
1754 } else {
1755 return String8("<unknown application or window>");
1756 }
1757}
1758
1759void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
1760 if (mFocusedWindowHandle != NULL) {
1761 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1762 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1763#if DEBUG_DISPATCH_CYCLE
1764 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.string());
1765#endif
1766 return;
1767 }
1768 }
1769
1770 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1771 switch (eventEntry->type) {
1772 case EventEntry::TYPE_MOTION: {
1773 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1774 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1775 return;
1776 }
1777
1778 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1779 eventType = USER_ACTIVITY_EVENT_TOUCH;
1780 }
1781 break;
1782 }
1783 case EventEntry::TYPE_KEY: {
1784 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1785 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1786 return;
1787 }
1788 eventType = USER_ACTIVITY_EVENT_BUTTON;
1789 break;
1790 }
1791 }
1792
1793 CommandEntry* commandEntry = postCommandLocked(
1794 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1795 commandEntry->eventTime = eventEntry->eventTime;
1796 commandEntry->userActivityEventType = eventType;
1797}
1798
1799void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1800 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1801#if DEBUG_DISPATCH_CYCLE
1802 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1803 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1804 "pointerIds=0x%x",
1805 connection->getInputChannelName(), inputTarget->flags,
1806 inputTarget->xOffset, inputTarget->yOffset,
1807 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1808#endif
1809
1810 // Skip this event if the connection status is not normal.
1811 // We don't want to enqueue additional outbound events if the connection is broken.
1812 if (connection->status != Connection::STATUS_NORMAL) {
1813#if DEBUG_DISPATCH_CYCLE
1814 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
1815 connection->getInputChannelName(), connection->getStatusLabel());
1816#endif
1817 return;
1818 }
1819
1820 // Split a motion event if needed.
1821 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1822 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1823
1824 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1825 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1826 MotionEntry* splitMotionEntry = splitMotionEvent(
1827 originalMotionEntry, inputTarget->pointerIds);
1828 if (!splitMotionEntry) {
1829 return; // split event was dropped
1830 }
1831#if DEBUG_FOCUS
1832 ALOGD("channel '%s' ~ Split motion event.",
1833 connection->getInputChannelName());
1834 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1835#endif
1836 enqueueDispatchEntriesLocked(currentTime, connection,
1837 splitMotionEntry, inputTarget);
1838 splitMotionEntry->release();
1839 return;
1840 }
1841 }
1842
1843 // Not splitting. Enqueue dispatch entries for the event as is.
1844 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1845}
1846
1847void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1848 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1849 bool wasEmpty = connection->outboundQueue.isEmpty();
1850
1851 // Enqueue dispatch entries for the requested modes.
1852 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1853 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1854 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1855 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1856 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1857 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1858 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1859 InputTarget::FLAG_DISPATCH_AS_IS);
1860 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1861 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1862 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1863 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1864
1865 // If the outbound queue was previously empty, start the dispatch cycle going.
1866 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1867 startDispatchCycleLocked(currentTime, connection);
1868 }
1869}
1870
1871void InputDispatcher::enqueueDispatchEntryLocked(
1872 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1873 int32_t dispatchMode) {
1874 int32_t inputTargetFlags = inputTarget->flags;
1875 if (!(inputTargetFlags & dispatchMode)) {
1876 return;
1877 }
1878 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1879
1880 // This is a new event.
1881 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1882 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1883 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1884 inputTarget->scaleFactor);
1885
1886 // Apply target flags and update the connection's input state.
1887 switch (eventEntry->type) {
1888 case EventEntry::TYPE_KEY: {
1889 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1890 dispatchEntry->resolvedAction = keyEntry->action;
1891 dispatchEntry->resolvedFlags = keyEntry->flags;
1892
1893 if (!connection->inputState.trackKey(keyEntry,
1894 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1895#if DEBUG_DISPATCH_CYCLE
1896 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
1897 connection->getInputChannelName());
1898#endif
1899 delete dispatchEntry;
1900 return; // skip the inconsistent event
1901 }
1902 break;
1903 }
1904
1905 case EventEntry::TYPE_MOTION: {
1906 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1907 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1908 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1909 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1910 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1911 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1912 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1913 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1914 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1915 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1916 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1917 } else {
1918 dispatchEntry->resolvedAction = motionEntry->action;
1919 }
1920 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1921 && !connection->inputState.isHovering(
1922 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
1923#if DEBUG_DISPATCH_CYCLE
1924 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
1925 connection->getInputChannelName());
1926#endif
1927 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1928 }
1929
1930 dispatchEntry->resolvedFlags = motionEntry->flags;
1931 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1932 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1933 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001934 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
1935 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937
1938 if (!connection->inputState.trackMotion(motionEntry,
1939 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1940#if DEBUG_DISPATCH_CYCLE
1941 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
1942 connection->getInputChannelName());
1943#endif
1944 delete dispatchEntry;
1945 return; // skip the inconsistent event
1946 }
1947 break;
1948 }
1949 }
1950
1951 // Remember that we are waiting for this dispatch to complete.
1952 if (dispatchEntry->hasForegroundTarget()) {
1953 incrementPendingForegroundDispatchesLocked(eventEntry);
1954 }
1955
1956 // Enqueue the dispatch entry.
1957 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1958 traceOutboundQueueLengthLocked(connection);
1959}
1960
1961void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
1962 const sp<Connection>& connection) {
1963#if DEBUG_DISPATCH_CYCLE
1964 ALOGD("channel '%s' ~ startDispatchCycle",
1965 connection->getInputChannelName());
1966#endif
1967
1968 while (connection->status == Connection::STATUS_NORMAL
1969 && !connection->outboundQueue.isEmpty()) {
1970 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
1971 dispatchEntry->deliveryTime = currentTime;
1972
1973 // Publish the event.
1974 status_t status;
1975 EventEntry* eventEntry = dispatchEntry->eventEntry;
1976 switch (eventEntry->type) {
1977 case EventEntry::TYPE_KEY: {
1978 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1979
1980 // Publish the key event.
1981 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
1982 keyEntry->deviceId, keyEntry->source,
1983 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1984 keyEntry->keyCode, keyEntry->scanCode,
1985 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1986 keyEntry->eventTime);
1987 break;
1988 }
1989
1990 case EventEntry::TYPE_MOTION: {
1991 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1992
1993 PointerCoords scaledCoords[MAX_POINTERS];
1994 const PointerCoords* usingCoords = motionEntry->pointerCoords;
1995
1996 // Set the X and Y offset depending on the input source.
1997 float xOffset, yOffset, scaleFactor;
1998 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
1999 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
2000 scaleFactor = dispatchEntry->scaleFactor;
2001 xOffset = dispatchEntry->xOffset * scaleFactor;
2002 yOffset = dispatchEntry->yOffset * scaleFactor;
2003 if (scaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002004 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 scaledCoords[i] = motionEntry->pointerCoords[i];
2006 scaledCoords[i].scale(scaleFactor);
2007 }
2008 usingCoords = scaledCoords;
2009 }
2010 } else {
2011 xOffset = 0.0f;
2012 yOffset = 0.0f;
2013 scaleFactor = 1.0f;
2014
2015 // We don't want the dispatch target to know.
2016 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002017 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002018 scaledCoords[i].clear();
2019 }
2020 usingCoords = scaledCoords;
2021 }
2022 }
2023
2024 // Publish the motion event.
2025 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002026 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002027 dispatchEntry->resolvedAction, motionEntry->actionButton,
2028 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2029 motionEntry->metaState, motionEntry->buttonState,
2030 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031 motionEntry->downTime, motionEntry->eventTime,
2032 motionEntry->pointerCount, motionEntry->pointerProperties,
2033 usingCoords);
2034 break;
2035 }
2036
2037 default:
2038 ALOG_ASSERT(false);
2039 return;
2040 }
2041
2042 // Check the result.
2043 if (status) {
2044 if (status == WOULD_BLOCK) {
2045 if (connection->waitQueue.isEmpty()) {
2046 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2047 "This is unexpected because the wait queue is empty, so the pipe "
2048 "should be empty and we shouldn't have any problems writing an "
2049 "event to it, status=%d", connection->getInputChannelName(), status);
2050 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2051 } else {
2052 // Pipe is full and we are waiting for the app to finish process some events
2053 // before sending more events to it.
2054#if DEBUG_DISPATCH_CYCLE
2055 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2056 "waiting for the application to catch up",
2057 connection->getInputChannelName());
2058#endif
2059 connection->inputPublisherBlocked = true;
2060 }
2061 } else {
2062 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
2063 "status=%d", connection->getInputChannelName(), status);
2064 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2065 }
2066 return;
2067 }
2068
2069 // Re-enqueue the event on the wait queue.
2070 connection->outboundQueue.dequeue(dispatchEntry);
2071 traceOutboundQueueLengthLocked(connection);
2072 connection->waitQueue.enqueueAtTail(dispatchEntry);
2073 traceWaitQueueLengthLocked(connection);
2074 }
2075}
2076
2077void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2078 const sp<Connection>& connection, uint32_t seq, bool handled) {
2079#if DEBUG_DISPATCH_CYCLE
2080 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
2081 connection->getInputChannelName(), seq, toString(handled));
2082#endif
2083
2084 connection->inputPublisherBlocked = false;
2085
2086 if (connection->status == Connection::STATUS_BROKEN
2087 || connection->status == Connection::STATUS_ZOMBIE) {
2088 return;
2089 }
2090
2091 // Notify other system components and prepare to start the next dispatch cycle.
2092 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2093}
2094
2095void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2096 const sp<Connection>& connection, bool notify) {
2097#if DEBUG_DISPATCH_CYCLE
2098 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
2099 connection->getInputChannelName(), toString(notify));
2100#endif
2101
2102 // Clear the dispatch queues.
2103 drainDispatchQueueLocked(&connection->outboundQueue);
2104 traceOutboundQueueLengthLocked(connection);
2105 drainDispatchQueueLocked(&connection->waitQueue);
2106 traceWaitQueueLengthLocked(connection);
2107
2108 // The connection appears to be unrecoverably broken.
2109 // Ignore already broken or zombie connections.
2110 if (connection->status == Connection::STATUS_NORMAL) {
2111 connection->status = Connection::STATUS_BROKEN;
2112
2113 if (notify) {
2114 // Notify other system components.
2115 onDispatchCycleBrokenLocked(currentTime, connection);
2116 }
2117 }
2118}
2119
2120void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2121 while (!queue->isEmpty()) {
2122 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2123 releaseDispatchEntryLocked(dispatchEntry);
2124 }
2125}
2126
2127void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2128 if (dispatchEntry->hasForegroundTarget()) {
2129 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2130 }
2131 delete dispatchEntry;
2132}
2133
2134int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2135 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2136
2137 { // acquire lock
2138 AutoMutex _l(d->mLock);
2139
2140 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2141 if (connectionIndex < 0) {
2142 ALOGE("Received spurious receive callback for unknown input channel. "
2143 "fd=%d, events=0x%x", fd, events);
2144 return 0; // remove the callback
2145 }
2146
2147 bool notify;
2148 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2149 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2150 if (!(events & ALOOPER_EVENT_INPUT)) {
2151 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
2152 "events=0x%x", connection->getInputChannelName(), events);
2153 return 1;
2154 }
2155
2156 nsecs_t currentTime = now();
2157 bool gotOne = false;
2158 status_t status;
2159 for (;;) {
2160 uint32_t seq;
2161 bool handled;
2162 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2163 if (status) {
2164 break;
2165 }
2166 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2167 gotOne = true;
2168 }
2169 if (gotOne) {
2170 d->runCommandsLockedInterruptible();
2171 if (status == WOULD_BLOCK) {
2172 return 1;
2173 }
2174 }
2175
2176 notify = status != DEAD_OBJECT || !connection->monitor;
2177 if (notify) {
2178 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
2179 connection->getInputChannelName(), status);
2180 }
2181 } else {
2182 // Monitor channels are never explicitly unregistered.
2183 // We do it automatically when the remote endpoint is closed so don't warn
2184 // about them.
2185 notify = !connection->monitor;
2186 if (notify) {
2187 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
2188 "events=0x%x", connection->getInputChannelName(), events);
2189 }
2190 }
2191
2192 // Unregister the channel.
2193 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2194 return 0; // remove the callback
2195 } // release lock
2196}
2197
2198void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2199 const CancelationOptions& options) {
2200 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2201 synthesizeCancelationEventsForConnectionLocked(
2202 mConnectionsByFd.valueAt(i), options);
2203 }
2204}
2205
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002206void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2207 const CancelationOptions& options) {
2208 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2209 synthesizeCancelationEventsForInputChannelLocked(mMonitoringChannels[i], options);
2210 }
2211}
2212
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2214 const sp<InputChannel>& channel, const CancelationOptions& options) {
2215 ssize_t index = getConnectionIndexLocked(channel);
2216 if (index >= 0) {
2217 synthesizeCancelationEventsForConnectionLocked(
2218 mConnectionsByFd.valueAt(index), options);
2219 }
2220}
2221
2222void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2223 const sp<Connection>& connection, const CancelationOptions& options) {
2224 if (connection->status == Connection::STATUS_BROKEN) {
2225 return;
2226 }
2227
2228 nsecs_t currentTime = now();
2229
2230 Vector<EventEntry*> cancelationEvents;
2231 connection->inputState.synthesizeCancelationEvents(currentTime,
2232 cancelationEvents, options);
2233
2234 if (!cancelationEvents.isEmpty()) {
2235#if DEBUG_OUTBOUND_EVENT_DETAILS
2236 ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
2237 "with reality: %s, mode=%d.",
2238 connection->getInputChannelName(), cancelationEvents.size(),
2239 options.reason, options.mode);
2240#endif
2241 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2242 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2243 switch (cancelationEventEntry->type) {
2244 case EventEntry::TYPE_KEY:
2245 logOutboundKeyDetailsLocked("cancel - ",
2246 static_cast<KeyEntry*>(cancelationEventEntry));
2247 break;
2248 case EventEntry::TYPE_MOTION:
2249 logOutboundMotionDetailsLocked("cancel - ",
2250 static_cast<MotionEntry*>(cancelationEventEntry));
2251 break;
2252 }
2253
2254 InputTarget target;
2255 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2256 if (windowHandle != NULL) {
2257 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2258 target.xOffset = -windowInfo->frameLeft;
2259 target.yOffset = -windowInfo->frameTop;
2260 target.scaleFactor = windowInfo->scaleFactor;
2261 } else {
2262 target.xOffset = 0;
2263 target.yOffset = 0;
2264 target.scaleFactor = 1.0f;
2265 }
2266 target.inputChannel = connection->inputChannel;
2267 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2268
2269 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2270 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2271
2272 cancelationEventEntry->release();
2273 }
2274
2275 startDispatchCycleLocked(currentTime, connection);
2276 }
2277}
2278
2279InputDispatcher::MotionEntry*
2280InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2281 ALOG_ASSERT(pointerIds.value != 0);
2282
2283 uint32_t splitPointerIndexMap[MAX_POINTERS];
2284 PointerProperties splitPointerProperties[MAX_POINTERS];
2285 PointerCoords splitPointerCoords[MAX_POINTERS];
2286
2287 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2288 uint32_t splitPointerCount = 0;
2289
2290 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2291 originalPointerIndex++) {
2292 const PointerProperties& pointerProperties =
2293 originalMotionEntry->pointerProperties[originalPointerIndex];
2294 uint32_t pointerId = uint32_t(pointerProperties.id);
2295 if (pointerIds.hasBit(pointerId)) {
2296 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2297 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2298 splitPointerCoords[splitPointerCount].copyFrom(
2299 originalMotionEntry->pointerCoords[originalPointerIndex]);
2300 splitPointerCount += 1;
2301 }
2302 }
2303
2304 if (splitPointerCount != pointerIds.count()) {
2305 // This is bad. We are missing some of the pointers that we expected to deliver.
2306 // Most likely this indicates that we received an ACTION_MOVE events that has
2307 // different pointer ids than we expected based on the previous ACTION_DOWN
2308 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2309 // in this way.
2310 ALOGW("Dropping split motion event because the pointer count is %d but "
2311 "we expected there to be %d pointers. This probably means we received "
2312 "a broken sequence of pointer ids from the input device.",
2313 splitPointerCount, pointerIds.count());
2314 return NULL;
2315 }
2316
2317 int32_t action = originalMotionEntry->action;
2318 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2319 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2320 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2321 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2322 const PointerProperties& pointerProperties =
2323 originalMotionEntry->pointerProperties[originalPointerIndex];
2324 uint32_t pointerId = uint32_t(pointerProperties.id);
2325 if (pointerIds.hasBit(pointerId)) {
2326 if (pointerIds.count() == 1) {
2327 // The first/last pointer went down/up.
2328 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2329 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2330 } else {
2331 // A secondary pointer went down/up.
2332 uint32_t splitPointerIndex = 0;
2333 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2334 splitPointerIndex += 1;
2335 }
2336 action = maskedAction | (splitPointerIndex
2337 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2338 }
2339 } else {
2340 // An unrelated pointer changed.
2341 action = AMOTION_EVENT_ACTION_MOVE;
2342 }
2343 }
2344
2345 MotionEntry* splitMotionEntry = new MotionEntry(
2346 originalMotionEntry->eventTime,
2347 originalMotionEntry->deviceId,
2348 originalMotionEntry->source,
2349 originalMotionEntry->policyFlags,
2350 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002351 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 originalMotionEntry->flags,
2353 originalMotionEntry->metaState,
2354 originalMotionEntry->buttonState,
2355 originalMotionEntry->edgeFlags,
2356 originalMotionEntry->xPrecision,
2357 originalMotionEntry->yPrecision,
2358 originalMotionEntry->downTime,
2359 originalMotionEntry->displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002360 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361
2362 if (originalMotionEntry->injectionState) {
2363 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2364 splitMotionEntry->injectionState->refCount += 1;
2365 }
2366
2367 return splitMotionEntry;
2368}
2369
2370void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2371#if DEBUG_INBOUND_EVENT_DETAILS
2372 ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
2373#endif
2374
2375 bool needWake;
2376 { // acquire lock
2377 AutoMutex _l(mLock);
2378
2379 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2380 needWake = enqueueInboundEventLocked(newEntry);
2381 } // release lock
2382
2383 if (needWake) {
2384 mLooper->wake();
2385 }
2386}
2387
2388void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2389#if DEBUG_INBOUND_EVENT_DETAILS
2390 ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
2391 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
2392 args->eventTime, args->deviceId, args->source, args->policyFlags,
2393 args->action, args->flags, args->keyCode, args->scanCode,
2394 args->metaState, args->downTime);
2395#endif
2396 if (!validateKeyEvent(args->action)) {
2397 return;
2398 }
2399
2400 uint32_t policyFlags = args->policyFlags;
2401 int32_t flags = args->flags;
2402 int32_t metaState = args->metaState;
2403 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2404 policyFlags |= POLICY_FLAG_VIRTUAL;
2405 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407 if (policyFlags & POLICY_FLAG_FUNCTION) {
2408 metaState |= AMETA_FUNCTION_ON;
2409 }
2410
2411 policyFlags |= POLICY_FLAG_TRUSTED;
2412
Michael Wright78f24442014-08-06 15:55:28 -07002413 int32_t keyCode = args->keyCode;
2414 if (metaState & AMETA_META_ON && args->action == AKEY_EVENT_ACTION_DOWN) {
2415 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2416 if (keyCode == AKEYCODE_DEL) {
2417 newKeyCode = AKEYCODE_BACK;
2418 } else if (keyCode == AKEYCODE_ENTER) {
2419 newKeyCode = AKEYCODE_HOME;
2420 }
2421 if (newKeyCode != AKEYCODE_UNKNOWN) {
2422 AutoMutex _l(mLock);
2423 struct KeyReplacement replacement = {keyCode, args->deviceId};
2424 mReplacedKeys.add(replacement, newKeyCode);
2425 keyCode = newKeyCode;
Evan Roskye71f0552017-03-21 18:12:36 -07002426 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
Michael Wright78f24442014-08-06 15:55:28 -07002427 }
2428 } else if (args->action == AKEY_EVENT_ACTION_UP) {
2429 // In order to maintain a consistent stream of up and down events, check to see if the key
2430 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2431 // even if the modifier was released between the down and the up events.
2432 AutoMutex _l(mLock);
2433 struct KeyReplacement replacement = {keyCode, args->deviceId};
2434 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2435 if (index >= 0) {
2436 keyCode = mReplacedKeys.valueAt(index);
2437 mReplacedKeys.removeItemsAt(index);
Evan Roskye71f0552017-03-21 18:12:36 -07002438 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
Michael Wright78f24442014-08-06 15:55:28 -07002439 }
2440 }
2441
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 KeyEvent event;
2443 event.initialize(args->deviceId, args->source, args->action,
Michael Wright78f24442014-08-06 15:55:28 -07002444 flags, keyCode, args->scanCode, metaState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445 args->downTime, args->eventTime);
2446
2447 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
2448
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 bool needWake;
2450 { // acquire lock
2451 mLock.lock();
2452
2453 if (shouldSendKeyToInputFilterLocked(args)) {
2454 mLock.unlock();
2455
2456 policyFlags |= POLICY_FLAG_FILTERED;
2457 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2458 return; // event was consumed by the filter
2459 }
2460
2461 mLock.lock();
2462 }
2463
2464 int32_t repeatCount = 0;
2465 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2466 args->deviceId, args->source, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002467 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 metaState, repeatCount, args->downTime);
2469
2470 needWake = enqueueInboundEventLocked(newEntry);
2471 mLock.unlock();
2472 } // release lock
2473
2474 if (needWake) {
2475 mLooper->wake();
2476 }
2477}
2478
2479bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2480 return mInputFilterEnabled;
2481}
2482
2483void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2484#if DEBUG_INBOUND_EVENT_DETAILS
2485 ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002486 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
2487 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 args->eventTime, args->deviceId, args->source, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002489 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2491 for (uint32_t i = 0; i < args->pointerCount; i++) {
2492 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2493 "x=%f, y=%f, pressure=%f, size=%f, "
2494 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2495 "orientation=%f",
2496 i, args->pointerProperties[i].id,
2497 args->pointerProperties[i].toolType,
2498 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2499 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2500 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2501 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2502 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2503 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2504 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2505 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2506 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2507 }
2508#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002509 if (!validateMotionEvent(args->action, args->actionButton,
2510 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 return;
2512 }
2513
2514 uint32_t policyFlags = args->policyFlags;
2515 policyFlags |= POLICY_FLAG_TRUSTED;
2516 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
2517
2518 bool needWake;
2519 { // acquire lock
2520 mLock.lock();
2521
2522 if (shouldSendMotionToInputFilterLocked(args)) {
2523 mLock.unlock();
2524
2525 MotionEvent event;
Michael Wright7b159c92015-05-14 14:48:03 +01002526 event.initialize(args->deviceId, args->source, args->action, args->actionButton,
2527 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2528 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529 args->downTime, args->eventTime,
2530 args->pointerCount, args->pointerProperties, args->pointerCoords);
2531
2532 policyFlags |= POLICY_FLAG_FILTERED;
2533 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2534 return; // event was consumed by the filter
2535 }
2536
2537 mLock.lock();
2538 }
2539
2540 // Just enqueue a new motion event.
2541 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2542 args->deviceId, args->source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002543 args->action, args->actionButton, args->flags,
2544 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2546 args->displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002547 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548
2549 needWake = enqueueInboundEventLocked(newEntry);
2550 mLock.unlock();
2551 } // release lock
2552
2553 if (needWake) {
2554 mLooper->wake();
2555 }
2556}
2557
2558bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2559 // TODO: support sending secondary display events to input filter
2560 return mInputFilterEnabled && isMainDisplay(args->displayId);
2561}
2562
2563void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2564#if DEBUG_INBOUND_EVENT_DETAILS
2565 ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x",
2566 args->eventTime, args->policyFlags,
2567 args->switchValues, args->switchMask);
2568#endif
2569
2570 uint32_t policyFlags = args->policyFlags;
2571 policyFlags |= POLICY_FLAG_TRUSTED;
2572 mPolicy->notifySwitch(args->eventTime,
2573 args->switchValues, args->switchMask, policyFlags);
2574}
2575
2576void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2577#if DEBUG_INBOUND_EVENT_DETAILS
2578 ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
2579 args->eventTime, args->deviceId);
2580#endif
2581
2582 bool needWake;
2583 { // acquire lock
2584 AutoMutex _l(mLock);
2585
2586 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2587 needWake = enqueueInboundEventLocked(newEntry);
2588 } // release lock
2589
2590 if (needWake) {
2591 mLooper->wake();
2592 }
2593}
2594
Jeff Brownf086ddb2014-02-11 14:28:48 -08002595int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2597 uint32_t policyFlags) {
2598#if DEBUG_INBOUND_EVENT_DETAILS
2599 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Tarandeep Singh58641502017-07-31 10:51:54 -07002600 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x, displayId=%d",
2601 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags,
2602 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603#endif
2604
2605 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2606
2607 policyFlags |= POLICY_FLAG_INJECTED;
2608 if (hasInjectionPermission(injectorPid, injectorUid)) {
2609 policyFlags |= POLICY_FLAG_TRUSTED;
2610 }
2611
2612 EventEntry* firstInjectedEntry;
2613 EventEntry* lastInjectedEntry;
2614 switch (event->getType()) {
2615 case AINPUT_EVENT_TYPE_KEY: {
2616 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2617 int32_t action = keyEvent->getAction();
2618 if (! validateKeyEvent(action)) {
2619 return INPUT_EVENT_INJECTION_FAILED;
2620 }
2621
2622 int32_t flags = keyEvent->getFlags();
2623 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2624 policyFlags |= POLICY_FLAG_VIRTUAL;
2625 }
2626
2627 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2628 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
2629 }
2630
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631 mLock.lock();
2632 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
2633 keyEvent->getDeviceId(), keyEvent->getSource(),
2634 policyFlags, action, flags,
2635 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
2636 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2637 lastInjectedEntry = firstInjectedEntry;
2638 break;
2639 }
2640
2641 case AINPUT_EVENT_TYPE_MOTION: {
2642 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 int32_t action = motionEvent->getAction();
2644 size_t pointerCount = motionEvent->getPointerCount();
2645 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002646 int32_t actionButton = motionEvent->getActionButton();
2647 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 return INPUT_EVENT_INJECTION_FAILED;
2649 }
2650
2651 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2652 nsecs_t eventTime = motionEvent->getEventTime();
2653 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
2654 }
2655
2656 mLock.lock();
2657 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2658 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2659 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
2660 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002661 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 motionEvent->getMetaState(), motionEvent->getButtonState(),
2663 motionEvent->getEdgeFlags(),
2664 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2665 motionEvent->getDownTime(), displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002666 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2667 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668 lastInjectedEntry = firstInjectedEntry;
2669 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2670 sampleEventTimes += 1;
2671 samplePointerCoords += pointerCount;
2672 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2673 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002674 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675 motionEvent->getMetaState(), motionEvent->getButtonState(),
2676 motionEvent->getEdgeFlags(),
2677 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2678 motionEvent->getDownTime(), displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002679 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2680 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 lastInjectedEntry->next = nextInjectedEntry;
2682 lastInjectedEntry = nextInjectedEntry;
2683 }
2684 break;
2685 }
2686
2687 default:
2688 ALOGW("Cannot inject event of type %d", event->getType());
2689 return INPUT_EVENT_INJECTION_FAILED;
2690 }
2691
2692 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2693 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2694 injectionState->injectionIsAsync = true;
2695 }
2696
2697 injectionState->refCount += 1;
2698 lastInjectedEntry->injectionState = injectionState;
2699
2700 bool needWake = false;
2701 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2702 EventEntry* nextEntry = entry->next;
2703 needWake |= enqueueInboundEventLocked(entry);
2704 entry = nextEntry;
2705 }
2706
2707 mLock.unlock();
2708
2709 if (needWake) {
2710 mLooper->wake();
2711 }
2712
2713 int32_t injectionResult;
2714 { // acquire lock
2715 AutoMutex _l(mLock);
2716
2717 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2718 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2719 } else {
2720 for (;;) {
2721 injectionResult = injectionState->injectionResult;
2722 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2723 break;
2724 }
2725
2726 nsecs_t remainingTimeout = endTime - now();
2727 if (remainingTimeout <= 0) {
2728#if DEBUG_INJECTION
2729 ALOGD("injectInputEvent - Timed out waiting for injection result "
2730 "to become available.");
2731#endif
2732 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2733 break;
2734 }
2735
2736 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2737 }
2738
2739 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2740 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2741 while (injectionState->pendingForegroundDispatches != 0) {
2742#if DEBUG_INJECTION
2743 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2744 injectionState->pendingForegroundDispatches);
2745#endif
2746 nsecs_t remainingTimeout = endTime - now();
2747 if (remainingTimeout <= 0) {
2748#if DEBUG_INJECTION
2749 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2750 "dispatches to finish.");
2751#endif
2752 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2753 break;
2754 }
2755
2756 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2757 }
2758 }
2759 }
2760
2761 injectionState->release();
2762 } // release lock
2763
2764#if DEBUG_INJECTION
2765 ALOGD("injectInputEvent - Finished with result %d. "
2766 "injectorPid=%d, injectorUid=%d",
2767 injectionResult, injectorPid, injectorUid);
2768#endif
2769
2770 return injectionResult;
2771}
2772
2773bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2774 return injectorUid == 0
2775 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2776}
2777
2778void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2779 InjectionState* injectionState = entry->injectionState;
2780 if (injectionState) {
2781#if DEBUG_INJECTION
2782 ALOGD("Setting input event injection result to %d. "
2783 "injectorPid=%d, injectorUid=%d",
2784 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2785#endif
2786
2787 if (injectionState->injectionIsAsync
2788 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2789 // Log the outcome since the injector did not wait for the injection result.
2790 switch (injectionResult) {
2791 case INPUT_EVENT_INJECTION_SUCCEEDED:
2792 ALOGV("Asynchronous input event injection succeeded.");
2793 break;
2794 case INPUT_EVENT_INJECTION_FAILED:
2795 ALOGW("Asynchronous input event injection failed.");
2796 break;
2797 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2798 ALOGW("Asynchronous input event injection permission denied.");
2799 break;
2800 case INPUT_EVENT_INJECTION_TIMED_OUT:
2801 ALOGW("Asynchronous input event injection timed out.");
2802 break;
2803 }
2804 }
2805
2806 injectionState->injectionResult = injectionResult;
2807 mInjectionResultAvailableCondition.broadcast();
2808 }
2809}
2810
2811void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2812 InjectionState* injectionState = entry->injectionState;
2813 if (injectionState) {
2814 injectionState->pendingForegroundDispatches += 1;
2815 }
2816}
2817
2818void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2819 InjectionState* injectionState = entry->injectionState;
2820 if (injectionState) {
2821 injectionState->pendingForegroundDispatches -= 1;
2822
2823 if (injectionState->pendingForegroundDispatches == 0) {
2824 mInjectionSyncFinishedCondition.broadcast();
2825 }
2826 }
2827}
2828
2829sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2830 const sp<InputChannel>& inputChannel) const {
2831 size_t numWindows = mWindowHandles.size();
2832 for (size_t i = 0; i < numWindows; i++) {
2833 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2834 if (windowHandle->getInputChannel() == inputChannel) {
2835 return windowHandle;
2836 }
2837 }
2838 return NULL;
2839}
2840
2841bool InputDispatcher::hasWindowHandleLocked(
2842 const sp<InputWindowHandle>& windowHandle) const {
2843 size_t numWindows = mWindowHandles.size();
2844 for (size_t i = 0; i < numWindows; i++) {
2845 if (mWindowHandles.itemAt(i) == windowHandle) {
2846 return true;
2847 }
2848 }
2849 return false;
2850}
2851
2852void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
2853#if DEBUG_FOCUS
2854 ALOGD("setInputWindows");
2855#endif
2856 { // acquire lock
2857 AutoMutex _l(mLock);
2858
2859 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
2860 mWindowHandles = inputWindowHandles;
2861
2862 sp<InputWindowHandle> newFocusedWindowHandle;
2863 bool foundHoveredWindow = false;
2864 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2865 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2866 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
2867 mWindowHandles.removeAt(i--);
2868 continue;
2869 }
2870 if (windowHandle->getInfo()->hasFocus) {
2871 newFocusedWindowHandle = windowHandle;
2872 }
2873 if (windowHandle == mLastHoverWindowHandle) {
2874 foundHoveredWindow = true;
2875 }
2876 }
2877
2878 if (!foundHoveredWindow) {
2879 mLastHoverWindowHandle = NULL;
2880 }
2881
2882 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2883 if (mFocusedWindowHandle != NULL) {
2884#if DEBUG_FOCUS
2885 ALOGD("Focus left window: %s",
2886 mFocusedWindowHandle->getName().string());
2887#endif
2888 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2889 if (focusedInputChannel != NULL) {
2890 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2891 "focus left window");
2892 synthesizeCancelationEventsForInputChannelLocked(
2893 focusedInputChannel, options);
2894 }
2895 }
2896 if (newFocusedWindowHandle != NULL) {
2897#if DEBUG_FOCUS
2898 ALOGD("Focus entered window: %s",
2899 newFocusedWindowHandle->getName().string());
2900#endif
2901 }
2902 mFocusedWindowHandle = newFocusedWindowHandle;
2903 }
2904
Jeff Brownf086ddb2014-02-11 14:28:48 -08002905 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
2906 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
2907 for (size_t i = 0; i < state.windows.size(); i++) {
2908 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
2909 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910#if DEBUG_FOCUS
Jeff Brownf086ddb2014-02-11 14:28:48 -08002911 ALOGD("Touched window was removed: %s",
2912 touchedWindow.windowHandle->getName().string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002913#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08002914 sp<InputChannel> touchedInputChannel =
2915 touchedWindow.windowHandle->getInputChannel();
2916 if (touchedInputChannel != NULL) {
2917 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2918 "touched window was removed");
2919 synthesizeCancelationEventsForInputChannelLocked(
2920 touchedInputChannel, options);
2921 }
2922 state.windows.removeAt(i--);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924 }
2925 }
2926
2927 // Release information for windows that are no longer present.
2928 // This ensures that unused input channels are released promptly.
2929 // Otherwise, they might stick around until the window handle is destroyed
2930 // which might not happen until the next GC.
2931 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2932 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2933 if (!hasWindowHandleLocked(oldWindowHandle)) {
2934#if DEBUG_FOCUS
2935 ALOGD("Window went away: %s", oldWindowHandle->getName().string());
2936#endif
2937 oldWindowHandle->releaseInfo();
2938 }
2939 }
2940 } // release lock
2941
2942 // Wake up poll loop since it may need to make new input dispatching choices.
2943 mLooper->wake();
2944}
2945
2946void InputDispatcher::setFocusedApplication(
2947 const sp<InputApplicationHandle>& inputApplicationHandle) {
2948#if DEBUG_FOCUS
2949 ALOGD("setFocusedApplication");
2950#endif
2951 { // acquire lock
2952 AutoMutex _l(mLock);
2953
2954 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
2955 if (mFocusedApplicationHandle != inputApplicationHandle) {
2956 if (mFocusedApplicationHandle != NULL) {
2957 resetANRTimeoutsLocked();
2958 mFocusedApplicationHandle->releaseInfo();
2959 }
2960 mFocusedApplicationHandle = inputApplicationHandle;
2961 }
2962 } else if (mFocusedApplicationHandle != NULL) {
2963 resetANRTimeoutsLocked();
2964 mFocusedApplicationHandle->releaseInfo();
2965 mFocusedApplicationHandle.clear();
2966 }
2967
2968#if DEBUG_FOCUS
2969 //logDispatchStateLocked();
2970#endif
2971 } // release lock
2972
2973 // Wake up poll loop since it may need to make new input dispatching choices.
2974 mLooper->wake();
2975}
2976
2977void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
2978#if DEBUG_FOCUS
2979 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
2980#endif
2981
2982 bool changed;
2983 { // acquire lock
2984 AutoMutex _l(mLock);
2985
2986 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
2987 if (mDispatchFrozen && !frozen) {
2988 resetANRTimeoutsLocked();
2989 }
2990
2991 if (mDispatchEnabled && !enabled) {
2992 resetAndDropEverythingLocked("dispatcher is being disabled");
2993 }
2994
2995 mDispatchEnabled = enabled;
2996 mDispatchFrozen = frozen;
2997 changed = true;
2998 } else {
2999 changed = false;
3000 }
3001
3002#if DEBUG_FOCUS
3003 //logDispatchStateLocked();
3004#endif
3005 } // release lock
3006
3007 if (changed) {
3008 // Wake up poll loop since it may need to make new input dispatching choices.
3009 mLooper->wake();
3010 }
3011}
3012
3013void InputDispatcher::setInputFilterEnabled(bool enabled) {
3014#if DEBUG_FOCUS
3015 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3016#endif
3017
3018 { // acquire lock
3019 AutoMutex _l(mLock);
3020
3021 if (mInputFilterEnabled == enabled) {
3022 return;
3023 }
3024
3025 mInputFilterEnabled = enabled;
3026 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3027 } // release lock
3028
3029 // Wake up poll loop since there might be work to do to drop everything.
3030 mLooper->wake();
3031}
3032
3033bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3034 const sp<InputChannel>& toChannel) {
3035#if DEBUG_FOCUS
3036 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
3037 fromChannel->getName().string(), toChannel->getName().string());
3038#endif
3039 { // acquire lock
3040 AutoMutex _l(mLock);
3041
3042 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3043 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3044 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
3045#if DEBUG_FOCUS
3046 ALOGD("Cannot transfer focus because from or to window not found.");
3047#endif
3048 return false;
3049 }
3050 if (fromWindowHandle == toWindowHandle) {
3051#if DEBUG_FOCUS
3052 ALOGD("Trivial transfer to same window.");
3053#endif
3054 return true;
3055 }
3056 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3057#if DEBUG_FOCUS
3058 ALOGD("Cannot transfer focus because windows are on different displays.");
3059#endif
3060 return false;
3061 }
3062
3063 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003064 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3065 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3066 for (size_t i = 0; i < state.windows.size(); i++) {
3067 const TouchedWindow& touchedWindow = state.windows[i];
3068 if (touchedWindow.windowHandle == fromWindowHandle) {
3069 int32_t oldTargetFlags = touchedWindow.targetFlags;
3070 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003071
Jeff Brownf086ddb2014-02-11 14:28:48 -08003072 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073
Jeff Brownf086ddb2014-02-11 14:28:48 -08003074 int32_t newTargetFlags = oldTargetFlags
3075 & (InputTarget::FLAG_FOREGROUND
3076 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3077 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078
Jeff Brownf086ddb2014-02-11 14:28:48 -08003079 found = true;
3080 goto Found;
3081 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082 }
3083 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003084Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085
3086 if (! found) {
3087#if DEBUG_FOCUS
3088 ALOGD("Focus transfer failed because from window did not have focus.");
3089#endif
3090 return false;
3091 }
3092
3093 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3094 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3095 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3096 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3097 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3098
3099 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3100 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3101 "transferring touch focus from this window to another window");
3102 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3103 }
3104
3105#if DEBUG_FOCUS
3106 logDispatchStateLocked();
3107#endif
3108 } // release lock
3109
3110 // Wake up poll loop since it may need to make new input dispatching choices.
3111 mLooper->wake();
3112 return true;
3113}
3114
3115void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3116#if DEBUG_FOCUS
3117 ALOGD("Resetting and dropping all events (%s).", reason);
3118#endif
3119
3120 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3121 synthesizeCancelationEventsForAllConnectionsLocked(options);
3122
3123 resetKeyRepeatLocked();
3124 releasePendingEventLocked();
3125 drainInboundQueueLocked();
3126 resetANRTimeoutsLocked();
3127
Jeff Brownf086ddb2014-02-11 14:28:48 -08003128 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003130 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131}
3132
3133void InputDispatcher::logDispatchStateLocked() {
3134 String8 dump;
3135 dumpDispatchStateLocked(dump);
3136
3137 char* text = dump.lockBuffer(dump.size());
3138 char* start = text;
3139 while (*start != '\0') {
3140 char* end = strchr(start, '\n');
3141 if (*end == '\n') {
3142 *(end++) = '\0';
3143 }
3144 ALOGD("%s", start);
3145 start = end;
3146 }
3147}
3148
3149void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
3150 dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3151 dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
3152
3153 if (mFocusedApplicationHandle != NULL) {
3154 dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
3155 mFocusedApplicationHandle->getName().string(),
3156 mFocusedApplicationHandle->getDispatchingTimeout(
3157 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3158 } else {
3159 dump.append(INDENT "FocusedApplication: <null>\n");
3160 }
3161 dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
3162 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
3163
Jeff Brownf086ddb2014-02-11 14:28:48 -08003164 if (!mTouchStatesByDisplay.isEmpty()) {
3165 dump.appendFormat(INDENT "TouchStatesByDisplay:\n");
3166 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3167 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
3168 dump.appendFormat(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
3169 state.displayId, toString(state.down), toString(state.split),
3170 state.deviceId, state.source);
3171 if (!state.windows.isEmpty()) {
3172 dump.append(INDENT3 "Windows:\n");
3173 for (size_t i = 0; i < state.windows.size(); i++) {
3174 const TouchedWindow& touchedWindow = state.windows[i];
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003175 dump.appendFormat(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003176 i, touchedWindow.windowHandle->getName().string(),
3177 touchedWindow.pointerIds.value,
3178 touchedWindow.targetFlags);
3179 }
3180 } else {
3181 dump.append(INDENT3 "Windows: <none>\n");
3182 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 }
3184 } else {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003185 dump.append(INDENT "TouchStates: <no displays touched>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 }
3187
3188 if (!mWindowHandles.isEmpty()) {
3189 dump.append(INDENT "Windows:\n");
3190 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3191 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3192 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3193
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003194 dump.appendFormat(INDENT2 "%zu: name='%s', displayId=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3196 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3197 "frame=[%d,%d][%d,%d], scale=%f, "
3198 "touchableRegion=",
3199 i, windowInfo->name.string(), windowInfo->displayId,
3200 toString(windowInfo->paused),
3201 toString(windowInfo->hasFocus),
3202 toString(windowInfo->hasWallpaper),
3203 toString(windowInfo->visible),
3204 toString(windowInfo->canReceiveKeys),
3205 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3206 windowInfo->layer,
3207 windowInfo->frameLeft, windowInfo->frameTop,
3208 windowInfo->frameRight, windowInfo->frameBottom,
3209 windowInfo->scaleFactor);
3210 dumpRegion(dump, windowInfo->touchableRegion);
3211 dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3212 dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3213 windowInfo->ownerPid, windowInfo->ownerUid,
3214 windowInfo->dispatchingTimeout / 1000000.0);
3215 }
3216 } else {
3217 dump.append(INDENT "Windows: <none>\n");
3218 }
3219
3220 if (!mMonitoringChannels.isEmpty()) {
3221 dump.append(INDENT "MonitoringChannels:\n");
3222 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3223 const sp<InputChannel>& channel = mMonitoringChannels[i];
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003224 dump.appendFormat(INDENT2 "%zu: '%s'\n", i, channel->getName().string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 }
3226 } else {
3227 dump.append(INDENT "MonitoringChannels: <none>\n");
3228 }
3229
3230 nsecs_t currentTime = now();
3231
3232 // Dump recently dispatched or dropped events from oldest to newest.
3233 if (!mRecentQueue.isEmpty()) {
3234 dump.appendFormat(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
3235 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
3236 dump.append(INDENT2);
3237 entry->appendDescription(dump);
3238 dump.appendFormat(", age=%0.1fms\n",
3239 (currentTime - entry->eventTime) * 0.000001f);
3240 }
3241 } else {
3242 dump.append(INDENT "RecentQueue: <empty>\n");
3243 }
3244
3245 // Dump event currently being dispatched.
3246 if (mPendingEvent) {
3247 dump.append(INDENT "PendingEvent:\n");
3248 dump.append(INDENT2);
3249 mPendingEvent->appendDescription(dump);
3250 dump.appendFormat(", age=%0.1fms\n",
3251 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3252 } else {
3253 dump.append(INDENT "PendingEvent: <none>\n");
3254 }
3255
3256 // Dump inbound events from oldest to newest.
3257 if (!mInboundQueue.isEmpty()) {
3258 dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
3259 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
3260 dump.append(INDENT2);
3261 entry->appendDescription(dump);
3262 dump.appendFormat(", age=%0.1fms\n",
3263 (currentTime - entry->eventTime) * 0.000001f);
3264 }
3265 } else {
3266 dump.append(INDENT "InboundQueue: <empty>\n");
3267 }
3268
Michael Wright78f24442014-08-06 15:55:28 -07003269 if (!mReplacedKeys.isEmpty()) {
3270 dump.append(INDENT "ReplacedKeys:\n");
3271 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3272 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3273 int32_t newKeyCode = mReplacedKeys.valueAt(i);
3274 dump.appendFormat(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
3275 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3276 }
3277 } else {
3278 dump.append(INDENT "ReplacedKeys: <empty>\n");
3279 }
3280
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 if (!mConnectionsByFd.isEmpty()) {
3282 dump.append(INDENT "Connections:\n");
3283 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3284 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003285 dump.appendFormat(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
3287 i, connection->getInputChannelName(), connection->getWindowName(),
3288 connection->getStatusLabel(), toString(connection->monitor),
3289 toString(connection->inputPublisherBlocked));
3290
3291 if (!connection->outboundQueue.isEmpty()) {
3292 dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
3293 connection->outboundQueue.count());
3294 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3295 entry = entry->next) {
3296 dump.append(INDENT4);
3297 entry->eventEntry->appendDescription(dump);
3298 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
3299 entry->targetFlags, entry->resolvedAction,
3300 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3301 }
3302 } else {
3303 dump.append(INDENT3 "OutboundQueue: <empty>\n");
3304 }
3305
3306 if (!connection->waitQueue.isEmpty()) {
3307 dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
3308 connection->waitQueue.count());
3309 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3310 entry = entry->next) {
3311 dump.append(INDENT4);
3312 entry->eventEntry->appendDescription(dump);
3313 dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
3314 "age=%0.1fms, wait=%0.1fms\n",
3315 entry->targetFlags, entry->resolvedAction,
3316 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3317 (currentTime - entry->deliveryTime) * 0.000001f);
3318 }
3319 } else {
3320 dump.append(INDENT3 "WaitQueue: <empty>\n");
3321 }
3322 }
3323 } else {
3324 dump.append(INDENT "Connections: <none>\n");
3325 }
3326
3327 if (isAppSwitchPendingLocked()) {
3328 dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
3329 (mAppSwitchDueTime - now()) / 1000000.0);
3330 } else {
3331 dump.append(INDENT "AppSwitch: not pending\n");
3332 }
3333
3334 dump.append(INDENT "Configuration:\n");
3335 dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
3336 mConfig.keyRepeatDelay * 0.000001f);
3337 dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
3338 mConfig.keyRepeatTimeout * 0.000001f);
3339}
3340
3341status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3342 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
3343#if DEBUG_REGISTRATION
3344 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
3345 toString(monitor));
3346#endif
3347
3348 { // acquire lock
3349 AutoMutex _l(mLock);
3350
3351 if (getConnectionIndexLocked(inputChannel) >= 0) {
3352 ALOGW("Attempted to register already registered input channel '%s'",
3353 inputChannel->getName().string());
3354 return BAD_VALUE;
3355 }
3356
3357 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3358
3359 int fd = inputChannel->getFd();
3360 mConnectionsByFd.add(fd, connection);
3361
3362 if (monitor) {
3363 mMonitoringChannels.push(inputChannel);
3364 }
3365
3366 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3367 } // release lock
3368
3369 // Wake the looper because some connections have changed.
3370 mLooper->wake();
3371 return OK;
3372}
3373
3374status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3375#if DEBUG_REGISTRATION
3376 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
3377#endif
3378
3379 { // acquire lock
3380 AutoMutex _l(mLock);
3381
3382 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3383 if (status) {
3384 return status;
3385 }
3386 } // release lock
3387
3388 // Wake the poll loop because removing the connection may have changed the current
3389 // synchronization state.
3390 mLooper->wake();
3391 return OK;
3392}
3393
3394status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3395 bool notify) {
3396 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3397 if (connectionIndex < 0) {
3398 ALOGW("Attempted to unregister already unregistered input channel '%s'",
3399 inputChannel->getName().string());
3400 return BAD_VALUE;
3401 }
3402
3403 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3404 mConnectionsByFd.removeItemsAt(connectionIndex);
3405
3406 if (connection->monitor) {
3407 removeMonitorChannelLocked(inputChannel);
3408 }
3409
3410 mLooper->removeFd(inputChannel->getFd());
3411
3412 nsecs_t currentTime = now();
3413 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3414
3415 connection->status = Connection::STATUS_ZOMBIE;
3416 return OK;
3417}
3418
3419void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3420 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3421 if (mMonitoringChannels[i] == inputChannel) {
3422 mMonitoringChannels.removeAt(i);
3423 break;
3424 }
3425 }
3426}
3427
3428ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
3429 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3430 if (connectionIndex >= 0) {
3431 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3432 if (connection->inputChannel.get() == inputChannel.get()) {
3433 return connectionIndex;
3434 }
3435 }
3436
3437 return -1;
3438}
3439
3440void InputDispatcher::onDispatchCycleFinishedLocked(
3441 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3442 CommandEntry* commandEntry = postCommandLocked(
3443 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3444 commandEntry->connection = connection;
3445 commandEntry->eventTime = currentTime;
3446 commandEntry->seq = seq;
3447 commandEntry->handled = handled;
3448}
3449
3450void InputDispatcher::onDispatchCycleBrokenLocked(
3451 nsecs_t currentTime, const sp<Connection>& connection) {
3452 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
3453 connection->getInputChannelName());
3454
3455 CommandEntry* commandEntry = postCommandLocked(
3456 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3457 commandEntry->connection = connection;
3458}
3459
3460void InputDispatcher::onANRLocked(
3461 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3462 const sp<InputWindowHandle>& windowHandle,
3463 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3464 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3465 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3466 ALOGI("Application is not responding: %s. "
3467 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
3468 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
3469 dispatchLatency, waitDuration, reason);
3470
3471 // Capture a record of the InputDispatcher state at the time of the ANR.
3472 time_t t = time(NULL);
3473 struct tm tm;
3474 localtime_r(&t, &tm);
3475 char timestr[64];
3476 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3477 mLastANRState.clear();
3478 mLastANRState.append(INDENT "ANR:\n");
3479 mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
3480 mLastANRState.appendFormat(INDENT2 "Window: %s\n",
3481 getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
3482 mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3483 mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3484 mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
3485 dumpDispatchStateLocked(mLastANRState);
3486
3487 CommandEntry* commandEntry = postCommandLocked(
3488 & InputDispatcher::doNotifyANRLockedInterruptible);
3489 commandEntry->inputApplicationHandle = applicationHandle;
3490 commandEntry->inputWindowHandle = windowHandle;
3491 commandEntry->reason = reason;
3492}
3493
3494void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3495 CommandEntry* commandEntry) {
3496 mLock.unlock();
3497
3498 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3499
3500 mLock.lock();
3501}
3502
3503void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3504 CommandEntry* commandEntry) {
3505 sp<Connection> connection = commandEntry->connection;
3506
3507 if (connection->status != Connection::STATUS_ZOMBIE) {
3508 mLock.unlock();
3509
3510 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3511
3512 mLock.lock();
3513 }
3514}
3515
3516void InputDispatcher::doNotifyANRLockedInterruptible(
3517 CommandEntry* commandEntry) {
3518 mLock.unlock();
3519
3520 nsecs_t newTimeout = mPolicy->notifyANR(
3521 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3522 commandEntry->reason);
3523
3524 mLock.lock();
3525
3526 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3527 commandEntry->inputWindowHandle != NULL
3528 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
3529}
3530
3531void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3532 CommandEntry* commandEntry) {
3533 KeyEntry* entry = commandEntry->keyEntry;
3534
3535 KeyEvent event;
3536 initializeKeyEvent(&event, entry);
3537
3538 mLock.unlock();
3539
3540 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3541 &event, entry->policyFlags);
3542
3543 mLock.lock();
3544
3545 if (delay < 0) {
3546 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3547 } else if (!delay) {
3548 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3549 } else {
3550 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3551 entry->interceptKeyWakeupTime = now() + delay;
3552 }
3553 entry->release();
3554}
3555
3556void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3557 CommandEntry* commandEntry) {
3558 sp<Connection> connection = commandEntry->connection;
3559 nsecs_t finishTime = commandEntry->eventTime;
3560 uint32_t seq = commandEntry->seq;
3561 bool handled = commandEntry->handled;
3562
3563 // Handle post-event policy actions.
3564 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3565 if (dispatchEntry) {
3566 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3567 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
3568 String8 msg;
3569 msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
3570 connection->getWindowName(), eventDuration * 0.000001f);
3571 dispatchEntry->eventEntry->appendDescription(msg);
3572 ALOGI("%s", msg.string());
3573 }
3574
3575 bool restartEvent;
3576 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3577 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3578 restartEvent = afterKeyEventLockedInterruptible(connection,
3579 dispatchEntry, keyEntry, handled);
3580 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3581 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3582 restartEvent = afterMotionEventLockedInterruptible(connection,
3583 dispatchEntry, motionEntry, handled);
3584 } else {
3585 restartEvent = false;
3586 }
3587
3588 // Dequeue the event and start the next cycle.
3589 // Note that because the lock might have been released, it is possible that the
3590 // contents of the wait queue to have been drained, so we need to double-check
3591 // a few things.
3592 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3593 connection->waitQueue.dequeue(dispatchEntry);
3594 traceWaitQueueLengthLocked(connection);
3595 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3596 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3597 traceOutboundQueueLengthLocked(connection);
3598 } else {
3599 releaseDispatchEntryLocked(dispatchEntry);
3600 }
3601 }
3602
3603 // Start the next dispatch cycle for this connection.
3604 startDispatchCycleLocked(now(), connection);
3605 }
3606}
3607
3608bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3609 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3610 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3611 // Get the fallback key state.
3612 // Clear it out after dispatching the UP.
3613 int32_t originalKeyCode = keyEntry->keyCode;
3614 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3615 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3616 connection->inputState.removeFallbackKey(originalKeyCode);
3617 }
3618
3619 if (handled || !dispatchEntry->hasForegroundTarget()) {
3620 // If the application handles the original key for which we previously
3621 // generated a fallback or if the window is not a foreground window,
3622 // then cancel the associated fallback key, if any.
3623 if (fallbackKeyCode != -1) {
3624 // Dispatch the unhandled key to the policy with the cancel flag.
3625#if DEBUG_OUTBOUND_EVENT_DETAILS
3626 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3627 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3628 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3629 keyEntry->policyFlags);
3630#endif
3631 KeyEvent event;
3632 initializeKeyEvent(&event, keyEntry);
3633 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3634
3635 mLock.unlock();
3636
3637 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3638 &event, keyEntry->policyFlags, &event);
3639
3640 mLock.lock();
3641
3642 // Cancel the fallback key.
3643 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3644 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3645 "application handled the original non-fallback key "
3646 "or is no longer a foreground target, "
3647 "canceling previously dispatched fallback key");
3648 options.keyCode = fallbackKeyCode;
3649 synthesizeCancelationEventsForConnectionLocked(connection, options);
3650 }
3651 connection->inputState.removeFallbackKey(originalKeyCode);
3652 }
3653 } else {
3654 // If the application did not handle a non-fallback key, first check
3655 // that we are in a good state to perform unhandled key event processing
3656 // Then ask the policy what to do with it.
3657 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3658 && keyEntry->repeatCount == 0;
3659 if (fallbackKeyCode == -1 && !initialDown) {
3660#if DEBUG_OUTBOUND_EVENT_DETAILS
3661 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3662 "since this is not an initial down. "
3663 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3664 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3665 keyEntry->policyFlags);
3666#endif
3667 return false;
3668 }
3669
3670 // Dispatch the unhandled key to the policy.
3671#if DEBUG_OUTBOUND_EVENT_DETAILS
3672 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
3673 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3674 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3675 keyEntry->policyFlags);
3676#endif
3677 KeyEvent event;
3678 initializeKeyEvent(&event, keyEntry);
3679
3680 mLock.unlock();
3681
3682 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3683 &event, keyEntry->policyFlags, &event);
3684
3685 mLock.lock();
3686
3687 if (connection->status != Connection::STATUS_NORMAL) {
3688 connection->inputState.removeFallbackKey(originalKeyCode);
3689 return false;
3690 }
3691
3692 // Latch the fallback keycode for this key on an initial down.
3693 // The fallback keycode cannot change at any other point in the lifecycle.
3694 if (initialDown) {
3695 if (fallback) {
3696 fallbackKeyCode = event.getKeyCode();
3697 } else {
3698 fallbackKeyCode = AKEYCODE_UNKNOWN;
3699 }
3700 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3701 }
3702
3703 ALOG_ASSERT(fallbackKeyCode != -1);
3704
3705 // Cancel the fallback key if the policy decides not to send it anymore.
3706 // We will continue to dispatch the key to the policy but we will no
3707 // longer dispatch a fallback key to the application.
3708 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3709 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3710#if DEBUG_OUTBOUND_EVENT_DETAILS
3711 if (fallback) {
3712 ALOGD("Unhandled key event: Policy requested to send key %d"
3713 "as a fallback for %d, but on the DOWN it had requested "
3714 "to send %d instead. Fallback canceled.",
3715 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3716 } else {
3717 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
3718 "but on the DOWN it had requested to send %d. "
3719 "Fallback canceled.",
3720 originalKeyCode, fallbackKeyCode);
3721 }
3722#endif
3723
3724 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3725 "canceling fallback, policy no longer desires it");
3726 options.keyCode = fallbackKeyCode;
3727 synthesizeCancelationEventsForConnectionLocked(connection, options);
3728
3729 fallback = false;
3730 fallbackKeyCode = AKEYCODE_UNKNOWN;
3731 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3732 connection->inputState.setFallbackKey(originalKeyCode,
3733 fallbackKeyCode);
3734 }
3735 }
3736
3737#if DEBUG_OUTBOUND_EVENT_DETAILS
3738 {
3739 String8 msg;
3740 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3741 connection->inputState.getFallbackKeys();
3742 for (size_t i = 0; i < fallbackKeys.size(); i++) {
3743 msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
3744 fallbackKeys.valueAt(i));
3745 }
3746 ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
3747 fallbackKeys.size(), msg.string());
3748 }
3749#endif
3750
3751 if (fallback) {
3752 // Restart the dispatch cycle using the fallback key.
3753 keyEntry->eventTime = event.getEventTime();
3754 keyEntry->deviceId = event.getDeviceId();
3755 keyEntry->source = event.getSource();
3756 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3757 keyEntry->keyCode = fallbackKeyCode;
3758 keyEntry->scanCode = event.getScanCode();
3759 keyEntry->metaState = event.getMetaState();
3760 keyEntry->repeatCount = event.getRepeatCount();
3761 keyEntry->downTime = event.getDownTime();
3762 keyEntry->syntheticRepeat = false;
3763
3764#if DEBUG_OUTBOUND_EVENT_DETAILS
3765 ALOGD("Unhandled key event: Dispatching fallback key. "
3766 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3767 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3768#endif
3769 return true; // restart the event
3770 } else {
3771#if DEBUG_OUTBOUND_EVENT_DETAILS
3772 ALOGD("Unhandled key event: No fallback key.");
3773#endif
3774 }
3775 }
3776 }
3777 return false;
3778}
3779
3780bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3781 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3782 return false;
3783}
3784
3785void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3786 mLock.unlock();
3787
3788 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
3789
3790 mLock.lock();
3791}
3792
3793void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3794 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3795 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3796 entry->downTime, entry->eventTime);
3797}
3798
3799void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3800 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3801 // TODO Write some statistics about how long we spend waiting.
3802}
3803
3804void InputDispatcher::traceInboundQueueLengthLocked() {
3805 if (ATRACE_ENABLED()) {
3806 ATRACE_INT("iq", mInboundQueue.count());
3807 }
3808}
3809
3810void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3811 if (ATRACE_ENABLED()) {
3812 char counterName[40];
3813 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
3814 ATRACE_INT(counterName, connection->outboundQueue.count());
3815 }
3816}
3817
3818void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3819 if (ATRACE_ENABLED()) {
3820 char counterName[40];
3821 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
3822 ATRACE_INT(counterName, connection->waitQueue.count());
3823 }
3824}
3825
3826void InputDispatcher::dump(String8& dump) {
3827 AutoMutex _l(mLock);
3828
3829 dump.append("Input Dispatcher State:\n");
3830 dumpDispatchStateLocked(dump);
3831
3832 if (!mLastANRState.isEmpty()) {
3833 dump.append("\nInput Dispatcher State at time of last ANR:\n");
3834 dump.append(mLastANRState);
3835 }
3836}
3837
3838void InputDispatcher::monitor() {
3839 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3840 mLock.lock();
3841 mLooper->wake();
3842 mDispatcherIsAliveCondition.wait(mLock);
3843 mLock.unlock();
3844}
3845
3846
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847// --- InputDispatcher::InjectionState ---
3848
3849InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3850 refCount(1),
3851 injectorPid(injectorPid), injectorUid(injectorUid),
3852 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3853 pendingForegroundDispatches(0) {
3854}
3855
3856InputDispatcher::InjectionState::~InjectionState() {
3857}
3858
3859void InputDispatcher::InjectionState::release() {
3860 refCount -= 1;
3861 if (refCount == 0) {
3862 delete this;
3863 } else {
3864 ALOG_ASSERT(refCount > 0);
3865 }
3866}
3867
3868
3869// --- InputDispatcher::EventEntry ---
3870
3871InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3872 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3873 injectionState(NULL), dispatchInProgress(false) {
3874}
3875
3876InputDispatcher::EventEntry::~EventEntry() {
3877 releaseInjectionState();
3878}
3879
3880void InputDispatcher::EventEntry::release() {
3881 refCount -= 1;
3882 if (refCount == 0) {
3883 delete this;
3884 } else {
3885 ALOG_ASSERT(refCount > 0);
3886 }
3887}
3888
3889void InputDispatcher::EventEntry::releaseInjectionState() {
3890 if (injectionState) {
3891 injectionState->release();
3892 injectionState = NULL;
3893 }
3894}
3895
3896
3897// --- InputDispatcher::ConfigurationChangedEntry ---
3898
3899InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3900 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3901}
3902
3903InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3904}
3905
3906void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
3907 msg.append("ConfigurationChangedEvent(), policyFlags=0x%08x",
3908 policyFlags);
3909}
3910
3911
3912// --- InputDispatcher::DeviceResetEntry ---
3913
3914InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3915 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3916 deviceId(deviceId) {
3917}
3918
3919InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3920}
3921
3922void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
3923 msg.appendFormat("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
3924 deviceId, policyFlags);
3925}
3926
3927
3928// --- InputDispatcher::KeyEntry ---
3929
3930InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
3931 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
3932 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3933 int32_t repeatCount, nsecs_t downTime) :
3934 EventEntry(TYPE_KEY, eventTime, policyFlags),
3935 deviceId(deviceId), source(source), action(action), flags(flags),
3936 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3937 repeatCount(repeatCount), downTime(downTime),
3938 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3939 interceptKeyWakeupTime(0) {
3940}
3941
3942InputDispatcher::KeyEntry::~KeyEntry() {
3943}
3944
3945void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
3946 msg.appendFormat("KeyEvent(deviceId=%d, source=0x%08x, action=%d, "
3947 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
3948 "repeatCount=%d), policyFlags=0x%08x",
3949 deviceId, source, action, flags, keyCode, scanCode, metaState,
3950 repeatCount, policyFlags);
3951}
3952
3953void InputDispatcher::KeyEntry::recycle() {
3954 releaseInjectionState();
3955
3956 dispatchInProgress = false;
3957 syntheticRepeat = false;
3958 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
3959 interceptKeyWakeupTime = 0;
3960}
3961
3962
3963// --- InputDispatcher::MotionEntry ---
3964
Michael Wright7b159c92015-05-14 14:48:03 +01003965InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
3966 uint32_t source, uint32_t policyFlags, int32_t action, int32_t actionButton,
3967 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3968 float xPrecision, float yPrecision, nsecs_t downTime,
3969 int32_t displayId, uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08003970 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
3971 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 EventEntry(TYPE_MOTION, eventTime, policyFlags),
3973 eventTime(eventTime),
Michael Wright7b159c92015-05-14 14:48:03 +01003974 deviceId(deviceId), source(source), action(action), actionButton(actionButton),
3975 flags(flags), metaState(metaState), buttonState(buttonState),
3976 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
3978 for (uint32_t i = 0; i < pointerCount; i++) {
3979 this->pointerProperties[i].copyFrom(pointerProperties[i]);
3980 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08003981 if (xOffset || yOffset) {
3982 this->pointerCoords[i].applyOffset(xOffset, yOffset);
3983 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 }
3985}
3986
3987InputDispatcher::MotionEntry::~MotionEntry() {
3988}
3989
3990void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
Michael Wright7b159c92015-05-14 14:48:03 +01003991 msg.appendFormat("MotionEvent(deviceId=%d, source=0x%08x, action=%d, actionButton=0x%08x, "
3992 "flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
3993 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, displayId=%d, pointers=[",
3994 deviceId, source, action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003995 xPrecision, yPrecision, displayId);
3996 for (uint32_t i = 0; i < pointerCount; i++) {
3997 if (i) {
3998 msg.append(", ");
3999 }
4000 msg.appendFormat("%d: (%.1f, %.1f)", pointerProperties[i].id,
4001 pointerCoords[i].getX(), pointerCoords[i].getY());
4002 }
4003 msg.appendFormat("]), policyFlags=0x%08x", policyFlags);
4004}
4005
4006
4007// --- InputDispatcher::DispatchEntry ---
4008
4009volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4010
4011InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4012 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4013 seq(nextSeq()),
4014 eventEntry(eventEntry), targetFlags(targetFlags),
4015 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4016 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4017 eventEntry->refCount += 1;
4018}
4019
4020InputDispatcher::DispatchEntry::~DispatchEntry() {
4021 eventEntry->release();
4022}
4023
4024uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4025 // Sequence number 0 is reserved and will never be returned.
4026 uint32_t seq;
4027 do {
4028 seq = android_atomic_inc(&sNextSeqAtomic);
4029 } while (!seq);
4030 return seq;
4031}
4032
4033
4034// --- InputDispatcher::InputState ---
4035
4036InputDispatcher::InputState::InputState() {
4037}
4038
4039InputDispatcher::InputState::~InputState() {
4040}
4041
4042bool InputDispatcher::InputState::isNeutral() const {
4043 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4044}
4045
4046bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4047 int32_t displayId) const {
4048 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4049 const MotionMemento& memento = mMotionMementos.itemAt(i);
4050 if (memento.deviceId == deviceId
4051 && memento.source == source
4052 && memento.displayId == displayId
4053 && memento.hovering) {
4054 return true;
4055 }
4056 }
4057 return false;
4058}
4059
4060bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4061 int32_t action, int32_t flags) {
4062 switch (action) {
4063 case AKEY_EVENT_ACTION_UP: {
4064 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4065 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4066 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4067 mFallbackKeys.removeItemsAt(i);
4068 } else {
4069 i += 1;
4070 }
4071 }
4072 }
4073 ssize_t index = findKeyMemento(entry);
4074 if (index >= 0) {
4075 mKeyMementos.removeAt(index);
4076 return true;
4077 }
4078 /* FIXME: We can't just drop the key up event because that prevents creating
4079 * popup windows that are automatically shown when a key is held and then
4080 * dismissed when the key is released. The problem is that the popup will
4081 * not have received the original key down, so the key up will be considered
4082 * to be inconsistent with its observed state. We could perhaps handle this
4083 * by synthesizing a key down but that will cause other problems.
4084 *
4085 * So for now, allow inconsistent key up events to be dispatched.
4086 *
4087#if DEBUG_OUTBOUND_EVENT_DETAILS
4088 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4089 "keyCode=%d, scanCode=%d",
4090 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4091#endif
4092 return false;
4093 */
4094 return true;
4095 }
4096
4097 case AKEY_EVENT_ACTION_DOWN: {
4098 ssize_t index = findKeyMemento(entry);
4099 if (index >= 0) {
4100 mKeyMementos.removeAt(index);
4101 }
4102 addKeyMemento(entry, flags);
4103 return true;
4104 }
4105
4106 default:
4107 return true;
4108 }
4109}
4110
4111bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4112 int32_t action, int32_t flags) {
4113 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4114 switch (actionMasked) {
4115 case AMOTION_EVENT_ACTION_UP:
4116 case AMOTION_EVENT_ACTION_CANCEL: {
4117 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4118 if (index >= 0) {
4119 mMotionMementos.removeAt(index);
4120 return true;
4121 }
4122#if DEBUG_OUTBOUND_EVENT_DETAILS
4123 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4124 "actionMasked=%d",
4125 entry->deviceId, entry->source, actionMasked);
4126#endif
4127 return false;
4128 }
4129
4130 case AMOTION_EVENT_ACTION_DOWN: {
4131 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4132 if (index >= 0) {
4133 mMotionMementos.removeAt(index);
4134 }
4135 addMotionMemento(entry, flags, false /*hovering*/);
4136 return true;
4137 }
4138
4139 case AMOTION_EVENT_ACTION_POINTER_UP:
4140 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4141 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004142 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4143 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4144 // generate cancellation events for these since they're based in relative rather than
4145 // absolute units.
4146 return true;
4147 }
4148
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004150
4151 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4152 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4153 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4154 // other value and we need to track the motion so we can send cancellation events for
4155 // anything generating fallback events (e.g. DPad keys for joystick movements).
4156 if (index >= 0) {
4157 if (entry->pointerCoords[0].isEmpty()) {
4158 mMotionMementos.removeAt(index);
4159 } else {
4160 MotionMemento& memento = mMotionMementos.editItemAt(index);
4161 memento.setPointers(entry);
4162 }
4163 } else if (!entry->pointerCoords[0].isEmpty()) {
4164 addMotionMemento(entry, flags, false /*hovering*/);
4165 }
4166
4167 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4168 return true;
4169 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 if (index >= 0) {
4171 MotionMemento& memento = mMotionMementos.editItemAt(index);
4172 memento.setPointers(entry);
4173 return true;
4174 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175#if DEBUG_OUTBOUND_EVENT_DETAILS
4176 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
4177 "deviceId=%d, source=%08x, actionMasked=%d",
4178 entry->deviceId, entry->source, actionMasked);
4179#endif
4180 return false;
4181 }
4182
4183 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4184 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4185 if (index >= 0) {
4186 mMotionMementos.removeAt(index);
4187 return true;
4188 }
4189#if DEBUG_OUTBOUND_EVENT_DETAILS
4190 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4191 entry->deviceId, entry->source);
4192#endif
4193 return false;
4194 }
4195
4196 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4197 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4198 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4199 if (index >= 0) {
4200 mMotionMementos.removeAt(index);
4201 }
4202 addMotionMemento(entry, flags, true /*hovering*/);
4203 return true;
4204 }
4205
4206 default:
4207 return true;
4208 }
4209}
4210
4211ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4212 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4213 const KeyMemento& memento = mKeyMementos.itemAt(i);
4214 if (memento.deviceId == entry->deviceId
4215 && memento.source == entry->source
4216 && memento.keyCode == entry->keyCode
4217 && memento.scanCode == entry->scanCode) {
4218 return i;
4219 }
4220 }
4221 return -1;
4222}
4223
4224ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4225 bool hovering) const {
4226 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4227 const MotionMemento& memento = mMotionMementos.itemAt(i);
4228 if (memento.deviceId == entry->deviceId
4229 && memento.source == entry->source
4230 && memento.displayId == entry->displayId
4231 && memento.hovering == hovering) {
4232 return i;
4233 }
4234 }
4235 return -1;
4236}
4237
4238void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4239 mKeyMementos.push();
4240 KeyMemento& memento = mKeyMementos.editTop();
4241 memento.deviceId = entry->deviceId;
4242 memento.source = entry->source;
4243 memento.keyCode = entry->keyCode;
4244 memento.scanCode = entry->scanCode;
4245 memento.metaState = entry->metaState;
4246 memento.flags = flags;
4247 memento.downTime = entry->downTime;
4248 memento.policyFlags = entry->policyFlags;
4249}
4250
4251void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4252 int32_t flags, bool hovering) {
4253 mMotionMementos.push();
4254 MotionMemento& memento = mMotionMementos.editTop();
4255 memento.deviceId = entry->deviceId;
4256 memento.source = entry->source;
4257 memento.flags = flags;
4258 memento.xPrecision = entry->xPrecision;
4259 memento.yPrecision = entry->yPrecision;
4260 memento.downTime = entry->downTime;
4261 memento.displayId = entry->displayId;
4262 memento.setPointers(entry);
4263 memento.hovering = hovering;
4264 memento.policyFlags = entry->policyFlags;
4265}
4266
4267void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4268 pointerCount = entry->pointerCount;
4269 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4270 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4271 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4272 }
4273}
4274
4275void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4276 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4277 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4278 const KeyMemento& memento = mKeyMementos.itemAt(i);
4279 if (shouldCancelKey(memento, options)) {
4280 outEvents.push(new KeyEntry(currentTime,
4281 memento.deviceId, memento.source, memento.policyFlags,
4282 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4283 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4284 }
4285 }
4286
4287 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4288 const MotionMemento& memento = mMotionMementos.itemAt(i);
4289 if (shouldCancelMotion(memento, options)) {
4290 outEvents.push(new MotionEntry(currentTime,
4291 memento.deviceId, memento.source, memento.policyFlags,
4292 memento.hovering
4293 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4294 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004295 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 memento.xPrecision, memento.yPrecision, memento.downTime,
4297 memento.displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004298 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4299 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 }
4301 }
4302}
4303
4304void InputDispatcher::InputState::clear() {
4305 mKeyMementos.clear();
4306 mMotionMementos.clear();
4307 mFallbackKeys.clear();
4308}
4309
4310void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4311 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4312 const MotionMemento& memento = mMotionMementos.itemAt(i);
4313 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4314 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4315 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4316 if (memento.deviceId == otherMemento.deviceId
4317 && memento.source == otherMemento.source
4318 && memento.displayId == otherMemento.displayId) {
4319 other.mMotionMementos.removeAt(j);
4320 } else {
4321 j += 1;
4322 }
4323 }
4324 other.mMotionMementos.push(memento);
4325 }
4326 }
4327}
4328
4329int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4330 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4331 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4332}
4333
4334void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4335 int32_t fallbackKeyCode) {
4336 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4337 if (index >= 0) {
4338 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4339 } else {
4340 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4341 }
4342}
4343
4344void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4345 mFallbackKeys.removeItem(originalKeyCode);
4346}
4347
4348bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4349 const CancelationOptions& options) {
4350 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4351 return false;
4352 }
4353
4354 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4355 return false;
4356 }
4357
4358 switch (options.mode) {
4359 case CancelationOptions::CANCEL_ALL_EVENTS:
4360 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4361 return true;
4362 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4363 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4364 default:
4365 return false;
4366 }
4367}
4368
4369bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4370 const CancelationOptions& options) {
4371 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4372 return false;
4373 }
4374
4375 switch (options.mode) {
4376 case CancelationOptions::CANCEL_ALL_EVENTS:
4377 return true;
4378 case CancelationOptions::CANCEL_POINTER_EVENTS:
4379 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4380 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4381 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4382 default:
4383 return false;
4384 }
4385}
4386
4387
4388// --- InputDispatcher::Connection ---
4389
4390InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4391 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4392 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4393 monitor(monitor),
4394 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4395}
4396
4397InputDispatcher::Connection::~Connection() {
4398}
4399
4400const char* InputDispatcher::Connection::getWindowName() const {
4401 if (inputWindowHandle != NULL) {
4402 return inputWindowHandle->getName().string();
4403 }
4404 if (monitor) {
4405 return "monitor";
4406 }
4407 return "?";
4408}
4409
4410const char* InputDispatcher::Connection::getStatusLabel() const {
4411 switch (status) {
4412 case STATUS_NORMAL:
4413 return "NORMAL";
4414
4415 case STATUS_BROKEN:
4416 return "BROKEN";
4417
4418 case STATUS_ZOMBIE:
4419 return "ZOMBIE";
4420
4421 default:
4422 return "UNKNOWN";
4423 }
4424}
4425
4426InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4427 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4428 if (entry->seq == seq) {
4429 return entry;
4430 }
4431 }
4432 return NULL;
4433}
4434
4435
4436// --- InputDispatcher::CommandEntry ---
4437
4438InputDispatcher::CommandEntry::CommandEntry(Command command) :
4439 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4440 seq(0), handled(false) {
4441}
4442
4443InputDispatcher::CommandEntry::~CommandEntry() {
4444}
4445
4446
4447// --- InputDispatcher::TouchState ---
4448
4449InputDispatcher::TouchState::TouchState() :
4450 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
4451}
4452
4453InputDispatcher::TouchState::~TouchState() {
4454}
4455
4456void InputDispatcher::TouchState::reset() {
4457 down = false;
4458 split = false;
4459 deviceId = -1;
4460 source = 0;
4461 displayId = -1;
4462 windows.clear();
4463}
4464
4465void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4466 down = other.down;
4467 split = other.split;
4468 deviceId = other.deviceId;
4469 source = other.source;
4470 displayId = other.displayId;
4471 windows = other.windows;
4472}
4473
4474void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4475 int32_t targetFlags, BitSet32 pointerIds) {
4476 if (targetFlags & InputTarget::FLAG_SPLIT) {
4477 split = true;
4478 }
4479
4480 for (size_t i = 0; i < windows.size(); i++) {
4481 TouchedWindow& touchedWindow = windows.editItemAt(i);
4482 if (touchedWindow.windowHandle == windowHandle) {
4483 touchedWindow.targetFlags |= targetFlags;
4484 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4485 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4486 }
4487 touchedWindow.pointerIds.value |= pointerIds.value;
4488 return;
4489 }
4490 }
4491
4492 windows.push();
4493
4494 TouchedWindow& touchedWindow = windows.editTop();
4495 touchedWindow.windowHandle = windowHandle;
4496 touchedWindow.targetFlags = targetFlags;
4497 touchedWindow.pointerIds = pointerIds;
4498}
4499
4500void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4501 for (size_t i = 0; i < windows.size(); i++) {
4502 if (windows.itemAt(i).windowHandle == windowHandle) {
4503 windows.removeAt(i);
4504 return;
4505 }
4506 }
4507}
4508
4509void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4510 for (size_t i = 0 ; i < windows.size(); ) {
4511 TouchedWindow& window = windows.editItemAt(i);
4512 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4513 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4514 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4515 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4516 i += 1;
4517 } else {
4518 windows.removeAt(i);
4519 }
4520 }
4521}
4522
4523sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4524 for (size_t i = 0; i < windows.size(); i++) {
4525 const TouchedWindow& window = windows.itemAt(i);
4526 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4527 return window.windowHandle;
4528 }
4529 }
4530 return NULL;
4531}
4532
4533bool InputDispatcher::TouchState::isSlippery() const {
4534 // Must have exactly one foreground window.
4535 bool haveSlipperyForegroundWindow = false;
4536 for (size_t i = 0; i < windows.size(); i++) {
4537 const TouchedWindow& window = windows.itemAt(i);
4538 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4539 if (haveSlipperyForegroundWindow
4540 || !(window.windowHandle->getInfo()->layoutParamsFlags
4541 & InputWindowInfo::FLAG_SLIPPERY)) {
4542 return false;
4543 }
4544 haveSlipperyForegroundWindow = true;
4545 }
4546 }
4547 return haveSlipperyForegroundWindow;
4548}
4549
4550
4551// --- InputDispatcherThread ---
4552
4553InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4554 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4555}
4556
4557InputDispatcherThread::~InputDispatcherThread() {
4558}
4559
4560bool InputDispatcherThread::threadLoop() {
4561 mDispatcher->dispatchOnce();
4562 return true;
4563}
4564
4565} // namespace android