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