blob: 18744c3401090f27de832f2ccac2ddf349af12e0 [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
Michael Wright2b3c3302018-03-02 17:19:13 +000055#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080056#include <android-base/stringprintf.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070057#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <utils/Trace.h>
59#include <powermanager/PowerManager.h>
60#include <ui/Region.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080061
62#define INDENT " "
63#define INDENT2 " "
64#define INDENT3 " "
65#define INDENT4 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
71// Default input dispatching timeout if there is no focused application or paused window
72// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000073constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080074
75// Amount of time to allow for all pending events to be processed when an app switch
76// key is on the way. This is used to preempt input dispatch and drop input events
77// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000078constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Amount of time to allow for an event to be dispatched (measured since its eventTime)
81// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000082constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080083
84// Amount of time to allow touch events to be streamed out to a connection before requiring
85// that the first event be finished. This value extends the ANR timeout by the specified
86// amount. For example, if streaming is allowed to get ahead by one second relative to the
87// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000091constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
92
93// Log a warning when an interception call takes longer than this to process.
94constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
96// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +000097constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
98
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
100static inline nsecs_t now() {
101 return systemTime(SYSTEM_TIME_MONOTONIC);
102}
103
104static inline const char* toString(bool value) {
105 return value ? "true" : "false";
106}
107
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800108static std::string motionActionToString(int32_t action) {
109 // Convert MotionEvent action to string
110 switch(action & AMOTION_EVENT_ACTION_MASK) {
111 case AMOTION_EVENT_ACTION_DOWN:
112 return "DOWN";
113 case AMOTION_EVENT_ACTION_MOVE:
114 return "MOVE";
115 case AMOTION_EVENT_ACTION_UP:
116 return "UP";
117 case AMOTION_EVENT_ACTION_POINTER_DOWN:
118 return "POINTER_DOWN";
119 case AMOTION_EVENT_ACTION_POINTER_UP:
120 return "POINTER_UP";
121 }
122 return StringPrintf("%" PRId32, action);
123}
124
125static std::string keyActionToString(int32_t action) {
126 // Convert KeyEvent action to string
127 switch(action) {
128 case AKEY_EVENT_ACTION_DOWN:
129 return "DOWN";
130 case AKEY_EVENT_ACTION_UP:
131 return "UP";
132 case AKEY_EVENT_ACTION_MULTIPLE:
133 return "MULTIPLE";
134 }
135 return StringPrintf("%" PRId32, action);
136}
137
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
139 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
140 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
141}
142
143static bool isValidKeyAction(int32_t action) {
144 switch (action) {
145 case AKEY_EVENT_ACTION_DOWN:
146 case AKEY_EVENT_ACTION_UP:
147 return true;
148 default:
149 return false;
150 }
151}
152
153static bool validateKeyEvent(int32_t action) {
154 if (! isValidKeyAction(action)) {
155 ALOGE("Key event has invalid action code 0x%x", action);
156 return false;
157 }
158 return true;
159}
160
Michael Wright7b159c92015-05-14 14:48:03 +0100161static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800162 switch (action & AMOTION_EVENT_ACTION_MASK) {
163 case AMOTION_EVENT_ACTION_DOWN:
164 case AMOTION_EVENT_ACTION_UP:
165 case AMOTION_EVENT_ACTION_CANCEL:
166 case AMOTION_EVENT_ACTION_MOVE:
167 case AMOTION_EVENT_ACTION_OUTSIDE:
168 case AMOTION_EVENT_ACTION_HOVER_ENTER:
169 case AMOTION_EVENT_ACTION_HOVER_MOVE:
170 case AMOTION_EVENT_ACTION_HOVER_EXIT:
171 case AMOTION_EVENT_ACTION_SCROLL:
172 return true;
173 case AMOTION_EVENT_ACTION_POINTER_DOWN:
174 case AMOTION_EVENT_ACTION_POINTER_UP: {
175 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800176 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 }
Michael Wright7b159c92015-05-14 14:48:03 +0100178 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
179 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
180 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 default:
182 return false;
183 }
184}
185
Michael Wright7b159c92015-05-14 14:48:03 +0100186static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100188 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 ALOGE("Motion event has invalid action code 0x%x", action);
190 return false;
191 }
192 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000193 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 pointerCount, MAX_POINTERS);
195 return false;
196 }
197 BitSet32 pointerIdBits;
198 for (size_t i = 0; i < pointerCount; i++) {
199 int32_t id = pointerProperties[i].id;
200 if (id < 0 || id > MAX_POINTER_ID) {
201 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
202 id, MAX_POINTER_ID);
203 return false;
204 }
205 if (pointerIdBits.hasBit(id)) {
206 ALOGE("Motion event has duplicate pointer id %d", id);
207 return false;
208 }
209 pointerIdBits.markBit(id);
210 }
211 return true;
212}
213
214static bool isMainDisplay(int32_t displayId) {
215 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
216}
217
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800218static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800220 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 return;
222 }
223
224 bool first = true;
225 Region::const_iterator cur = region.begin();
226 Region::const_iterator const tail = region.end();
227 while (cur != tail) {
228 if (first) {
229 first = false;
230 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800231 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800233 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 cur++;
235 }
236}
237
238
239// --- InputDispatcher ---
240
241InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
242 mPolicy(policy),
Michael Wright3a981722015-06-10 15:26:13 +0100243 mPendingEvent(NULL), mLastDropReason(DROP_REASON_NOT_DROPPED),
244 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245 mNextUnblockedEvent(NULL),
246 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
247 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
248 mLooper = new Looper(false);
249
250 mKeyRepeatState.lastKeyEntry = NULL;
251
252 policy->getDispatcherConfiguration(&mConfig);
253}
254
255InputDispatcher::~InputDispatcher() {
256 { // acquire lock
257 AutoMutex _l(mLock);
258
259 resetKeyRepeatLocked();
260 releasePendingEventLocked();
261 drainInboundQueueLocked();
262 }
263
264 while (mConnectionsByFd.size() != 0) {
265 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
266 }
267}
268
269void InputDispatcher::dispatchOnce() {
270 nsecs_t nextWakeupTime = LONG_LONG_MAX;
271 { // acquire lock
272 AutoMutex _l(mLock);
273 mDispatcherIsAliveCondition.broadcast();
274
275 // Run a dispatch loop if there are no pending commands.
276 // The dispatch loop might enqueue commands to run afterwards.
277 if (!haveCommandsLocked()) {
278 dispatchOnceInnerLocked(&nextWakeupTime);
279 }
280
281 // Run all pending commands if there are any.
282 // If any commands were run then force the next poll to wake up immediately.
283 if (runCommandsLockedInterruptible()) {
284 nextWakeupTime = LONG_LONG_MIN;
285 }
286 } // release lock
287
288 // Wait for callback or timeout or wake. (make sure we round up, not down)
289 nsecs_t currentTime = now();
290 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
291 mLooper->pollOnce(timeoutMillis);
292}
293
294void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
295 nsecs_t currentTime = now();
296
Jeff Browndc5992e2014-04-11 01:27:26 -0700297 // Reset the key repeat timer whenever normal dispatch is suspended while the
298 // device is in a non-interactive state. This is to ensure that we abort a key
299 // repeat if the device is just coming out of sleep.
300 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800301 resetKeyRepeatLocked();
302 }
303
304 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
305 if (mDispatchFrozen) {
306#if DEBUG_FOCUS
307 ALOGD("Dispatch frozen. Waiting some more.");
308#endif
309 return;
310 }
311
312 // Optimize latency of app switches.
313 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
314 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
315 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
316 if (mAppSwitchDueTime < *nextWakeupTime) {
317 *nextWakeupTime = mAppSwitchDueTime;
318 }
319
320 // Ready to start a new event.
321 // If we don't already have a pending event, go grab one.
322 if (! mPendingEvent) {
323 if (mInboundQueue.isEmpty()) {
324 if (isAppSwitchDue) {
325 // The inbound queue is empty so the app switch key we were waiting
326 // for will never arrive. Stop waiting for it.
327 resetPendingAppSwitchLocked(false);
328 isAppSwitchDue = false;
329 }
330
331 // Synthesize a key repeat if appropriate.
332 if (mKeyRepeatState.lastKeyEntry) {
333 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
334 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
335 } else {
336 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
337 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
338 }
339 }
340 }
341
342 // Nothing to do if there is no pending event.
343 if (!mPendingEvent) {
344 return;
345 }
346 } else {
347 // Inbound queue has at least one entry.
348 mPendingEvent = mInboundQueue.dequeueAtHead();
349 traceInboundQueueLengthLocked();
350 }
351
352 // Poke user activity for this event.
353 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
354 pokeUserActivityLocked(mPendingEvent);
355 }
356
357 // Get ready to dispatch the event.
358 resetANRTimeoutsLocked();
359 }
360
361 // Now we have an event to dispatch.
362 // All events are eventually dequeued and processed this way, even if we intend to drop them.
363 ALOG_ASSERT(mPendingEvent != NULL);
364 bool done = false;
365 DropReason dropReason = DROP_REASON_NOT_DROPPED;
366 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
367 dropReason = DROP_REASON_POLICY;
368 } else if (!mDispatchEnabled) {
369 dropReason = DROP_REASON_DISABLED;
370 }
371
372 if (mNextUnblockedEvent == mPendingEvent) {
373 mNextUnblockedEvent = NULL;
374 }
375
376 switch (mPendingEvent->type) {
377 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
378 ConfigurationChangedEntry* typedEntry =
379 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
380 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
381 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
382 break;
383 }
384
385 case EventEntry::TYPE_DEVICE_RESET: {
386 DeviceResetEntry* typedEntry =
387 static_cast<DeviceResetEntry*>(mPendingEvent);
388 done = dispatchDeviceResetLocked(currentTime, typedEntry);
389 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
390 break;
391 }
392
393 case EventEntry::TYPE_KEY: {
394 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
395 if (isAppSwitchDue) {
396 if (isAppSwitchKeyEventLocked(typedEntry)) {
397 resetPendingAppSwitchLocked(true);
398 isAppSwitchDue = false;
399 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
400 dropReason = DROP_REASON_APP_SWITCH;
401 }
402 }
403 if (dropReason == DROP_REASON_NOT_DROPPED
404 && isStaleEventLocked(currentTime, typedEntry)) {
405 dropReason = DROP_REASON_STALE;
406 }
407 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
408 dropReason = DROP_REASON_BLOCKED;
409 }
410 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
411 break;
412 }
413
414 case EventEntry::TYPE_MOTION: {
415 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
416 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
417 dropReason = DROP_REASON_APP_SWITCH;
418 }
419 if (dropReason == DROP_REASON_NOT_DROPPED
420 && isStaleEventLocked(currentTime, typedEntry)) {
421 dropReason = DROP_REASON_STALE;
422 }
423 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
424 dropReason = DROP_REASON_BLOCKED;
425 }
426 done = dispatchMotionLocked(currentTime, typedEntry,
427 &dropReason, nextWakeupTime);
428 break;
429 }
430
431 default:
432 ALOG_ASSERT(false);
433 break;
434 }
435
436 if (done) {
437 if (dropReason != DROP_REASON_NOT_DROPPED) {
438 dropInboundEventLocked(mPendingEvent, dropReason);
439 }
Michael Wright3a981722015-06-10 15:26:13 +0100440 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800441
442 releasePendingEventLocked();
443 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
444 }
445}
446
447bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
448 bool needWake = mInboundQueue.isEmpty();
449 mInboundQueue.enqueueAtTail(entry);
450 traceInboundQueueLengthLocked();
451
452 switch (entry->type) {
453 case EventEntry::TYPE_KEY: {
454 // Optimize app switch latency.
455 // If the application takes too long to catch up then we drop all events preceding
456 // the app switch key.
457 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
458 if (isAppSwitchKeyEventLocked(keyEntry)) {
459 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
460 mAppSwitchSawKeyDown = true;
461 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
462 if (mAppSwitchSawKeyDown) {
463#if DEBUG_APP_SWITCH
464 ALOGD("App switch is pending!");
465#endif
466 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
467 mAppSwitchSawKeyDown = false;
468 needWake = true;
469 }
470 }
471 }
472 break;
473 }
474
475 case EventEntry::TYPE_MOTION: {
476 // Optimize case where the current application is unresponsive and the user
477 // decides to touch a window in a different application.
478 // If the application takes too long to catch up then we drop all events preceding
479 // the touch into the other window.
480 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
481 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
482 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
483 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
484 && mInputTargetWaitApplicationHandle != NULL) {
485 int32_t displayId = motionEntry->displayId;
486 int32_t x = int32_t(motionEntry->pointerCoords[0].
487 getAxisValue(AMOTION_EVENT_AXIS_X));
488 int32_t y = int32_t(motionEntry->pointerCoords[0].
489 getAxisValue(AMOTION_EVENT_AXIS_Y));
490 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
491 if (touchedWindowHandle != NULL
492 && touchedWindowHandle->inputApplicationHandle
493 != mInputTargetWaitApplicationHandle) {
494 // User touched a different application than the one we are waiting on.
495 // Flag the event, and start pruning the input queue.
496 mNextUnblockedEvent = motionEntry;
497 needWake = true;
498 }
499 }
500 break;
501 }
502 }
503
504 return needWake;
505}
506
507void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
508 entry->refCount += 1;
509 mRecentQueue.enqueueAtTail(entry);
510 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
511 mRecentQueue.dequeueAtHead()->release();
512 }
513}
514
515sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
516 int32_t x, int32_t y) {
517 // Traverse windows from front to back to find touched window.
518 size_t numWindows = mWindowHandles.size();
519 for (size_t i = 0; i < numWindows; i++) {
520 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
521 const InputWindowInfo* windowInfo = windowHandle->getInfo();
522 if (windowInfo->displayId == displayId) {
523 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800524
525 if (windowInfo->visible) {
526 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
527 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
528 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
529 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
530 // Found window.
531 return windowHandle;
532 }
533 }
534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535 }
536 }
537 return NULL;
538}
539
540void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
541 const char* reason;
542 switch (dropReason) {
543 case DROP_REASON_POLICY:
544#if DEBUG_INBOUND_EVENT_DETAILS
545 ALOGD("Dropped event because policy consumed it.");
546#endif
547 reason = "inbound event was dropped because the policy consumed it";
548 break;
549 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100550 if (mLastDropReason != DROP_REASON_DISABLED) {
551 ALOGI("Dropped event because input dispatch is disabled.");
552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553 reason = "inbound event was dropped because input dispatch is disabled";
554 break;
555 case DROP_REASON_APP_SWITCH:
556 ALOGI("Dropped event because of pending overdue app switch.");
557 reason = "inbound event was dropped because of pending overdue app switch";
558 break;
559 case DROP_REASON_BLOCKED:
560 ALOGI("Dropped event because the current application is not responding and the user "
561 "has started interacting with a different application.");
562 reason = "inbound event was dropped because the current application is not responding "
563 "and the user has started interacting with a different application";
564 break;
565 case DROP_REASON_STALE:
566 ALOGI("Dropped event because it is stale.");
567 reason = "inbound event was dropped because it is stale";
568 break;
569 default:
570 ALOG_ASSERT(false);
571 return;
572 }
573
574 switch (entry->type) {
575 case EventEntry::TYPE_KEY: {
576 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
577 synthesizeCancelationEventsForAllConnectionsLocked(options);
578 break;
579 }
580 case EventEntry::TYPE_MOTION: {
581 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
582 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
583 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
584 synthesizeCancelationEventsForAllConnectionsLocked(options);
585 } else {
586 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
587 synthesizeCancelationEventsForAllConnectionsLocked(options);
588 }
589 break;
590 }
591 }
592}
593
594bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
595 return keyCode == AKEYCODE_HOME
596 || keyCode == AKEYCODE_ENDCALL
597 || keyCode == AKEYCODE_APP_SWITCH;
598}
599
600bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
601 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
602 && isAppSwitchKeyCode(keyEntry->keyCode)
603 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
604 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
605}
606
607bool InputDispatcher::isAppSwitchPendingLocked() {
608 return mAppSwitchDueTime != LONG_LONG_MAX;
609}
610
611void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
612 mAppSwitchDueTime = LONG_LONG_MAX;
613
614#if DEBUG_APP_SWITCH
615 if (handled) {
616 ALOGD("App switch has arrived.");
617 } else {
618 ALOGD("App switch was abandoned.");
619 }
620#endif
621}
622
623bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
624 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
625}
626
627bool InputDispatcher::haveCommandsLocked() const {
628 return !mCommandQueue.isEmpty();
629}
630
631bool InputDispatcher::runCommandsLockedInterruptible() {
632 if (mCommandQueue.isEmpty()) {
633 return false;
634 }
635
636 do {
637 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
638
639 Command command = commandEntry->command;
640 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
641
642 commandEntry->connection.clear();
643 delete commandEntry;
644 } while (! mCommandQueue.isEmpty());
645 return true;
646}
647
648InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
649 CommandEntry* commandEntry = new CommandEntry(command);
650 mCommandQueue.enqueueAtTail(commandEntry);
651 return commandEntry;
652}
653
654void InputDispatcher::drainInboundQueueLocked() {
655 while (! mInboundQueue.isEmpty()) {
656 EventEntry* entry = mInboundQueue.dequeueAtHead();
657 releaseInboundEventLocked(entry);
658 }
659 traceInboundQueueLengthLocked();
660}
661
662void InputDispatcher::releasePendingEventLocked() {
663 if (mPendingEvent) {
664 resetANRTimeoutsLocked();
665 releaseInboundEventLocked(mPendingEvent);
666 mPendingEvent = NULL;
667 }
668}
669
670void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
671 InjectionState* injectionState = entry->injectionState;
672 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
673#if DEBUG_DISPATCH_CYCLE
674 ALOGD("Injected inbound event was dropped.");
675#endif
676 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
677 }
678 if (entry == mNextUnblockedEvent) {
679 mNextUnblockedEvent = NULL;
680 }
681 addRecentEventLocked(entry);
682 entry->release();
683}
684
685void InputDispatcher::resetKeyRepeatLocked() {
686 if (mKeyRepeatState.lastKeyEntry) {
687 mKeyRepeatState.lastKeyEntry->release();
688 mKeyRepeatState.lastKeyEntry = NULL;
689 }
690}
691
692InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
693 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
694
695 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700696 uint32_t policyFlags = entry->policyFlags &
697 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 if (entry->refCount == 1) {
699 entry->recycle();
700 entry->eventTime = currentTime;
701 entry->policyFlags = policyFlags;
702 entry->repeatCount += 1;
703 } else {
704 KeyEntry* newEntry = new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100705 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706 entry->action, entry->flags, entry->keyCode, entry->scanCode,
707 entry->metaState, entry->repeatCount + 1, entry->downTime);
708
709 mKeyRepeatState.lastKeyEntry = newEntry;
710 entry->release();
711
712 entry = newEntry;
713 }
714 entry->syntheticRepeat = true;
715
716 // Increment reference count since we keep a reference to the event in
717 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
718 entry->refCount += 1;
719
720 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
721 return entry;
722}
723
724bool InputDispatcher::dispatchConfigurationChangedLocked(
725 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
726#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700727 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728#endif
729
730 // Reset key repeating in case a keyboard device was added or removed or something.
731 resetKeyRepeatLocked();
732
733 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
734 CommandEntry* commandEntry = postCommandLocked(
735 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
736 commandEntry->eventTime = entry->eventTime;
737 return true;
738}
739
740bool InputDispatcher::dispatchDeviceResetLocked(
741 nsecs_t currentTime, DeviceResetEntry* entry) {
742#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700743 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
744 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745#endif
746
747 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
748 "device was reset");
749 options.deviceId = entry->deviceId;
750 synthesizeCancelationEventsForAllConnectionsLocked(options);
751 return true;
752}
753
754bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
755 DropReason* dropReason, nsecs_t* nextWakeupTime) {
756 // Preprocessing.
757 if (! entry->dispatchInProgress) {
758 if (entry->repeatCount == 0
759 && entry->action == AKEY_EVENT_ACTION_DOWN
760 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
761 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
762 if (mKeyRepeatState.lastKeyEntry
763 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
764 // We have seen two identical key downs in a row which indicates that the device
765 // driver is automatically generating key repeats itself. We take note of the
766 // repeat here, but we disable our own next key repeat timer since it is clear that
767 // we will not need to synthesize key repeats ourselves.
768 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
769 resetKeyRepeatLocked();
770 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
771 } else {
772 // Not a repeat. Save key down state in case we do see a repeat later.
773 resetKeyRepeatLocked();
774 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
775 }
776 mKeyRepeatState.lastKeyEntry = entry;
777 entry->refCount += 1;
778 } else if (! entry->syntheticRepeat) {
779 resetKeyRepeatLocked();
780 }
781
782 if (entry->repeatCount == 1) {
783 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
784 } else {
785 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
786 }
787
788 entry->dispatchInProgress = true;
789
790 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
791 }
792
793 // Handle case where the policy asked us to try again later last time.
794 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
795 if (currentTime < entry->interceptKeyWakeupTime) {
796 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
797 *nextWakeupTime = entry->interceptKeyWakeupTime;
798 }
799 return false; // wait until next wakeup
800 }
801 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
802 entry->interceptKeyWakeupTime = 0;
803 }
804
805 // Give the policy a chance to intercept the key.
806 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
807 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
808 CommandEntry* commandEntry = postCommandLocked(
809 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
810 if (mFocusedWindowHandle != NULL) {
811 commandEntry->inputWindowHandle = mFocusedWindowHandle;
812 }
813 commandEntry->keyEntry = entry;
814 entry->refCount += 1;
815 return false; // wait for the command to run
816 } else {
817 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
818 }
819 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
820 if (*dropReason == DROP_REASON_NOT_DROPPED) {
821 *dropReason = DROP_REASON_POLICY;
822 }
823 }
824
825 // Clean up if dropping the event.
826 if (*dropReason != DROP_REASON_NOT_DROPPED) {
827 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
828 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
829 return true;
830 }
831
832 // Identify targets.
833 Vector<InputTarget> inputTargets;
834 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
835 entry, inputTargets, nextWakeupTime);
836 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
837 return false;
838 }
839
840 setInjectionResultLocked(entry, injectionResult);
841 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
842 return true;
843 }
844
845 addMonitoringTargetsLocked(inputTargets);
846
847 // Dispatch the key.
848 dispatchEventLocked(currentTime, entry, inputTargets);
849 return true;
850}
851
852void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
853#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100854 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
855 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
856 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100858 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
860 entry->repeatCount, entry->downTime);
861#endif
862}
863
864bool InputDispatcher::dispatchMotionLocked(
865 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
866 // Preprocessing.
867 if (! entry->dispatchInProgress) {
868 entry->dispatchInProgress = true;
869
870 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
871 }
872
873 // Clean up if dropping the event.
874 if (*dropReason != DROP_REASON_NOT_DROPPED) {
875 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
876 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
877 return true;
878 }
879
880 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
881
882 // Identify targets.
883 Vector<InputTarget> inputTargets;
884
885 bool conflictingPointerActions = false;
886 int32_t injectionResult;
887 if (isPointerEvent) {
888 // Pointer event. (eg. touchscreen)
889 injectionResult = findTouchedWindowTargetsLocked(currentTime,
890 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
891 } else {
892 // Non touch event. (eg. trackball)
893 injectionResult = findFocusedWindowTargetsLocked(currentTime,
894 entry, inputTargets, nextWakeupTime);
895 }
896 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
897 return false;
898 }
899
900 setInjectionResultLocked(entry, injectionResult);
901 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100902 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
903 CancelationOptions::Mode mode(isPointerEvent ?
904 CancelationOptions::CANCEL_POINTER_EVENTS :
905 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
906 CancelationOptions options(mode, "input event injection failed");
907 synthesizeCancelationEventsForMonitorsLocked(options);
908 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 return true;
910 }
911
Tarandeep Singh48aeb512017-07-17 11:22:52 -0700912 addMonitoringTargetsLocked(inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913
914 // Dispatch the motion.
915 if (conflictingPointerActions) {
916 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
917 "conflicting pointer actions");
918 synthesizeCancelationEventsForAllConnectionsLocked(options);
919 }
920 dispatchEventLocked(currentTime, entry, inputTargets);
921 return true;
922}
923
924
925void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
926#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800927 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
928 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100929 "action=0x%x, actionButton=0x%x, flags=0x%x, "
930 "metaState=0x%x, buttonState=0x%x,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700931 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800933 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100934 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 entry->metaState, entry->buttonState,
936 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
937 entry->downTime);
938
939 for (uint32_t i = 0; i < entry->pointerCount; i++) {
940 ALOGD(" Pointer %d: id=%d, toolType=%d, "
941 "x=%f, y=%f, pressure=%f, size=%f, "
942 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800943 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 i, entry->pointerProperties[i].id,
945 entry->pointerProperties[i].toolType,
946 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
947 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
948 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
949 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
950 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
951 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
952 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
953 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800954 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955 }
956#endif
957}
958
959void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
960 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
961#if DEBUG_DISPATCH_CYCLE
962 ALOGD("dispatchEventToCurrentInputTargets");
963#endif
964
965 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
966
967 pokeUserActivityLocked(eventEntry);
968
969 for (size_t i = 0; i < inputTargets.size(); i++) {
970 const InputTarget& inputTarget = inputTargets.itemAt(i);
971
972 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
973 if (connectionIndex >= 0) {
974 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
975 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
976 } else {
977#if DEBUG_FOCUS
978 ALOGD("Dropping event delivery to target with channel '%s' because it "
979 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800980 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981#endif
982 }
983 }
984}
985
986int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
987 const EventEntry* entry,
988 const sp<InputApplicationHandle>& applicationHandle,
989 const sp<InputWindowHandle>& windowHandle,
990 nsecs_t* nextWakeupTime, const char* reason) {
991 if (applicationHandle == NULL && windowHandle == NULL) {
992 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
993#if DEBUG_FOCUS
994 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
995#endif
996 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
997 mInputTargetWaitStartTime = currentTime;
998 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
999 mInputTargetWaitTimeoutExpired = false;
1000 mInputTargetWaitApplicationHandle.clear();
1001 }
1002 } else {
1003 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1004#if DEBUG_FOCUS
1005 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001006 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 reason);
1008#endif
1009 nsecs_t timeout;
1010 if (windowHandle != NULL) {
1011 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1012 } else if (applicationHandle != NULL) {
1013 timeout = applicationHandle->getDispatchingTimeout(
1014 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1015 } else {
1016 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1017 }
1018
1019 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1020 mInputTargetWaitStartTime = currentTime;
1021 mInputTargetWaitTimeoutTime = currentTime + timeout;
1022 mInputTargetWaitTimeoutExpired = false;
1023 mInputTargetWaitApplicationHandle.clear();
1024
1025 if (windowHandle != NULL) {
1026 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
1027 }
1028 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
1029 mInputTargetWaitApplicationHandle = applicationHandle;
1030 }
1031 }
1032 }
1033
1034 if (mInputTargetWaitTimeoutExpired) {
1035 return INPUT_EVENT_INJECTION_TIMED_OUT;
1036 }
1037
1038 if (currentTime >= mInputTargetWaitTimeoutTime) {
1039 onANRLocked(currentTime, applicationHandle, windowHandle,
1040 entry->eventTime, mInputTargetWaitStartTime, reason);
1041
1042 // Force poll loop to wake up immediately on next iteration once we get the
1043 // ANR response back from the policy.
1044 *nextWakeupTime = LONG_LONG_MIN;
1045 return INPUT_EVENT_INJECTION_PENDING;
1046 } else {
1047 // Force poll loop to wake up when timeout is due.
1048 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1049 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1050 }
1051 return INPUT_EVENT_INJECTION_PENDING;
1052 }
1053}
1054
1055void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1056 const sp<InputChannel>& inputChannel) {
1057 if (newTimeout > 0) {
1058 // Extend the timeout.
1059 mInputTargetWaitTimeoutTime = now() + newTimeout;
1060 } else {
1061 // Give up.
1062 mInputTargetWaitTimeoutExpired = true;
1063
1064 // Input state will not be realistic. Mark it out of sync.
1065 if (inputChannel.get()) {
1066 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1067 if (connectionIndex >= 0) {
1068 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1069 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1070
1071 if (windowHandle != NULL) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001072 const InputWindowInfo* info = windowHandle->getInfo();
1073 if (info) {
1074 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId);
1075 if (stateIndex >= 0) {
1076 mTouchStatesByDisplay.editValueAt(stateIndex).removeWindow(
1077 windowHandle);
1078 }
1079 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 }
1081
1082 if (connection->status == Connection::STATUS_NORMAL) {
1083 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1084 "application not responding");
1085 synthesizeCancelationEventsForConnectionLocked(connection, options);
1086 }
1087 }
1088 }
1089 }
1090}
1091
1092nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1093 nsecs_t currentTime) {
1094 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1095 return currentTime - mInputTargetWaitStartTime;
1096 }
1097 return 0;
1098}
1099
1100void InputDispatcher::resetANRTimeoutsLocked() {
1101#if DEBUG_FOCUS
1102 ALOGD("Resetting ANR timeouts.");
1103#endif
1104
1105 // Reset input target wait timeout.
1106 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1107 mInputTargetWaitApplicationHandle.clear();
1108}
1109
1110int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1111 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1112 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001113 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114
1115 // If there is no currently focused window and no focused application
1116 // then drop the event.
1117 if (mFocusedWindowHandle == NULL) {
1118 if (mFocusedApplicationHandle != NULL) {
1119 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1120 mFocusedApplicationHandle, NULL, nextWakeupTime,
1121 "Waiting because no window has focus but there is a "
1122 "focused application that may eventually add a window "
1123 "when it finishes starting up.");
1124 goto Unresponsive;
1125 }
1126
1127 ALOGI("Dropping event because there is no focused window or focused application.");
1128 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1129 goto Failed;
1130 }
1131
1132 // Check permissions.
1133 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
1134 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1135 goto Failed;
1136 }
1137
Jeff Brownffb49772014-10-10 19:01:34 -07001138 // Check whether the window is ready for more input.
1139 reason = checkWindowReadyForMoreInputLocked(currentTime,
1140 mFocusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001141 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001143 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144 goto Unresponsive;
1145 }
1146
1147 // Success! Output targets.
1148 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1149 addWindowTargetLocked(mFocusedWindowHandle,
1150 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1151 inputTargets);
1152
1153 // Done.
1154Failed:
1155Unresponsive:
1156 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1157 updateDispatchStatisticsLocked(currentTime, entry,
1158 injectionResult, timeSpentWaitingForApplication);
1159#if DEBUG_FOCUS
1160 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1161 "timeSpentWaitingForApplication=%0.1fms",
1162 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1163#endif
1164 return injectionResult;
1165}
1166
1167int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1168 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1169 bool* outConflictingPointerActions) {
1170 enum InjectionPermission {
1171 INJECTION_PERMISSION_UNKNOWN,
1172 INJECTION_PERMISSION_GRANTED,
1173 INJECTION_PERMISSION_DENIED
1174 };
1175
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 // For security reasons, we defer updating the touch state until we are sure that
1177 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 int32_t displayId = entry->displayId;
1179 int32_t action = entry->action;
1180 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1181
1182 // Update the touch state as needed based on the properties of the touch event.
1183 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1184 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1185 sp<InputWindowHandle> newHoverWindowHandle;
1186
Jeff Brownf086ddb2014-02-11 14:28:48 -08001187 // Copy current touch state into mTempTouchState.
1188 // This state is always reset at the end of this function, so if we don't find state
1189 // for the specified display then our initial state will be empty.
1190 const TouchState* oldState = NULL;
1191 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1192 if (oldStateIndex >= 0) {
1193 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1194 mTempTouchState.copyFrom(*oldState);
1195 }
1196
1197 bool isSplit = mTempTouchState.split;
1198 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1199 && (mTempTouchState.deviceId != entry->deviceId
1200 || mTempTouchState.source != entry->source
1201 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1203 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1204 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1205 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1206 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1207 || isHoverAction);
1208 bool wrongDevice = false;
1209 if (newGesture) {
1210 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001211 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001212#if DEBUG_FOCUS
1213 ALOGD("Dropping event because a pointer for a different device is already down.");
1214#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001215 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1217 switchedDevice = false;
1218 wrongDevice = true;
1219 goto Failed;
1220 }
1221 mTempTouchState.reset();
1222 mTempTouchState.down = down;
1223 mTempTouchState.deviceId = entry->deviceId;
1224 mTempTouchState.source = entry->source;
1225 mTempTouchState.displayId = displayId;
1226 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001227 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1228#if DEBUG_FOCUS
1229 ALOGI("Dropping move event because a pointer for a different device is already active.");
1230#endif
1231 // TODO: test multiple simultaneous input streams.
1232 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1233 switchedDevice = false;
1234 wrongDevice = true;
1235 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 }
1237
1238 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1239 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1240
1241 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1242 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1243 getAxisValue(AMOTION_EVENT_AXIS_X));
1244 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1245 getAxisValue(AMOTION_EVENT_AXIS_Y));
1246 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 bool isTouchModal = false;
1248
1249 // Traverse windows from front to back to find touched window and outside targets.
1250 size_t numWindows = mWindowHandles.size();
1251 for (size_t i = 0; i < numWindows; i++) {
1252 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1253 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1254 if (windowInfo->displayId != displayId) {
1255 continue; // wrong display
1256 }
1257
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 int32_t flags = windowInfo->layoutParamsFlags;
1259 if (windowInfo->visible) {
1260 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1261 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1262 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1263 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001264 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 break; // found touched window, exit window loop
1266 }
1267 }
1268
1269 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1270 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001272 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 }
1274 }
1275 }
1276
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 // Figure out whether splitting will be allowed for this window.
1278 if (newTouchedWindowHandle != NULL
1279 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1280 // New window supports splitting.
1281 isSplit = true;
1282 } else if (isSplit) {
1283 // New window does not support splitting but we have already split events.
1284 // Ignore the new window.
1285 newTouchedWindowHandle = NULL;
1286 }
1287
1288 // Handle the case where we did not find a window.
1289 if (newTouchedWindowHandle == NULL) {
1290 // Try to assign the pointer to the first foreground window we find, if there is one.
1291 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1292 if (newTouchedWindowHandle == NULL) {
1293 ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y);
1294 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1295 goto Failed;
1296 }
1297 }
1298
1299 // Set target flags.
1300 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1301 if (isSplit) {
1302 targetFlags |= InputTarget::FLAG_SPLIT;
1303 }
1304 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1305 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001306 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1307 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 }
1309
1310 // Update hover state.
1311 if (isHoverAction) {
1312 newHoverWindowHandle = newTouchedWindowHandle;
1313 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1314 newHoverWindowHandle = mLastHoverWindowHandle;
1315 }
1316
1317 // Update the temporary touch state.
1318 BitSet32 pointerIds;
1319 if (isSplit) {
1320 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1321 pointerIds.markBit(pointerId);
1322 }
1323 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1324 } else {
1325 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1326
1327 // If the pointer is not currently down, then ignore the event.
1328 if (! mTempTouchState.down) {
1329#if DEBUG_FOCUS
1330 ALOGD("Dropping event because the pointer is not down or we previously "
1331 "dropped the pointer down event.");
1332#endif
1333 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1334 goto Failed;
1335 }
1336
1337 // Check whether touches should slip outside of the current foreground window.
1338 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1339 && entry->pointerCount == 1
1340 && mTempTouchState.isSlippery()) {
1341 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1342 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1343
1344 sp<InputWindowHandle> oldTouchedWindowHandle =
1345 mTempTouchState.getFirstForegroundWindowHandle();
1346 sp<InputWindowHandle> newTouchedWindowHandle =
1347 findTouchedWindowAtLocked(displayId, x, y);
1348 if (oldTouchedWindowHandle != newTouchedWindowHandle
1349 && newTouchedWindowHandle != NULL) {
1350#if DEBUG_FOCUS
1351 ALOGD("Touch is slipping out of window %s into window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001352 oldTouchedWindowHandle->getName().c_str(),
1353 newTouchedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001354#endif
1355 // Make a slippery exit from the old window.
1356 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1357 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1358
1359 // Make a slippery entrance into the new window.
1360 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1361 isSplit = true;
1362 }
1363
1364 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1365 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1366 if (isSplit) {
1367 targetFlags |= InputTarget::FLAG_SPLIT;
1368 }
1369 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1370 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1371 }
1372
1373 BitSet32 pointerIds;
1374 if (isSplit) {
1375 pointerIds.markBit(entry->pointerProperties[0].id);
1376 }
1377 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1378 }
1379 }
1380 }
1381
1382 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1383 // Let the previous window know that the hover sequence is over.
1384 if (mLastHoverWindowHandle != NULL) {
1385#if DEBUG_HOVER
1386 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001387 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388#endif
1389 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1390 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1391 }
1392
1393 // Let the new window know that the hover sequence is starting.
1394 if (newHoverWindowHandle != NULL) {
1395#if DEBUG_HOVER
1396 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001397 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001398#endif
1399 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1400 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1401 }
1402 }
1403
1404 // Check permission to inject into all touched foreground windows and ensure there
1405 // is at least one touched foreground window.
1406 {
1407 bool haveForegroundWindow = false;
1408 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1409 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1410 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1411 haveForegroundWindow = true;
1412 if (! checkInjectionPermission(touchedWindow.windowHandle,
1413 entry->injectionState)) {
1414 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1415 injectionPermission = INJECTION_PERMISSION_DENIED;
1416 goto Failed;
1417 }
1418 }
1419 }
1420 if (! haveForegroundWindow) {
1421#if DEBUG_FOCUS
1422 ALOGD("Dropping event because there is no touched foreground window to receive it.");
1423#endif
1424 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1425 goto Failed;
1426 }
1427
1428 // Permission granted to injection into all touched foreground windows.
1429 injectionPermission = INJECTION_PERMISSION_GRANTED;
1430 }
1431
1432 // Check whether windows listening for outside touches are owned by the same UID. If it is
1433 // set the policy flag that we will not reveal coordinate information to this window.
1434 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1435 sp<InputWindowHandle> foregroundWindowHandle =
1436 mTempTouchState.getFirstForegroundWindowHandle();
1437 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1438 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1439 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1440 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1441 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1442 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1443 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1444 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1445 }
1446 }
1447 }
1448 }
1449
1450 // Ensure all touched foreground windows are ready for new input.
1451 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1452 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1453 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001454 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001455 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001456 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001457 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001459 NULL, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 goto Unresponsive;
1461 }
1462 }
1463 }
1464
1465 // If this is the first pointer going down and the touched window has a wallpaper
1466 // then also add the touched wallpaper windows so they are locked in for the duration
1467 // of the touch gesture.
1468 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1469 // engine only supports touch events. We would need to add a mechanism similar
1470 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1471 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1472 sp<InputWindowHandle> foregroundWindowHandle =
1473 mTempTouchState.getFirstForegroundWindowHandle();
1474 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
1475 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1476 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1477 const InputWindowInfo* info = windowHandle->getInfo();
1478 if (info->displayId == displayId
1479 && windowHandle->getInfo()->layoutParamsType
1480 == InputWindowInfo::TYPE_WALLPAPER) {
1481 mTempTouchState.addOrUpdateWindow(windowHandle,
1482 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001483 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484 | InputTarget::FLAG_DISPATCH_AS_IS,
1485 BitSet32(0));
1486 }
1487 }
1488 }
1489 }
1490
1491 // Success! Output targets.
1492 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1493
1494 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1495 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1496 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1497 touchedWindow.pointerIds, inputTargets);
1498 }
1499
1500 // Drop the outside or hover touch windows since we will not care about them
1501 // in the next iteration.
1502 mTempTouchState.filterNonAsIsTouchWindows();
1503
1504Failed:
1505 // Check injection permission once and for all.
1506 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
1507 if (checkInjectionPermission(NULL, entry->injectionState)) {
1508 injectionPermission = INJECTION_PERMISSION_GRANTED;
1509 } else {
1510 injectionPermission = INJECTION_PERMISSION_DENIED;
1511 }
1512 }
1513
1514 // Update final pieces of touch state if the injector had permission.
1515 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1516 if (!wrongDevice) {
1517 if (switchedDevice) {
1518#if DEBUG_FOCUS
1519 ALOGD("Conflicting pointer actions: Switched to a different device.");
1520#endif
1521 *outConflictingPointerActions = true;
1522 }
1523
1524 if (isHoverAction) {
1525 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001526 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527#if DEBUG_FOCUS
1528 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1529#endif
1530 *outConflictingPointerActions = true;
1531 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001532 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1534 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001535 mTempTouchState.deviceId = entry->deviceId;
1536 mTempTouchState.source = entry->source;
1537 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 }
1539 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1540 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1541 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001542 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001543 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1544 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001545 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546#if DEBUG_FOCUS
1547 ALOGD("Conflicting pointer actions: Down received while already down.");
1548#endif
1549 *outConflictingPointerActions = true;
1550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1552 // One pointer went up.
1553 if (isSplit) {
1554 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1555 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1556
1557 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1558 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1559 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1560 touchedWindow.pointerIds.clearBit(pointerId);
1561 if (touchedWindow.pointerIds.isEmpty()) {
1562 mTempTouchState.windows.removeAt(i);
1563 continue;
1564 }
1565 }
1566 i += 1;
1567 }
1568 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001569 }
1570
1571 // Save changes unless the action was scroll in which case the temporary touch
1572 // state was only valid for this one action.
1573 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1574 if (mTempTouchState.displayId >= 0) {
1575 if (oldStateIndex >= 0) {
1576 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1577 } else {
1578 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1579 }
1580 } else if (oldStateIndex >= 0) {
1581 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 }
1584
1585 // Update hover state.
1586 mLastHoverWindowHandle = newHoverWindowHandle;
1587 }
1588 } else {
1589#if DEBUG_FOCUS
1590 ALOGD("Not updating touch focus because injection was denied.");
1591#endif
1592 }
1593
1594Unresponsive:
1595 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1596 mTempTouchState.reset();
1597
1598 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1599 updateDispatchStatisticsLocked(currentTime, entry,
1600 injectionResult, timeSpentWaitingForApplication);
1601#if DEBUG_FOCUS
1602 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1603 "timeSpentWaitingForApplication=%0.1fms",
1604 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1605#endif
1606 return injectionResult;
1607}
1608
1609void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1610 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1611 inputTargets.push();
1612
1613 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1614 InputTarget& target = inputTargets.editTop();
1615 target.inputChannel = windowInfo->inputChannel;
1616 target.flags = targetFlags;
1617 target.xOffset = - windowInfo->frameLeft;
1618 target.yOffset = - windowInfo->frameTop;
1619 target.scaleFactor = windowInfo->scaleFactor;
1620 target.pointerIds = pointerIds;
1621}
1622
1623void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
1624 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1625 inputTargets.push();
1626
1627 InputTarget& target = inputTargets.editTop();
1628 target.inputChannel = mMonitoringChannels[i];
1629 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1630 target.xOffset = 0;
1631 target.yOffset = 0;
1632 target.pointerIds.clear();
1633 target.scaleFactor = 1.0f;
1634 }
1635}
1636
1637bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1638 const InjectionState* injectionState) {
1639 if (injectionState
1640 && (windowHandle == NULL
1641 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1642 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1643 if (windowHandle != NULL) {
1644 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1645 "owned by uid %d",
1646 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001647 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 windowHandle->getInfo()->ownerUid);
1649 } else {
1650 ALOGW("Permission denied: injecting event from pid %d uid %d",
1651 injectionState->injectorPid, injectionState->injectorUid);
1652 }
1653 return false;
1654 }
1655 return true;
1656}
1657
1658bool InputDispatcher::isWindowObscuredAtPointLocked(
1659 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1660 int32_t displayId = windowHandle->getInfo()->displayId;
1661 size_t numWindows = mWindowHandles.size();
1662 for (size_t i = 0; i < numWindows; i++) {
1663 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1664 if (otherHandle == windowHandle) {
1665 break;
1666 }
1667
1668 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1669 if (otherInfo->displayId == displayId
1670 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1671 && otherInfo->frameContainsPoint(x, y)) {
1672 return true;
1673 }
1674 }
1675 return false;
1676}
1677
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001678
1679bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1680 int32_t displayId = windowHandle->getInfo()->displayId;
1681 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1682 size_t numWindows = mWindowHandles.size();
1683 for (size_t i = 0; i < numWindows; i++) {
1684 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1685 if (otherHandle == windowHandle) {
1686 break;
1687 }
1688
1689 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1690 if (otherInfo->displayId == displayId
1691 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1692 && otherInfo->overlaps(windowInfo)) {
1693 return true;
1694 }
1695 }
1696 return false;
1697}
1698
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001699std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001700 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1701 const char* targetType) {
1702 // If the window is paused then keep waiting.
1703 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001704 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001705 }
1706
1707 // If the window's connection is not registered then keep waiting.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brownffb49772014-10-10 19:01:34 -07001709 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001710 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001711 "registered with the input dispatcher. The window may be in the process "
1712 "of being removed.", targetType);
1713 }
1714
1715 // If the connection is dead then keep waiting.
1716 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1717 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001718 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001719 "The window may be in the process of being removed.", targetType,
1720 connection->getStatusLabel());
1721 }
1722
1723 // If the connection is backed up then keep waiting.
1724 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001725 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001726 "Outbound queue length: %d. Wait queue length: %d.",
1727 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1728 }
1729
1730 // Ensure that the dispatch queues aren't too far backed up for this event.
1731 if (eventEntry->type == EventEntry::TYPE_KEY) {
1732 // If the event is a key event, then we must wait for all previous events to
1733 // complete before delivering it because previous events may have the
1734 // side-effect of transferring focus to a different window and we want to
1735 // ensure that the following keys are sent to the new window.
1736 //
1737 // Suppose the user touches a button in a window then immediately presses "A".
1738 // If the button causes a pop-up window to appear then we want to ensure that
1739 // the "A" key is delivered to the new pop-up window. This is because users
1740 // often anticipate pending UI changes when typing on a keyboard.
1741 // To obtain this behavior, we must serialize key events with respect to all
1742 // prior input events.
1743 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001744 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001745 "finished processing all of the input events that were previously "
1746 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1747 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001748 }
Jeff Brownffb49772014-10-10 19:01:34 -07001749 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 // Touch events can always be sent to a window immediately because the user intended
1751 // to touch whatever was visible at the time. Even if focus changes or a new
1752 // window appears moments later, the touch event was meant to be delivered to
1753 // whatever window happened to be on screen at the time.
1754 //
1755 // Generic motion events, such as trackball or joystick events are a little trickier.
1756 // Like key events, generic motion events are delivered to the focused window.
1757 // Unlike key events, generic motion events don't tend to transfer focus to other
1758 // windows and it is not important for them to be serialized. So we prefer to deliver
1759 // generic motion events as soon as possible to improve efficiency and reduce lag
1760 // through batching.
1761 //
1762 // The one case where we pause input event delivery is when the wait queue is piling
1763 // up with lots of events because the application is not responding.
1764 // This condition ensures that ANRs are detected reliably.
1765 if (!connection->waitQueue.isEmpty()
1766 && currentTime >= connection->waitQueue.head->deliveryTime
1767 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001768 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001769 "finished processing certain input events that were delivered to it over "
1770 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1771 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1772 connection->waitQueue.count(),
1773 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 }
1775 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001776 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001777}
1778
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001779std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 const sp<InputApplicationHandle>& applicationHandle,
1781 const sp<InputWindowHandle>& windowHandle) {
1782 if (applicationHandle != NULL) {
1783 if (windowHandle != NULL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001784 std::string label(applicationHandle->getName());
1785 label += " - ";
1786 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001787 return label;
1788 } else {
1789 return applicationHandle->getName();
1790 }
1791 } else if (windowHandle != NULL) {
1792 return windowHandle->getName();
1793 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001794 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 }
1796}
1797
1798void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
1799 if (mFocusedWindowHandle != NULL) {
1800 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1801 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1802#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001803 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804#endif
1805 return;
1806 }
1807 }
1808
1809 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1810 switch (eventEntry->type) {
1811 case EventEntry::TYPE_MOTION: {
1812 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1813 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1814 return;
1815 }
1816
1817 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1818 eventType = USER_ACTIVITY_EVENT_TOUCH;
1819 }
1820 break;
1821 }
1822 case EventEntry::TYPE_KEY: {
1823 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1824 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1825 return;
1826 }
1827 eventType = USER_ACTIVITY_EVENT_BUTTON;
1828 break;
1829 }
1830 }
1831
1832 CommandEntry* commandEntry = postCommandLocked(
1833 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1834 commandEntry->eventTime = eventEntry->eventTime;
1835 commandEntry->userActivityEventType = eventType;
1836}
1837
1838void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1839 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1840#if DEBUG_DISPATCH_CYCLE
1841 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1842 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1843 "pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001844 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 inputTarget->xOffset, inputTarget->yOffset,
1846 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1847#endif
1848
1849 // Skip this event if the connection status is not normal.
1850 // We don't want to enqueue additional outbound events if the connection is broken.
1851 if (connection->status != Connection::STATUS_NORMAL) {
1852#if DEBUG_DISPATCH_CYCLE
1853 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001854 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855#endif
1856 return;
1857 }
1858
1859 // Split a motion event if needed.
1860 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1861 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1862
1863 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1864 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1865 MotionEntry* splitMotionEntry = splitMotionEvent(
1866 originalMotionEntry, inputTarget->pointerIds);
1867 if (!splitMotionEntry) {
1868 return; // split event was dropped
1869 }
1870#if DEBUG_FOCUS
1871 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001872 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1874#endif
1875 enqueueDispatchEntriesLocked(currentTime, connection,
1876 splitMotionEntry, inputTarget);
1877 splitMotionEntry->release();
1878 return;
1879 }
1880 }
1881
1882 // Not splitting. Enqueue dispatch entries for the event as is.
1883 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1884}
1885
1886void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1887 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1888 bool wasEmpty = connection->outboundQueue.isEmpty();
1889
1890 // Enqueue dispatch entries for the requested modes.
1891 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1892 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1893 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1894 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1895 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1896 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1897 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1898 InputTarget::FLAG_DISPATCH_AS_IS);
1899 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1900 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1901 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1902 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1903
1904 // If the outbound queue was previously empty, start the dispatch cycle going.
1905 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1906 startDispatchCycleLocked(currentTime, connection);
1907 }
1908}
1909
1910void InputDispatcher::enqueueDispatchEntryLocked(
1911 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1912 int32_t dispatchMode) {
1913 int32_t inputTargetFlags = inputTarget->flags;
1914 if (!(inputTargetFlags & dispatchMode)) {
1915 return;
1916 }
1917 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1918
1919 // This is a new event.
1920 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1921 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1922 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1923 inputTarget->scaleFactor);
1924
1925 // Apply target flags and update the connection's input state.
1926 switch (eventEntry->type) {
1927 case EventEntry::TYPE_KEY: {
1928 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1929 dispatchEntry->resolvedAction = keyEntry->action;
1930 dispatchEntry->resolvedFlags = keyEntry->flags;
1931
1932 if (!connection->inputState.trackKey(keyEntry,
1933 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1934#if DEBUG_DISPATCH_CYCLE
1935 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001936 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937#endif
1938 delete dispatchEntry;
1939 return; // skip the inconsistent event
1940 }
1941 break;
1942 }
1943
1944 case EventEntry::TYPE_MOTION: {
1945 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1946 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1947 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1948 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1949 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1950 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1951 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1952 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1953 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1954 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1955 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1956 } else {
1957 dispatchEntry->resolvedAction = motionEntry->action;
1958 }
1959 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1960 && !connection->inputState.isHovering(
1961 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
1962#if DEBUG_DISPATCH_CYCLE
1963 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001964 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965#endif
1966 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1967 }
1968
1969 dispatchEntry->resolvedFlags = motionEntry->flags;
1970 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1971 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1972 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001973 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
1974 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1975 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976
1977 if (!connection->inputState.trackMotion(motionEntry,
1978 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1979#if DEBUG_DISPATCH_CYCLE
1980 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001981 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982#endif
1983 delete dispatchEntry;
1984 return; // skip the inconsistent event
1985 }
1986 break;
1987 }
1988 }
1989
1990 // Remember that we are waiting for this dispatch to complete.
1991 if (dispatchEntry->hasForegroundTarget()) {
1992 incrementPendingForegroundDispatchesLocked(eventEntry);
1993 }
1994
1995 // Enqueue the dispatch entry.
1996 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1997 traceOutboundQueueLengthLocked(connection);
1998}
1999
2000void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2001 const sp<Connection>& connection) {
2002#if DEBUG_DISPATCH_CYCLE
2003 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002004 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005#endif
2006
2007 while (connection->status == Connection::STATUS_NORMAL
2008 && !connection->outboundQueue.isEmpty()) {
2009 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2010 dispatchEntry->deliveryTime = currentTime;
2011
2012 // Publish the event.
2013 status_t status;
2014 EventEntry* eventEntry = dispatchEntry->eventEntry;
2015 switch (eventEntry->type) {
2016 case EventEntry::TYPE_KEY: {
2017 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2018
2019 // Publish the key event.
2020 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002021 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2023 keyEntry->keyCode, keyEntry->scanCode,
2024 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2025 keyEntry->eventTime);
2026 break;
2027 }
2028
2029 case EventEntry::TYPE_MOTION: {
2030 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2031
2032 PointerCoords scaledCoords[MAX_POINTERS];
2033 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2034
2035 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002036 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2038 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002039 float scaleFactor = dispatchEntry->scaleFactor;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 xOffset = dispatchEntry->xOffset * scaleFactor;
2041 yOffset = dispatchEntry->yOffset * scaleFactor;
2042 if (scaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002043 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 scaledCoords[i] = motionEntry->pointerCoords[i];
2045 scaledCoords[i].scale(scaleFactor);
2046 }
2047 usingCoords = scaledCoords;
2048 }
2049 } else {
2050 xOffset = 0.0f;
2051 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052
2053 // We don't want the dispatch target to know.
2054 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002055 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056 scaledCoords[i].clear();
2057 }
2058 usingCoords = scaledCoords;
2059 }
2060 }
2061
2062 // Publish the motion event.
2063 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002064 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002065 dispatchEntry->resolvedAction, motionEntry->actionButton,
2066 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2067 motionEntry->metaState, motionEntry->buttonState,
2068 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 motionEntry->downTime, motionEntry->eventTime,
2070 motionEntry->pointerCount, motionEntry->pointerProperties,
2071 usingCoords);
2072 break;
2073 }
2074
2075 default:
2076 ALOG_ASSERT(false);
2077 return;
2078 }
2079
2080 // Check the result.
2081 if (status) {
2082 if (status == WOULD_BLOCK) {
2083 if (connection->waitQueue.isEmpty()) {
2084 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2085 "This is unexpected because the wait queue is empty, so the pipe "
2086 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002087 "event to it, status=%d", connection->getInputChannelName().c_str(),
2088 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2090 } else {
2091 // Pipe is full and we are waiting for the app to finish process some events
2092 // before sending more events to it.
2093#if DEBUG_DISPATCH_CYCLE
2094 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2095 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002096 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097#endif
2098 connection->inputPublisherBlocked = true;
2099 }
2100 } else {
2101 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002102 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2104 }
2105 return;
2106 }
2107
2108 // Re-enqueue the event on the wait queue.
2109 connection->outboundQueue.dequeue(dispatchEntry);
2110 traceOutboundQueueLengthLocked(connection);
2111 connection->waitQueue.enqueueAtTail(dispatchEntry);
2112 traceWaitQueueLengthLocked(connection);
2113 }
2114}
2115
2116void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2117 const sp<Connection>& connection, uint32_t seq, bool handled) {
2118#if DEBUG_DISPATCH_CYCLE
2119 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002120 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121#endif
2122
2123 connection->inputPublisherBlocked = false;
2124
2125 if (connection->status == Connection::STATUS_BROKEN
2126 || connection->status == Connection::STATUS_ZOMBIE) {
2127 return;
2128 }
2129
2130 // Notify other system components and prepare to start the next dispatch cycle.
2131 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2132}
2133
2134void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2135 const sp<Connection>& connection, bool notify) {
2136#if DEBUG_DISPATCH_CYCLE
2137 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002138 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139#endif
2140
2141 // Clear the dispatch queues.
2142 drainDispatchQueueLocked(&connection->outboundQueue);
2143 traceOutboundQueueLengthLocked(connection);
2144 drainDispatchQueueLocked(&connection->waitQueue);
2145 traceWaitQueueLengthLocked(connection);
2146
2147 // The connection appears to be unrecoverably broken.
2148 // Ignore already broken or zombie connections.
2149 if (connection->status == Connection::STATUS_NORMAL) {
2150 connection->status = Connection::STATUS_BROKEN;
2151
2152 if (notify) {
2153 // Notify other system components.
2154 onDispatchCycleBrokenLocked(currentTime, connection);
2155 }
2156 }
2157}
2158
2159void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2160 while (!queue->isEmpty()) {
2161 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2162 releaseDispatchEntryLocked(dispatchEntry);
2163 }
2164}
2165
2166void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2167 if (dispatchEntry->hasForegroundTarget()) {
2168 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2169 }
2170 delete dispatchEntry;
2171}
2172
2173int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2174 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2175
2176 { // acquire lock
2177 AutoMutex _l(d->mLock);
2178
2179 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2180 if (connectionIndex < 0) {
2181 ALOGE("Received spurious receive callback for unknown input channel. "
2182 "fd=%d, events=0x%x", fd, events);
2183 return 0; // remove the callback
2184 }
2185
2186 bool notify;
2187 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2188 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2189 if (!(events & ALOOPER_EVENT_INPUT)) {
2190 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002191 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 return 1;
2193 }
2194
2195 nsecs_t currentTime = now();
2196 bool gotOne = false;
2197 status_t status;
2198 for (;;) {
2199 uint32_t seq;
2200 bool handled;
2201 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2202 if (status) {
2203 break;
2204 }
2205 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2206 gotOne = true;
2207 }
2208 if (gotOne) {
2209 d->runCommandsLockedInterruptible();
2210 if (status == WOULD_BLOCK) {
2211 return 1;
2212 }
2213 }
2214
2215 notify = status != DEAD_OBJECT || !connection->monitor;
2216 if (notify) {
2217 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002218 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 }
2220 } else {
2221 // Monitor channels are never explicitly unregistered.
2222 // We do it automatically when the remote endpoint is closed so don't warn
2223 // about them.
2224 notify = !connection->monitor;
2225 if (notify) {
2226 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002227 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228 }
2229 }
2230
2231 // Unregister the channel.
2232 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2233 return 0; // remove the callback
2234 } // release lock
2235}
2236
2237void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2238 const CancelationOptions& options) {
2239 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2240 synthesizeCancelationEventsForConnectionLocked(
2241 mConnectionsByFd.valueAt(i), options);
2242 }
2243}
2244
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002245void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2246 const CancelationOptions& options) {
2247 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2248 synthesizeCancelationEventsForInputChannelLocked(mMonitoringChannels[i], options);
2249 }
2250}
2251
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2253 const sp<InputChannel>& channel, const CancelationOptions& options) {
2254 ssize_t index = getConnectionIndexLocked(channel);
2255 if (index >= 0) {
2256 synthesizeCancelationEventsForConnectionLocked(
2257 mConnectionsByFd.valueAt(index), options);
2258 }
2259}
2260
2261void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2262 const sp<Connection>& connection, const CancelationOptions& options) {
2263 if (connection->status == Connection::STATUS_BROKEN) {
2264 return;
2265 }
2266
2267 nsecs_t currentTime = now();
2268
2269 Vector<EventEntry*> cancelationEvents;
2270 connection->inputState.synthesizeCancelationEvents(currentTime,
2271 cancelationEvents, options);
2272
2273 if (!cancelationEvents.isEmpty()) {
2274#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002275 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002277 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 options.reason, options.mode);
2279#endif
2280 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2281 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2282 switch (cancelationEventEntry->type) {
2283 case EventEntry::TYPE_KEY:
2284 logOutboundKeyDetailsLocked("cancel - ",
2285 static_cast<KeyEntry*>(cancelationEventEntry));
2286 break;
2287 case EventEntry::TYPE_MOTION:
2288 logOutboundMotionDetailsLocked("cancel - ",
2289 static_cast<MotionEntry*>(cancelationEventEntry));
2290 break;
2291 }
2292
2293 InputTarget target;
2294 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2295 if (windowHandle != NULL) {
2296 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2297 target.xOffset = -windowInfo->frameLeft;
2298 target.yOffset = -windowInfo->frameTop;
2299 target.scaleFactor = windowInfo->scaleFactor;
2300 } else {
2301 target.xOffset = 0;
2302 target.yOffset = 0;
2303 target.scaleFactor = 1.0f;
2304 }
2305 target.inputChannel = connection->inputChannel;
2306 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2307
2308 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2309 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2310
2311 cancelationEventEntry->release();
2312 }
2313
2314 startDispatchCycleLocked(currentTime, connection);
2315 }
2316}
2317
2318InputDispatcher::MotionEntry*
2319InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2320 ALOG_ASSERT(pointerIds.value != 0);
2321
2322 uint32_t splitPointerIndexMap[MAX_POINTERS];
2323 PointerProperties splitPointerProperties[MAX_POINTERS];
2324 PointerCoords splitPointerCoords[MAX_POINTERS];
2325
2326 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2327 uint32_t splitPointerCount = 0;
2328
2329 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2330 originalPointerIndex++) {
2331 const PointerProperties& pointerProperties =
2332 originalMotionEntry->pointerProperties[originalPointerIndex];
2333 uint32_t pointerId = uint32_t(pointerProperties.id);
2334 if (pointerIds.hasBit(pointerId)) {
2335 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2336 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2337 splitPointerCoords[splitPointerCount].copyFrom(
2338 originalMotionEntry->pointerCoords[originalPointerIndex]);
2339 splitPointerCount += 1;
2340 }
2341 }
2342
2343 if (splitPointerCount != pointerIds.count()) {
2344 // This is bad. We are missing some of the pointers that we expected to deliver.
2345 // Most likely this indicates that we received an ACTION_MOVE events that has
2346 // different pointer ids than we expected based on the previous ACTION_DOWN
2347 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2348 // in this way.
2349 ALOGW("Dropping split motion event because the pointer count is %d but "
2350 "we expected there to be %d pointers. This probably means we received "
2351 "a broken sequence of pointer ids from the input device.",
2352 splitPointerCount, pointerIds.count());
2353 return NULL;
2354 }
2355
2356 int32_t action = originalMotionEntry->action;
2357 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2358 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2359 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2360 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2361 const PointerProperties& pointerProperties =
2362 originalMotionEntry->pointerProperties[originalPointerIndex];
2363 uint32_t pointerId = uint32_t(pointerProperties.id);
2364 if (pointerIds.hasBit(pointerId)) {
2365 if (pointerIds.count() == 1) {
2366 // The first/last pointer went down/up.
2367 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2368 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2369 } else {
2370 // A secondary pointer went down/up.
2371 uint32_t splitPointerIndex = 0;
2372 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2373 splitPointerIndex += 1;
2374 }
2375 action = maskedAction | (splitPointerIndex
2376 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2377 }
2378 } else {
2379 // An unrelated pointer changed.
2380 action = AMOTION_EVENT_ACTION_MOVE;
2381 }
2382 }
2383
2384 MotionEntry* splitMotionEntry = new MotionEntry(
2385 originalMotionEntry->eventTime,
2386 originalMotionEntry->deviceId,
2387 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002388 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 originalMotionEntry->policyFlags,
2390 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002391 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 originalMotionEntry->flags,
2393 originalMotionEntry->metaState,
2394 originalMotionEntry->buttonState,
2395 originalMotionEntry->edgeFlags,
2396 originalMotionEntry->xPrecision,
2397 originalMotionEntry->yPrecision,
2398 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002399 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400
2401 if (originalMotionEntry->injectionState) {
2402 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2403 splitMotionEntry->injectionState->refCount += 1;
2404 }
2405
2406 return splitMotionEntry;
2407}
2408
2409void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2410#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002411 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412#endif
2413
2414 bool needWake;
2415 { // acquire lock
2416 AutoMutex _l(mLock);
2417
2418 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2419 needWake = enqueueInboundEventLocked(newEntry);
2420 } // release lock
2421
2422 if (needWake) {
2423 mLooper->wake();
2424 }
2425}
2426
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002427/**
2428 * If one of the meta shortcuts is detected, process them here:
2429 * Meta + Backspace -> generate BACK
2430 * Meta + Enter -> generate HOME
2431 * This will potentially overwrite keyCode and metaState.
2432 */
2433void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2434 int32_t& keyCode, int32_t& metaState) {
2435 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2436 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2437 if (keyCode == AKEYCODE_DEL) {
2438 newKeyCode = AKEYCODE_BACK;
2439 } else if (keyCode == AKEYCODE_ENTER) {
2440 newKeyCode = AKEYCODE_HOME;
2441 }
2442 if (newKeyCode != AKEYCODE_UNKNOWN) {
2443 AutoMutex _l(mLock);
2444 struct KeyReplacement replacement = {keyCode, deviceId};
2445 mReplacedKeys.add(replacement, newKeyCode);
2446 keyCode = newKeyCode;
2447 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2448 }
2449 } else if (action == AKEY_EVENT_ACTION_UP) {
2450 // In order to maintain a consistent stream of up and down events, check to see if the key
2451 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2452 // even if the modifier was released between the down and the up events.
2453 AutoMutex _l(mLock);
2454 struct KeyReplacement replacement = {keyCode, deviceId};
2455 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2456 if (index >= 0) {
2457 keyCode = mReplacedKeys.valueAt(index);
2458 mReplacedKeys.removeItemsAt(index);
2459 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2460 }
2461 }
2462}
2463
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2465#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002466 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002467 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002468 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002469 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 args->action, args->flags, args->keyCode, args->scanCode,
2471 args->metaState, args->downTime);
2472#endif
2473 if (!validateKeyEvent(args->action)) {
2474 return;
2475 }
2476
2477 uint32_t policyFlags = args->policyFlags;
2478 int32_t flags = args->flags;
2479 int32_t metaState = args->metaState;
2480 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2481 policyFlags |= POLICY_FLAG_VIRTUAL;
2482 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 if (policyFlags & POLICY_FLAG_FUNCTION) {
2485 metaState |= AMETA_FUNCTION_ON;
2486 }
2487
2488 policyFlags |= POLICY_FLAG_TRUSTED;
2489
Michael Wright78f24442014-08-06 15:55:28 -07002490 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002491 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002492
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002494 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Michael Wright78f24442014-08-06 15:55:28 -07002495 flags, keyCode, args->scanCode, metaState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 args->downTime, args->eventTime);
2497
Michael Wright2b3c3302018-03-02 17:19:13 +00002498 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002500 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2501 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2502 std::to_string(t.duration().count()).c_str());
2503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 bool needWake;
2506 { // acquire lock
2507 mLock.lock();
2508
2509 if (shouldSendKeyToInputFilterLocked(args)) {
2510 mLock.unlock();
2511
2512 policyFlags |= POLICY_FLAG_FILTERED;
2513 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2514 return; // event was consumed by the filter
2515 }
2516
2517 mLock.lock();
2518 }
2519
2520 int32_t repeatCount = 0;
2521 KeyEntry* newEntry = new KeyEntry(args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002522 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002523 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002524 metaState, repeatCount, args->downTime);
2525
2526 needWake = enqueueInboundEventLocked(newEntry);
2527 mLock.unlock();
2528 } // release lock
2529
2530 if (needWake) {
2531 mLooper->wake();
2532 }
2533}
2534
2535bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2536 return mInputFilterEnabled;
2537}
2538
2539void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2540#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002541 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2542 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002543 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002544 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002545 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002546 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2548 for (uint32_t i = 0; i < args->pointerCount; i++) {
2549 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2550 "x=%f, y=%f, pressure=%f, size=%f, "
2551 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2552 "orientation=%f",
2553 i, args->pointerProperties[i].id,
2554 args->pointerProperties[i].toolType,
2555 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2556 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2557 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2558 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2559 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2560 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2561 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2562 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2563 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2564 }
2565#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002566 if (!validateMotionEvent(args->action, args->actionButton,
2567 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 return;
2569 }
2570
2571 uint32_t policyFlags = args->policyFlags;
2572 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002573
2574 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002576 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2577 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2578 std::to_string(t.duration().count()).c_str());
2579 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580
2581 bool needWake;
2582 { // acquire lock
2583 mLock.lock();
2584
2585 if (shouldSendMotionToInputFilterLocked(args)) {
2586 mLock.unlock();
2587
2588 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002589 event.initialize(args->deviceId, args->source, args->displayId,
2590 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002591 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2592 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 args->downTime, args->eventTime,
2594 args->pointerCount, args->pointerProperties, args->pointerCoords);
2595
2596 policyFlags |= POLICY_FLAG_FILTERED;
2597 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2598 return; // event was consumed by the filter
2599 }
2600
2601 mLock.lock();
2602 }
2603
2604 // Just enqueue a new motion event.
2605 MotionEntry* newEntry = new MotionEntry(args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002606 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002607 args->action, args->actionButton, args->flags,
2608 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002610 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002611
2612 needWake = enqueueInboundEventLocked(newEntry);
2613 mLock.unlock();
2614 } // release lock
2615
2616 if (needWake) {
2617 mLooper->wake();
2618 }
2619}
2620
2621bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2622 // TODO: support sending secondary display events to input filter
2623 return mInputFilterEnabled && isMainDisplay(args->displayId);
2624}
2625
2626void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2627#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002628 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2629 "switchMask=0x%08x",
2630 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631#endif
2632
2633 uint32_t policyFlags = args->policyFlags;
2634 policyFlags |= POLICY_FLAG_TRUSTED;
2635 mPolicy->notifySwitch(args->eventTime,
2636 args->switchValues, args->switchMask, policyFlags);
2637}
2638
2639void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2640#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002641 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 args->eventTime, args->deviceId);
2643#endif
2644
2645 bool needWake;
2646 { // acquire lock
2647 AutoMutex _l(mLock);
2648
2649 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2650 needWake = enqueueInboundEventLocked(newEntry);
2651 } // release lock
2652
2653 if (needWake) {
2654 mLooper->wake();
2655 }
2656}
2657
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002658int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2660 uint32_t policyFlags) {
2661#if DEBUG_INBOUND_EVENT_DETAILS
2662 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002663 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2664 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665#endif
2666
2667 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2668
2669 policyFlags |= POLICY_FLAG_INJECTED;
2670 if (hasInjectionPermission(injectorPid, injectorUid)) {
2671 policyFlags |= POLICY_FLAG_TRUSTED;
2672 }
2673
2674 EventEntry* firstInjectedEntry;
2675 EventEntry* lastInjectedEntry;
2676 switch (event->getType()) {
2677 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002678 KeyEvent keyEvent;
2679 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2680 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 if (! validateKeyEvent(action)) {
2682 return INPUT_EVENT_INJECTION_FAILED;
2683 }
2684
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002685 int32_t flags = keyEvent.getFlags();
2686 int32_t keyCode = keyEvent.getKeyCode();
2687 int32_t metaState = keyEvent.getMetaState();
2688 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2689 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002690 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
2691 action, flags, keyCode, keyEvent.getScanCode(), metaState, 0,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002692 keyEvent.getDownTime(), keyEvent.getEventTime());
2693
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2695 policyFlags |= POLICY_FLAG_VIRTUAL;
2696 }
2697
2698 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002699 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002700 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002701 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2702 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2703 std::to_string(t.duration().count()).c_str());
2704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705 }
2706
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 mLock.lock();
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002708 firstInjectedEntry = new KeyEntry(keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002709 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002711 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2712 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 lastInjectedEntry = firstInjectedEntry;
2714 break;
2715 }
2716
2717 case AINPUT_EVENT_TYPE_MOTION: {
2718 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719 int32_t action = motionEvent->getAction();
2720 size_t pointerCount = motionEvent->getPointerCount();
2721 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002722 int32_t actionButton = motionEvent->getActionButton();
2723 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724 return INPUT_EVENT_INJECTION_FAILED;
2725 }
2726
2727 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2728 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002729 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002731 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2732 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2733 std::to_string(t.duration().count()).c_str());
2734 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 }
2736
2737 mLock.lock();
2738 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2739 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2740 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002741 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2742 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002743 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 motionEvent->getMetaState(), motionEvent->getButtonState(),
2745 motionEvent->getEdgeFlags(),
2746 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002747 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002748 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2749 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 lastInjectedEntry = firstInjectedEntry;
2751 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2752 sampleEventTimes += 1;
2753 samplePointerCoords += pointerCount;
2754 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002755 motionEvent->getDeviceId(), motionEvent->getSource(),
2756 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002757 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 motionEvent->getMetaState(), motionEvent->getButtonState(),
2759 motionEvent->getEdgeFlags(),
2760 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002761 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002762 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2763 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764 lastInjectedEntry->next = nextInjectedEntry;
2765 lastInjectedEntry = nextInjectedEntry;
2766 }
2767 break;
2768 }
2769
2770 default:
2771 ALOGW("Cannot inject event of type %d", event->getType());
2772 return INPUT_EVENT_INJECTION_FAILED;
2773 }
2774
2775 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2776 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2777 injectionState->injectionIsAsync = true;
2778 }
2779
2780 injectionState->refCount += 1;
2781 lastInjectedEntry->injectionState = injectionState;
2782
2783 bool needWake = false;
2784 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2785 EventEntry* nextEntry = entry->next;
2786 needWake |= enqueueInboundEventLocked(entry);
2787 entry = nextEntry;
2788 }
2789
2790 mLock.unlock();
2791
2792 if (needWake) {
2793 mLooper->wake();
2794 }
2795
2796 int32_t injectionResult;
2797 { // acquire lock
2798 AutoMutex _l(mLock);
2799
2800 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2801 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2802 } else {
2803 for (;;) {
2804 injectionResult = injectionState->injectionResult;
2805 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2806 break;
2807 }
2808
2809 nsecs_t remainingTimeout = endTime - now();
2810 if (remainingTimeout <= 0) {
2811#if DEBUG_INJECTION
2812 ALOGD("injectInputEvent - Timed out waiting for injection result "
2813 "to become available.");
2814#endif
2815 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2816 break;
2817 }
2818
2819 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2820 }
2821
2822 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2823 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2824 while (injectionState->pendingForegroundDispatches != 0) {
2825#if DEBUG_INJECTION
2826 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2827 injectionState->pendingForegroundDispatches);
2828#endif
2829 nsecs_t remainingTimeout = endTime - now();
2830 if (remainingTimeout <= 0) {
2831#if DEBUG_INJECTION
2832 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2833 "dispatches to finish.");
2834#endif
2835 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2836 break;
2837 }
2838
2839 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2840 }
2841 }
2842 }
2843
2844 injectionState->release();
2845 } // release lock
2846
2847#if DEBUG_INJECTION
2848 ALOGD("injectInputEvent - Finished with result %d. "
2849 "injectorPid=%d, injectorUid=%d",
2850 injectionResult, injectorPid, injectorUid);
2851#endif
2852
2853 return injectionResult;
2854}
2855
2856bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2857 return injectorUid == 0
2858 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2859}
2860
2861void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2862 InjectionState* injectionState = entry->injectionState;
2863 if (injectionState) {
2864#if DEBUG_INJECTION
2865 ALOGD("Setting input event injection result to %d. "
2866 "injectorPid=%d, injectorUid=%d",
2867 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2868#endif
2869
2870 if (injectionState->injectionIsAsync
2871 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2872 // Log the outcome since the injector did not wait for the injection result.
2873 switch (injectionResult) {
2874 case INPUT_EVENT_INJECTION_SUCCEEDED:
2875 ALOGV("Asynchronous input event injection succeeded.");
2876 break;
2877 case INPUT_EVENT_INJECTION_FAILED:
2878 ALOGW("Asynchronous input event injection failed.");
2879 break;
2880 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2881 ALOGW("Asynchronous input event injection permission denied.");
2882 break;
2883 case INPUT_EVENT_INJECTION_TIMED_OUT:
2884 ALOGW("Asynchronous input event injection timed out.");
2885 break;
2886 }
2887 }
2888
2889 injectionState->injectionResult = injectionResult;
2890 mInjectionResultAvailableCondition.broadcast();
2891 }
2892}
2893
2894void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2895 InjectionState* injectionState = entry->injectionState;
2896 if (injectionState) {
2897 injectionState->pendingForegroundDispatches += 1;
2898 }
2899}
2900
2901void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2902 InjectionState* injectionState = entry->injectionState;
2903 if (injectionState) {
2904 injectionState->pendingForegroundDispatches -= 1;
2905
2906 if (injectionState->pendingForegroundDispatches == 0) {
2907 mInjectionSyncFinishedCondition.broadcast();
2908 }
2909 }
2910}
2911
2912sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2913 const sp<InputChannel>& inputChannel) const {
2914 size_t numWindows = mWindowHandles.size();
2915 for (size_t i = 0; i < numWindows; i++) {
2916 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2917 if (windowHandle->getInputChannel() == inputChannel) {
2918 return windowHandle;
2919 }
2920 }
2921 return NULL;
2922}
2923
2924bool InputDispatcher::hasWindowHandleLocked(
2925 const sp<InputWindowHandle>& windowHandle) const {
2926 size_t numWindows = mWindowHandles.size();
2927 for (size_t i = 0; i < numWindows; i++) {
2928 if (mWindowHandles.itemAt(i) == windowHandle) {
2929 return true;
2930 }
2931 }
2932 return false;
2933}
2934
2935void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
2936#if DEBUG_FOCUS
2937 ALOGD("setInputWindows");
2938#endif
2939 { // acquire lock
2940 AutoMutex _l(mLock);
2941
2942 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
2943 mWindowHandles = inputWindowHandles;
2944
2945 sp<InputWindowHandle> newFocusedWindowHandle;
2946 bool foundHoveredWindow = false;
2947 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2948 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2949 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
2950 mWindowHandles.removeAt(i--);
2951 continue;
2952 }
2953 if (windowHandle->getInfo()->hasFocus) {
2954 newFocusedWindowHandle = windowHandle;
2955 }
2956 if (windowHandle == mLastHoverWindowHandle) {
2957 foundHoveredWindow = true;
2958 }
2959 }
2960
2961 if (!foundHoveredWindow) {
2962 mLastHoverWindowHandle = NULL;
2963 }
2964
2965 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2966 if (mFocusedWindowHandle != NULL) {
2967#if DEBUG_FOCUS
2968 ALOGD("Focus left window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002969 mFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002970#endif
2971 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2972 if (focusedInputChannel != NULL) {
2973 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2974 "focus left window");
2975 synthesizeCancelationEventsForInputChannelLocked(
2976 focusedInputChannel, options);
2977 }
2978 }
2979 if (newFocusedWindowHandle != NULL) {
2980#if DEBUG_FOCUS
2981 ALOGD("Focus entered window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002982 newFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002983#endif
2984 }
2985 mFocusedWindowHandle = newFocusedWindowHandle;
2986 }
2987
Jeff Brownf086ddb2014-02-11 14:28:48 -08002988 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
2989 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
Ivan Lozano96f12992017-11-09 14:45:38 -08002990 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08002991 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
2992 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993#if DEBUG_FOCUS
Jeff Brownf086ddb2014-02-11 14:28:48 -08002994 ALOGD("Touched window was removed: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002995 touchedWindow.windowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002996#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08002997 sp<InputChannel> touchedInputChannel =
2998 touchedWindow.windowHandle->getInputChannel();
2999 if (touchedInputChannel != NULL) {
3000 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3001 "touched window was removed");
3002 synthesizeCancelationEventsForInputChannelLocked(
3003 touchedInputChannel, options);
3004 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003005 state.windows.removeAt(i);
3006 } else {
3007 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 }
3010 }
3011
3012 // Release information for windows that are no longer present.
3013 // This ensures that unused input channels are released promptly.
3014 // Otherwise, they might stick around until the window handle is destroyed
3015 // which might not happen until the next GC.
3016 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
3017 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
3018 if (!hasWindowHandleLocked(oldWindowHandle)) {
3019#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003020 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021#endif
3022 oldWindowHandle->releaseInfo();
3023 }
3024 }
3025 } // release lock
3026
3027 // Wake up poll loop since it may need to make new input dispatching choices.
3028 mLooper->wake();
3029}
3030
3031void InputDispatcher::setFocusedApplication(
3032 const sp<InputApplicationHandle>& inputApplicationHandle) {
3033#if DEBUG_FOCUS
3034 ALOGD("setFocusedApplication");
3035#endif
3036 { // acquire lock
3037 AutoMutex _l(mLock);
3038
3039 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
3040 if (mFocusedApplicationHandle != inputApplicationHandle) {
3041 if (mFocusedApplicationHandle != NULL) {
3042 resetANRTimeoutsLocked();
3043 mFocusedApplicationHandle->releaseInfo();
3044 }
3045 mFocusedApplicationHandle = inputApplicationHandle;
3046 }
3047 } else if (mFocusedApplicationHandle != NULL) {
3048 resetANRTimeoutsLocked();
3049 mFocusedApplicationHandle->releaseInfo();
3050 mFocusedApplicationHandle.clear();
3051 }
3052
3053#if DEBUG_FOCUS
3054 //logDispatchStateLocked();
3055#endif
3056 } // release lock
3057
3058 // Wake up poll loop since it may need to make new input dispatching choices.
3059 mLooper->wake();
3060}
3061
3062void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3063#if DEBUG_FOCUS
3064 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3065#endif
3066
3067 bool changed;
3068 { // acquire lock
3069 AutoMutex _l(mLock);
3070
3071 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3072 if (mDispatchFrozen && !frozen) {
3073 resetANRTimeoutsLocked();
3074 }
3075
3076 if (mDispatchEnabled && !enabled) {
3077 resetAndDropEverythingLocked("dispatcher is being disabled");
3078 }
3079
3080 mDispatchEnabled = enabled;
3081 mDispatchFrozen = frozen;
3082 changed = true;
3083 } else {
3084 changed = false;
3085 }
3086
3087#if DEBUG_FOCUS
3088 //logDispatchStateLocked();
3089#endif
3090 } // release lock
3091
3092 if (changed) {
3093 // Wake up poll loop since it may need to make new input dispatching choices.
3094 mLooper->wake();
3095 }
3096}
3097
3098void InputDispatcher::setInputFilterEnabled(bool enabled) {
3099#if DEBUG_FOCUS
3100 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3101#endif
3102
3103 { // acquire lock
3104 AutoMutex _l(mLock);
3105
3106 if (mInputFilterEnabled == enabled) {
3107 return;
3108 }
3109
3110 mInputFilterEnabled = enabled;
3111 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3112 } // release lock
3113
3114 // Wake up poll loop since there might be work to do to drop everything.
3115 mLooper->wake();
3116}
3117
3118bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3119 const sp<InputChannel>& toChannel) {
3120#if DEBUG_FOCUS
3121 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003122 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003123#endif
3124 { // acquire lock
3125 AutoMutex _l(mLock);
3126
3127 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3128 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3129 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
3130#if DEBUG_FOCUS
3131 ALOGD("Cannot transfer focus because from or to window not found.");
3132#endif
3133 return false;
3134 }
3135 if (fromWindowHandle == toWindowHandle) {
3136#if DEBUG_FOCUS
3137 ALOGD("Trivial transfer to same window.");
3138#endif
3139 return true;
3140 }
3141 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3142#if DEBUG_FOCUS
3143 ALOGD("Cannot transfer focus because windows are on different displays.");
3144#endif
3145 return false;
3146 }
3147
3148 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003149 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3150 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3151 for (size_t i = 0; i < state.windows.size(); i++) {
3152 const TouchedWindow& touchedWindow = state.windows[i];
3153 if (touchedWindow.windowHandle == fromWindowHandle) {
3154 int32_t oldTargetFlags = touchedWindow.targetFlags;
3155 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156
Jeff Brownf086ddb2014-02-11 14:28:48 -08003157 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158
Jeff Brownf086ddb2014-02-11 14:28:48 -08003159 int32_t newTargetFlags = oldTargetFlags
3160 & (InputTarget::FLAG_FOREGROUND
3161 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3162 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163
Jeff Brownf086ddb2014-02-11 14:28:48 -08003164 found = true;
3165 goto Found;
3166 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 }
3168 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003169Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170
3171 if (! found) {
3172#if DEBUG_FOCUS
3173 ALOGD("Focus transfer failed because from window did not have focus.");
3174#endif
3175 return false;
3176 }
3177
3178 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3179 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3180 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3181 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3182 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3183
3184 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3185 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3186 "transferring touch focus from this window to another window");
3187 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3188 }
3189
3190#if DEBUG_FOCUS
3191 logDispatchStateLocked();
3192#endif
3193 } // release lock
3194
3195 // Wake up poll loop since it may need to make new input dispatching choices.
3196 mLooper->wake();
3197 return true;
3198}
3199
3200void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3201#if DEBUG_FOCUS
3202 ALOGD("Resetting and dropping all events (%s).", reason);
3203#endif
3204
3205 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3206 synthesizeCancelationEventsForAllConnectionsLocked(options);
3207
3208 resetKeyRepeatLocked();
3209 releasePendingEventLocked();
3210 drainInboundQueueLocked();
3211 resetANRTimeoutsLocked();
3212
Jeff Brownf086ddb2014-02-11 14:28:48 -08003213 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003215 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216}
3217
3218void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003219 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 dumpDispatchStateLocked(dump);
3221
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003222 std::istringstream stream(dump);
3223 std::string line;
3224
3225 while (std::getline(stream, line, '\n')) {
3226 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 }
3228}
3229
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003230void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3231 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3232 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233
3234 if (mFocusedApplicationHandle != NULL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003235 dump += StringPrintf(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
3236 mFocusedApplicationHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 mFocusedApplicationHandle->getDispatchingTimeout(
3238 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3239 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003240 dump += StringPrintf(INDENT "FocusedApplication: <null>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003242 dump += StringPrintf(INDENT "FocusedWindow: name='%s'\n",
3243 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().c_str() : "<null>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244
Jeff Brownf086ddb2014-02-11 14:28:48 -08003245 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003246 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003247 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3248 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003249 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003250 state.displayId, toString(state.down), toString(state.split),
3251 state.deviceId, state.source);
3252 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003253 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003254 for (size_t i = 0; i < state.windows.size(); i++) {
3255 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003256 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3257 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003258 touchedWindow.pointerIds.value,
3259 touchedWindow.targetFlags);
3260 }
3261 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003262 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264 }
3265 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003266 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267 }
3268
3269 if (!mWindowHandles.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003270 dump += INDENT "Windows:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3272 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3273 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3274
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003275 dump += StringPrintf(INDENT2 "%zu: name='%s', displayId=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3277 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3278 "frame=[%d,%d][%d,%d], scale=%f, "
3279 "touchableRegion=",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003280 i, windowInfo->name.c_str(), windowInfo->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 toString(windowInfo->paused),
3282 toString(windowInfo->hasFocus),
3283 toString(windowInfo->hasWallpaper),
3284 toString(windowInfo->visible),
3285 toString(windowInfo->canReceiveKeys),
3286 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3287 windowInfo->layer,
3288 windowInfo->frameLeft, windowInfo->frameTop,
3289 windowInfo->frameRight, windowInfo->frameBottom,
3290 windowInfo->scaleFactor);
3291 dumpRegion(dump, windowInfo->touchableRegion);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003292 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3293 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294 windowInfo->ownerPid, windowInfo->ownerUid,
3295 windowInfo->dispatchingTimeout / 1000000.0);
3296 }
3297 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003298 dump += INDENT "Windows: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299 }
3300
3301 if (!mMonitoringChannels.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003302 dump += INDENT "MonitoringChannels:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3304 const sp<InputChannel>& channel = mMonitoringChannels[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003305 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306 }
3307 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003308 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 }
3310
3311 nsecs_t currentTime = now();
3312
3313 // Dump recently dispatched or dropped events from oldest to newest.
3314 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003315 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003316 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003317 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003319 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 (currentTime - entry->eventTime) * 0.000001f);
3321 }
3322 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003323 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 }
3325
3326 // Dump event currently being dispatched.
3327 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003328 dump += INDENT "PendingEvent:\n";
3329 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003331 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3333 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003334 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335 }
3336
3337 // Dump inbound events from oldest to newest.
3338 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003339 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003341 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003343 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344 (currentTime - entry->eventTime) * 0.000001f);
3345 }
3346 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003347 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 }
3349
Michael Wright78f24442014-08-06 15:55:28 -07003350 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003351 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003352 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3353 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3354 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003355 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003356 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3357 }
3358 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003359 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003360 }
3361
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003363 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3365 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003366 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003368 i, connection->getInputChannelName().c_str(),
3369 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370 connection->getStatusLabel(), toString(connection->monitor),
3371 toString(connection->inputPublisherBlocked));
3372
3373 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003374 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375 connection->outboundQueue.count());
3376 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3377 entry = entry->next) {
3378 dump.append(INDENT4);
3379 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003380 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 entry->targetFlags, entry->resolvedAction,
3382 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3383 }
3384 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003385 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 }
3387
3388 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003389 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 connection->waitQueue.count());
3391 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3392 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003393 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003395 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 "age=%0.1fms, wait=%0.1fms\n",
3397 entry->targetFlags, entry->resolvedAction,
3398 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3399 (currentTime - entry->deliveryTime) * 0.000001f);
3400 }
3401 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003402 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 }
3404 }
3405 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003406 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 }
3408
3409 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003410 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 (mAppSwitchDueTime - now()) / 1000000.0);
3412 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003413 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414 }
3415
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003416 dump += INDENT "Configuration:\n";
3417 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003419 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420 mConfig.keyRepeatTimeout * 0.000001f);
3421}
3422
3423status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3424 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
3425#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003426 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 toString(monitor));
3428#endif
3429
3430 { // acquire lock
3431 AutoMutex _l(mLock);
3432
3433 if (getConnectionIndexLocked(inputChannel) >= 0) {
3434 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003435 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 return BAD_VALUE;
3437 }
3438
3439 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3440
3441 int fd = inputChannel->getFd();
3442 mConnectionsByFd.add(fd, connection);
3443
3444 if (monitor) {
3445 mMonitoringChannels.push(inputChannel);
3446 }
3447
3448 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3449 } // release lock
3450
3451 // Wake the looper because some connections have changed.
3452 mLooper->wake();
3453 return OK;
3454}
3455
3456status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3457#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003458 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459#endif
3460
3461 { // acquire lock
3462 AutoMutex _l(mLock);
3463
3464 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3465 if (status) {
3466 return status;
3467 }
3468 } // release lock
3469
3470 // Wake the poll loop because removing the connection may have changed the current
3471 // synchronization state.
3472 mLooper->wake();
3473 return OK;
3474}
3475
3476status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3477 bool notify) {
3478 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3479 if (connectionIndex < 0) {
3480 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003481 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482 return BAD_VALUE;
3483 }
3484
3485 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3486 mConnectionsByFd.removeItemsAt(connectionIndex);
3487
3488 if (connection->monitor) {
3489 removeMonitorChannelLocked(inputChannel);
3490 }
3491
3492 mLooper->removeFd(inputChannel->getFd());
3493
3494 nsecs_t currentTime = now();
3495 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3496
3497 connection->status = Connection::STATUS_ZOMBIE;
3498 return OK;
3499}
3500
3501void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3502 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3503 if (mMonitoringChannels[i] == inputChannel) {
3504 mMonitoringChannels.removeAt(i);
3505 break;
3506 }
3507 }
3508}
3509
3510ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
3511 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3512 if (connectionIndex >= 0) {
3513 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3514 if (connection->inputChannel.get() == inputChannel.get()) {
3515 return connectionIndex;
3516 }
3517 }
3518
3519 return -1;
3520}
3521
3522void InputDispatcher::onDispatchCycleFinishedLocked(
3523 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3524 CommandEntry* commandEntry = postCommandLocked(
3525 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3526 commandEntry->connection = connection;
3527 commandEntry->eventTime = currentTime;
3528 commandEntry->seq = seq;
3529 commandEntry->handled = handled;
3530}
3531
3532void InputDispatcher::onDispatchCycleBrokenLocked(
3533 nsecs_t currentTime, const sp<Connection>& connection) {
3534 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003535 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536
3537 CommandEntry* commandEntry = postCommandLocked(
3538 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3539 commandEntry->connection = connection;
3540}
3541
3542void InputDispatcher::onANRLocked(
3543 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3544 const sp<InputWindowHandle>& windowHandle,
3545 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3546 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3547 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3548 ALOGI("Application is not responding: %s. "
3549 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003550 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 dispatchLatency, waitDuration, reason);
3552
3553 // Capture a record of the InputDispatcher state at the time of the ANR.
3554 time_t t = time(NULL);
3555 struct tm tm;
3556 localtime_r(&t, &tm);
3557 char timestr[64];
3558 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3559 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003560 mLastANRState += INDENT "ANR:\n";
3561 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3562 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3563 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3564 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3565 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3566 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 dumpDispatchStateLocked(mLastANRState);
3568
3569 CommandEntry* commandEntry = postCommandLocked(
3570 & InputDispatcher::doNotifyANRLockedInterruptible);
3571 commandEntry->inputApplicationHandle = applicationHandle;
3572 commandEntry->inputWindowHandle = windowHandle;
3573 commandEntry->reason = reason;
3574}
3575
3576void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3577 CommandEntry* commandEntry) {
3578 mLock.unlock();
3579
3580 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3581
3582 mLock.lock();
3583}
3584
3585void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3586 CommandEntry* commandEntry) {
3587 sp<Connection> connection = commandEntry->connection;
3588
3589 if (connection->status != Connection::STATUS_ZOMBIE) {
3590 mLock.unlock();
3591
3592 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3593
3594 mLock.lock();
3595 }
3596}
3597
3598void InputDispatcher::doNotifyANRLockedInterruptible(
3599 CommandEntry* commandEntry) {
3600 mLock.unlock();
3601
3602 nsecs_t newTimeout = mPolicy->notifyANR(
3603 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3604 commandEntry->reason);
3605
3606 mLock.lock();
3607
3608 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3609 commandEntry->inputWindowHandle != NULL
3610 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
3611}
3612
3613void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3614 CommandEntry* commandEntry) {
3615 KeyEntry* entry = commandEntry->keyEntry;
3616
3617 KeyEvent event;
3618 initializeKeyEvent(&event, entry);
3619
3620 mLock.unlock();
3621
Michael Wright2b3c3302018-03-02 17:19:13 +00003622 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3624 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003625 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3626 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3627 std::to_string(t.duration().count()).c_str());
3628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629
3630 mLock.lock();
3631
3632 if (delay < 0) {
3633 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3634 } else if (!delay) {
3635 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3636 } else {
3637 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3638 entry->interceptKeyWakeupTime = now() + delay;
3639 }
3640 entry->release();
3641}
3642
3643void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3644 CommandEntry* commandEntry) {
3645 sp<Connection> connection = commandEntry->connection;
3646 nsecs_t finishTime = commandEntry->eventTime;
3647 uint32_t seq = commandEntry->seq;
3648 bool handled = commandEntry->handled;
3649
3650 // Handle post-event policy actions.
3651 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3652 if (dispatchEntry) {
3653 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3654 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003655 std::string msg =
3656 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003657 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003659 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 }
3661
3662 bool restartEvent;
3663 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3664 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3665 restartEvent = afterKeyEventLockedInterruptible(connection,
3666 dispatchEntry, keyEntry, handled);
3667 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3668 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3669 restartEvent = afterMotionEventLockedInterruptible(connection,
3670 dispatchEntry, motionEntry, handled);
3671 } else {
3672 restartEvent = false;
3673 }
3674
3675 // Dequeue the event and start the next cycle.
3676 // Note that because the lock might have been released, it is possible that the
3677 // contents of the wait queue to have been drained, so we need to double-check
3678 // a few things.
3679 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3680 connection->waitQueue.dequeue(dispatchEntry);
3681 traceWaitQueueLengthLocked(connection);
3682 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3683 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3684 traceOutboundQueueLengthLocked(connection);
3685 } else {
3686 releaseDispatchEntryLocked(dispatchEntry);
3687 }
3688 }
3689
3690 // Start the next dispatch cycle for this connection.
3691 startDispatchCycleLocked(now(), connection);
3692 }
3693}
3694
3695bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3696 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3697 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3698 // Get the fallback key state.
3699 // Clear it out after dispatching the UP.
3700 int32_t originalKeyCode = keyEntry->keyCode;
3701 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3702 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3703 connection->inputState.removeFallbackKey(originalKeyCode);
3704 }
3705
3706 if (handled || !dispatchEntry->hasForegroundTarget()) {
3707 // If the application handles the original key for which we previously
3708 // generated a fallback or if the window is not a foreground window,
3709 // then cancel the associated fallback key, if any.
3710 if (fallbackKeyCode != -1) {
3711 // Dispatch the unhandled key to the policy with the cancel flag.
3712#if DEBUG_OUTBOUND_EVENT_DETAILS
3713 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3714 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3715 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3716 keyEntry->policyFlags);
3717#endif
3718 KeyEvent event;
3719 initializeKeyEvent(&event, keyEntry);
3720 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3721
3722 mLock.unlock();
3723
3724 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3725 &event, keyEntry->policyFlags, &event);
3726
3727 mLock.lock();
3728
3729 // Cancel the fallback key.
3730 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3731 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3732 "application handled the original non-fallback key "
3733 "or is no longer a foreground target, "
3734 "canceling previously dispatched fallback key");
3735 options.keyCode = fallbackKeyCode;
3736 synthesizeCancelationEventsForConnectionLocked(connection, options);
3737 }
3738 connection->inputState.removeFallbackKey(originalKeyCode);
3739 }
3740 } else {
3741 // If the application did not handle a non-fallback key, first check
3742 // that we are in a good state to perform unhandled key event processing
3743 // Then ask the policy what to do with it.
3744 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3745 && keyEntry->repeatCount == 0;
3746 if (fallbackKeyCode == -1 && !initialDown) {
3747#if DEBUG_OUTBOUND_EVENT_DETAILS
3748 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3749 "since this is not an initial down. "
3750 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3751 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3752 keyEntry->policyFlags);
3753#endif
3754 return false;
3755 }
3756
3757 // Dispatch the unhandled key to the policy.
3758#if DEBUG_OUTBOUND_EVENT_DETAILS
3759 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
3760 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3761 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3762 keyEntry->policyFlags);
3763#endif
3764 KeyEvent event;
3765 initializeKeyEvent(&event, keyEntry);
3766
3767 mLock.unlock();
3768
3769 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3770 &event, keyEntry->policyFlags, &event);
3771
3772 mLock.lock();
3773
3774 if (connection->status != Connection::STATUS_NORMAL) {
3775 connection->inputState.removeFallbackKey(originalKeyCode);
3776 return false;
3777 }
3778
3779 // Latch the fallback keycode for this key on an initial down.
3780 // The fallback keycode cannot change at any other point in the lifecycle.
3781 if (initialDown) {
3782 if (fallback) {
3783 fallbackKeyCode = event.getKeyCode();
3784 } else {
3785 fallbackKeyCode = AKEYCODE_UNKNOWN;
3786 }
3787 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3788 }
3789
3790 ALOG_ASSERT(fallbackKeyCode != -1);
3791
3792 // Cancel the fallback key if the policy decides not to send it anymore.
3793 // We will continue to dispatch the key to the policy but we will no
3794 // longer dispatch a fallback key to the application.
3795 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3796 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3797#if DEBUG_OUTBOUND_EVENT_DETAILS
3798 if (fallback) {
3799 ALOGD("Unhandled key event: Policy requested to send key %d"
3800 "as a fallback for %d, but on the DOWN it had requested "
3801 "to send %d instead. Fallback canceled.",
3802 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3803 } else {
3804 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
3805 "but on the DOWN it had requested to send %d. "
3806 "Fallback canceled.",
3807 originalKeyCode, fallbackKeyCode);
3808 }
3809#endif
3810
3811 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3812 "canceling fallback, policy no longer desires it");
3813 options.keyCode = fallbackKeyCode;
3814 synthesizeCancelationEventsForConnectionLocked(connection, options);
3815
3816 fallback = false;
3817 fallbackKeyCode = AKEYCODE_UNKNOWN;
3818 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3819 connection->inputState.setFallbackKey(originalKeyCode,
3820 fallbackKeyCode);
3821 }
3822 }
3823
3824#if DEBUG_OUTBOUND_EVENT_DETAILS
3825 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003826 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3828 connection->inputState.getFallbackKeys();
3829 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003830 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 fallbackKeys.valueAt(i));
3832 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003833 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003834 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 }
3836#endif
3837
3838 if (fallback) {
3839 // Restart the dispatch cycle using the fallback key.
3840 keyEntry->eventTime = event.getEventTime();
3841 keyEntry->deviceId = event.getDeviceId();
3842 keyEntry->source = event.getSource();
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01003843 keyEntry->displayId = event.getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3845 keyEntry->keyCode = fallbackKeyCode;
3846 keyEntry->scanCode = event.getScanCode();
3847 keyEntry->metaState = event.getMetaState();
3848 keyEntry->repeatCount = event.getRepeatCount();
3849 keyEntry->downTime = event.getDownTime();
3850 keyEntry->syntheticRepeat = false;
3851
3852#if DEBUG_OUTBOUND_EVENT_DETAILS
3853 ALOGD("Unhandled key event: Dispatching fallback key. "
3854 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3855 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3856#endif
3857 return true; // restart the event
3858 } else {
3859#if DEBUG_OUTBOUND_EVENT_DETAILS
3860 ALOGD("Unhandled key event: No fallback key.");
3861#endif
3862 }
3863 }
3864 }
3865 return false;
3866}
3867
3868bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3869 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3870 return false;
3871}
3872
3873void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3874 mLock.unlock();
3875
3876 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
3877
3878 mLock.lock();
3879}
3880
3881void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01003882 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3884 entry->downTime, entry->eventTime);
3885}
3886
3887void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3888 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3889 // TODO Write some statistics about how long we spend waiting.
3890}
3891
3892void InputDispatcher::traceInboundQueueLengthLocked() {
3893 if (ATRACE_ENABLED()) {
3894 ATRACE_INT("iq", mInboundQueue.count());
3895 }
3896}
3897
3898void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3899 if (ATRACE_ENABLED()) {
3900 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003901 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 ATRACE_INT(counterName, connection->outboundQueue.count());
3903 }
3904}
3905
3906void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3907 if (ATRACE_ENABLED()) {
3908 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003909 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 ATRACE_INT(counterName, connection->waitQueue.count());
3911 }
3912}
3913
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003914void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 AutoMutex _l(mLock);
3916
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003917 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918 dumpDispatchStateLocked(dump);
3919
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003920 if (!mLastANRState.empty()) {
3921 dump += "\nInput Dispatcher State at time of last ANR:\n";
3922 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 }
3924}
3925
3926void InputDispatcher::monitor() {
3927 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3928 mLock.lock();
3929 mLooper->wake();
3930 mDispatcherIsAliveCondition.wait(mLock);
3931 mLock.unlock();
3932}
3933
3934
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935// --- InputDispatcher::InjectionState ---
3936
3937InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3938 refCount(1),
3939 injectorPid(injectorPid), injectorUid(injectorUid),
3940 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3941 pendingForegroundDispatches(0) {
3942}
3943
3944InputDispatcher::InjectionState::~InjectionState() {
3945}
3946
3947void InputDispatcher::InjectionState::release() {
3948 refCount -= 1;
3949 if (refCount == 0) {
3950 delete this;
3951 } else {
3952 ALOG_ASSERT(refCount > 0);
3953 }
3954}
3955
3956
3957// --- InputDispatcher::EventEntry ---
3958
3959InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3960 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3961 injectionState(NULL), dispatchInProgress(false) {
3962}
3963
3964InputDispatcher::EventEntry::~EventEntry() {
3965 releaseInjectionState();
3966}
3967
3968void InputDispatcher::EventEntry::release() {
3969 refCount -= 1;
3970 if (refCount == 0) {
3971 delete this;
3972 } else {
3973 ALOG_ASSERT(refCount > 0);
3974 }
3975}
3976
3977void InputDispatcher::EventEntry::releaseInjectionState() {
3978 if (injectionState) {
3979 injectionState->release();
3980 injectionState = NULL;
3981 }
3982}
3983
3984
3985// --- InputDispatcher::ConfigurationChangedEntry ---
3986
3987InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3988 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3989}
3990
3991InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3992}
3993
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003994void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
3995 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996}
3997
3998
3999// --- InputDispatcher::DeviceResetEntry ---
4000
4001InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4002 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4003 deviceId(deviceId) {
4004}
4005
4006InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4007}
4008
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004009void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4010 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 deviceId, policyFlags);
4012}
4013
4014
4015// --- InputDispatcher::KeyEntry ---
4016
4017InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004018 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4020 int32_t repeatCount, nsecs_t downTime) :
4021 EventEntry(TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004022 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004023 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4024 repeatCount(repeatCount), downTime(downTime),
4025 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4026 interceptKeyWakeupTime(0) {
4027}
4028
4029InputDispatcher::KeyEntry::~KeyEntry() {
4030}
4031
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004032void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004033 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4035 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004036 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004037 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004038}
4039
4040void InputDispatcher::KeyEntry::recycle() {
4041 releaseInjectionState();
4042
4043 dispatchInProgress = false;
4044 syntheticRepeat = false;
4045 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4046 interceptKeyWakeupTime = 0;
4047}
4048
4049
4050// --- InputDispatcher::MotionEntry ---
4051
Michael Wright7b159c92015-05-14 14:48:03 +01004052InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004053 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4054 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004055 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4056 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004057 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004058 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4059 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4061 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004062 deviceId(deviceId), source(source), displayId(displayId), action(action),
4063 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004064 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004065 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066 for (uint32_t i = 0; i < pointerCount; i++) {
4067 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4068 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004069 if (xOffset || yOffset) {
4070 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4071 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072 }
4073}
4074
4075InputDispatcher::MotionEntry::~MotionEntry() {
4076}
4077
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004078void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004079 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004080 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004081 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004082 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4083 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4084
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085 for (uint32_t i = 0; i < pointerCount; i++) {
4086 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004087 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004089 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 pointerCoords[i].getX(), pointerCoords[i].getY());
4091 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004092 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093}
4094
4095
4096// --- InputDispatcher::DispatchEntry ---
4097
4098volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4099
4100InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4101 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4102 seq(nextSeq()),
4103 eventEntry(eventEntry), targetFlags(targetFlags),
4104 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4105 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4106 eventEntry->refCount += 1;
4107}
4108
4109InputDispatcher::DispatchEntry::~DispatchEntry() {
4110 eventEntry->release();
4111}
4112
4113uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4114 // Sequence number 0 is reserved and will never be returned.
4115 uint32_t seq;
4116 do {
4117 seq = android_atomic_inc(&sNextSeqAtomic);
4118 } while (!seq);
4119 return seq;
4120}
4121
4122
4123// --- InputDispatcher::InputState ---
4124
4125InputDispatcher::InputState::InputState() {
4126}
4127
4128InputDispatcher::InputState::~InputState() {
4129}
4130
4131bool InputDispatcher::InputState::isNeutral() const {
4132 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4133}
4134
4135bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4136 int32_t displayId) const {
4137 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4138 const MotionMemento& memento = mMotionMementos.itemAt(i);
4139 if (memento.deviceId == deviceId
4140 && memento.source == source
4141 && memento.displayId == displayId
4142 && memento.hovering) {
4143 return true;
4144 }
4145 }
4146 return false;
4147}
4148
4149bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4150 int32_t action, int32_t flags) {
4151 switch (action) {
4152 case AKEY_EVENT_ACTION_UP: {
4153 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4154 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4155 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4156 mFallbackKeys.removeItemsAt(i);
4157 } else {
4158 i += 1;
4159 }
4160 }
4161 }
4162 ssize_t index = findKeyMemento(entry);
4163 if (index >= 0) {
4164 mKeyMementos.removeAt(index);
4165 return true;
4166 }
4167 /* FIXME: We can't just drop the key up event because that prevents creating
4168 * popup windows that are automatically shown when a key is held and then
4169 * dismissed when the key is released. The problem is that the popup will
4170 * not have received the original key down, so the key up will be considered
4171 * to be inconsistent with its observed state. We could perhaps handle this
4172 * by synthesizing a key down but that will cause other problems.
4173 *
4174 * So for now, allow inconsistent key up events to be dispatched.
4175 *
4176#if DEBUG_OUTBOUND_EVENT_DETAILS
4177 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4178 "keyCode=%d, scanCode=%d",
4179 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4180#endif
4181 return false;
4182 */
4183 return true;
4184 }
4185
4186 case AKEY_EVENT_ACTION_DOWN: {
4187 ssize_t index = findKeyMemento(entry);
4188 if (index >= 0) {
4189 mKeyMementos.removeAt(index);
4190 }
4191 addKeyMemento(entry, flags);
4192 return true;
4193 }
4194
4195 default:
4196 return true;
4197 }
4198}
4199
4200bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4201 int32_t action, int32_t flags) {
4202 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4203 switch (actionMasked) {
4204 case AMOTION_EVENT_ACTION_UP:
4205 case AMOTION_EVENT_ACTION_CANCEL: {
4206 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4207 if (index >= 0) {
4208 mMotionMementos.removeAt(index);
4209 return true;
4210 }
4211#if DEBUG_OUTBOUND_EVENT_DETAILS
4212 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004213 "displayId=%" PRId32 ", actionMasked=%d",
4214 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215#endif
4216 return false;
4217 }
4218
4219 case AMOTION_EVENT_ACTION_DOWN: {
4220 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4221 if (index >= 0) {
4222 mMotionMementos.removeAt(index);
4223 }
4224 addMotionMemento(entry, flags, false /*hovering*/);
4225 return true;
4226 }
4227
4228 case AMOTION_EVENT_ACTION_POINTER_UP:
4229 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4230 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004231 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4232 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4233 // generate cancellation events for these since they're based in relative rather than
4234 // absolute units.
4235 return true;
4236 }
4237
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004239
4240 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4241 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4242 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4243 // other value and we need to track the motion so we can send cancellation events for
4244 // anything generating fallback events (e.g. DPad keys for joystick movements).
4245 if (index >= 0) {
4246 if (entry->pointerCoords[0].isEmpty()) {
4247 mMotionMementos.removeAt(index);
4248 } else {
4249 MotionMemento& memento = mMotionMementos.editItemAt(index);
4250 memento.setPointers(entry);
4251 }
4252 } else if (!entry->pointerCoords[0].isEmpty()) {
4253 addMotionMemento(entry, flags, false /*hovering*/);
4254 }
4255
4256 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4257 return true;
4258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 if (index >= 0) {
4260 MotionMemento& memento = mMotionMementos.editItemAt(index);
4261 memento.setPointers(entry);
4262 return true;
4263 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264#if DEBUG_OUTBOUND_EVENT_DETAILS
4265 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004266 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4267 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268#endif
4269 return false;
4270 }
4271
4272 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4273 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4274 if (index >= 0) {
4275 mMotionMementos.removeAt(index);
4276 return true;
4277 }
4278#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004279 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4280 "displayId=%" PRId32,
4281 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282#endif
4283 return false;
4284 }
4285
4286 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4287 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4288 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4289 if (index >= 0) {
4290 mMotionMementos.removeAt(index);
4291 }
4292 addMotionMemento(entry, flags, true /*hovering*/);
4293 return true;
4294 }
4295
4296 default:
4297 return true;
4298 }
4299}
4300
4301ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4302 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4303 const KeyMemento& memento = mKeyMementos.itemAt(i);
4304 if (memento.deviceId == entry->deviceId
4305 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004306 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 && memento.keyCode == entry->keyCode
4308 && memento.scanCode == entry->scanCode) {
4309 return i;
4310 }
4311 }
4312 return -1;
4313}
4314
4315ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4316 bool hovering) const {
4317 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4318 const MotionMemento& memento = mMotionMementos.itemAt(i);
4319 if (memento.deviceId == entry->deviceId
4320 && memento.source == entry->source
4321 && memento.displayId == entry->displayId
4322 && memento.hovering == hovering) {
4323 return i;
4324 }
4325 }
4326 return -1;
4327}
4328
4329void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4330 mKeyMementos.push();
4331 KeyMemento& memento = mKeyMementos.editTop();
4332 memento.deviceId = entry->deviceId;
4333 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004334 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 memento.keyCode = entry->keyCode;
4336 memento.scanCode = entry->scanCode;
4337 memento.metaState = entry->metaState;
4338 memento.flags = flags;
4339 memento.downTime = entry->downTime;
4340 memento.policyFlags = entry->policyFlags;
4341}
4342
4343void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4344 int32_t flags, bool hovering) {
4345 mMotionMementos.push();
4346 MotionMemento& memento = mMotionMementos.editTop();
4347 memento.deviceId = entry->deviceId;
4348 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004349 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 memento.flags = flags;
4351 memento.xPrecision = entry->xPrecision;
4352 memento.yPrecision = entry->yPrecision;
4353 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354 memento.setPointers(entry);
4355 memento.hovering = hovering;
4356 memento.policyFlags = entry->policyFlags;
4357}
4358
4359void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4360 pointerCount = entry->pointerCount;
4361 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4362 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4363 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4364 }
4365}
4366
4367void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4368 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4369 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4370 const KeyMemento& memento = mKeyMementos.itemAt(i);
4371 if (shouldCancelKey(memento, options)) {
4372 outEvents.push(new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004373 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4375 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4376 }
4377 }
4378
4379 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4380 const MotionMemento& memento = mMotionMementos.itemAt(i);
4381 if (shouldCancelMotion(memento, options)) {
4382 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004383 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 memento.hovering
4385 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4386 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004387 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004389 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4390 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 }
4392 }
4393}
4394
4395void InputDispatcher::InputState::clear() {
4396 mKeyMementos.clear();
4397 mMotionMementos.clear();
4398 mFallbackKeys.clear();
4399}
4400
4401void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4402 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4403 const MotionMemento& memento = mMotionMementos.itemAt(i);
4404 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4405 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4406 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4407 if (memento.deviceId == otherMemento.deviceId
4408 && memento.source == otherMemento.source
4409 && memento.displayId == otherMemento.displayId) {
4410 other.mMotionMementos.removeAt(j);
4411 } else {
4412 j += 1;
4413 }
4414 }
4415 other.mMotionMementos.push(memento);
4416 }
4417 }
4418}
4419
4420int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4421 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4422 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4423}
4424
4425void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4426 int32_t fallbackKeyCode) {
4427 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4428 if (index >= 0) {
4429 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4430 } else {
4431 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4432 }
4433}
4434
4435void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4436 mFallbackKeys.removeItem(originalKeyCode);
4437}
4438
4439bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4440 const CancelationOptions& options) {
4441 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4442 return false;
4443 }
4444
4445 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4446 return false;
4447 }
4448
4449 switch (options.mode) {
4450 case CancelationOptions::CANCEL_ALL_EVENTS:
4451 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4452 return true;
4453 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4454 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4455 default:
4456 return false;
4457 }
4458}
4459
4460bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4461 const CancelationOptions& options) {
4462 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4463 return false;
4464 }
4465
4466 switch (options.mode) {
4467 case CancelationOptions::CANCEL_ALL_EVENTS:
4468 return true;
4469 case CancelationOptions::CANCEL_POINTER_EVENTS:
4470 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4471 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4472 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4473 default:
4474 return false;
4475 }
4476}
4477
4478
4479// --- InputDispatcher::Connection ---
4480
4481InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4482 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4483 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4484 monitor(monitor),
4485 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4486}
4487
4488InputDispatcher::Connection::~Connection() {
4489}
4490
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004491const std::string InputDispatcher::Connection::getWindowName() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492 if (inputWindowHandle != NULL) {
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004493 return inputWindowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004494 }
4495 if (monitor) {
4496 return "monitor";
4497 }
4498 return "?";
4499}
4500
4501const char* InputDispatcher::Connection::getStatusLabel() const {
4502 switch (status) {
4503 case STATUS_NORMAL:
4504 return "NORMAL";
4505
4506 case STATUS_BROKEN:
4507 return "BROKEN";
4508
4509 case STATUS_ZOMBIE:
4510 return "ZOMBIE";
4511
4512 default:
4513 return "UNKNOWN";
4514 }
4515}
4516
4517InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4518 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4519 if (entry->seq == seq) {
4520 return entry;
4521 }
4522 }
4523 return NULL;
4524}
4525
4526
4527// --- InputDispatcher::CommandEntry ---
4528
4529InputDispatcher::CommandEntry::CommandEntry(Command command) :
4530 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4531 seq(0), handled(false) {
4532}
4533
4534InputDispatcher::CommandEntry::~CommandEntry() {
4535}
4536
4537
4538// --- InputDispatcher::TouchState ---
4539
4540InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004541 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542}
4543
4544InputDispatcher::TouchState::~TouchState() {
4545}
4546
4547void InputDispatcher::TouchState::reset() {
4548 down = false;
4549 split = false;
4550 deviceId = -1;
4551 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004552 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 windows.clear();
4554}
4555
4556void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4557 down = other.down;
4558 split = other.split;
4559 deviceId = other.deviceId;
4560 source = other.source;
4561 displayId = other.displayId;
4562 windows = other.windows;
4563}
4564
4565void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4566 int32_t targetFlags, BitSet32 pointerIds) {
4567 if (targetFlags & InputTarget::FLAG_SPLIT) {
4568 split = true;
4569 }
4570
4571 for (size_t i = 0; i < windows.size(); i++) {
4572 TouchedWindow& touchedWindow = windows.editItemAt(i);
4573 if (touchedWindow.windowHandle == windowHandle) {
4574 touchedWindow.targetFlags |= targetFlags;
4575 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4576 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4577 }
4578 touchedWindow.pointerIds.value |= pointerIds.value;
4579 return;
4580 }
4581 }
4582
4583 windows.push();
4584
4585 TouchedWindow& touchedWindow = windows.editTop();
4586 touchedWindow.windowHandle = windowHandle;
4587 touchedWindow.targetFlags = targetFlags;
4588 touchedWindow.pointerIds = pointerIds;
4589}
4590
4591void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4592 for (size_t i = 0; i < windows.size(); i++) {
4593 if (windows.itemAt(i).windowHandle == windowHandle) {
4594 windows.removeAt(i);
4595 return;
4596 }
4597 }
4598}
4599
4600void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4601 for (size_t i = 0 ; i < windows.size(); ) {
4602 TouchedWindow& window = windows.editItemAt(i);
4603 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4604 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4605 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4606 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4607 i += 1;
4608 } else {
4609 windows.removeAt(i);
4610 }
4611 }
4612}
4613
4614sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4615 for (size_t i = 0; i < windows.size(); i++) {
4616 const TouchedWindow& window = windows.itemAt(i);
4617 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4618 return window.windowHandle;
4619 }
4620 }
4621 return NULL;
4622}
4623
4624bool InputDispatcher::TouchState::isSlippery() const {
4625 // Must have exactly one foreground window.
4626 bool haveSlipperyForegroundWindow = false;
4627 for (size_t i = 0; i < windows.size(); i++) {
4628 const TouchedWindow& window = windows.itemAt(i);
4629 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4630 if (haveSlipperyForegroundWindow
4631 || !(window.windowHandle->getInfo()->layoutParamsFlags
4632 & InputWindowInfo::FLAG_SLIPPERY)) {
4633 return false;
4634 }
4635 haveSlipperyForegroundWindow = true;
4636 }
4637 }
4638 return haveSlipperyForegroundWindow;
4639}
4640
4641
4642// --- InputDispatcherThread ---
4643
4644InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4645 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4646}
4647
4648InputDispatcherThread::~InputDispatcherThread() {
4649}
4650
4651bool InputDispatcherThread::threadLoop() {
4652 mDispatcher->dispatchOnce();
4653 return true;
4654}
4655
4656} // namespace android