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