blob: 5c078d39593a03de8f1874fbb30b1db51837e3eb [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,
705 entry->deviceId, entry->source, policyFlags,
706 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 Vishniakou5d83f602017-09-12 12:40:29 -0700854 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, policyFlags=0x%x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700856 "repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 prefix,
858 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
859 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,
2021 keyEntry->deviceId, keyEntry->source,
2022 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
2427void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2428#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002429 ALOGD("notifyKey - eventTime=%" PRId64
2430 ", deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
2431 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432 args->eventTime, args->deviceId, args->source, args->policyFlags,
2433 args->action, args->flags, args->keyCode, args->scanCode,
2434 args->metaState, args->downTime);
2435#endif
2436 if (!validateKeyEvent(args->action)) {
2437 return;
2438 }
2439
2440 uint32_t policyFlags = args->policyFlags;
2441 int32_t flags = args->flags;
2442 int32_t metaState = args->metaState;
2443 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2444 policyFlags |= POLICY_FLAG_VIRTUAL;
2445 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 if (policyFlags & POLICY_FLAG_FUNCTION) {
2448 metaState |= AMETA_FUNCTION_ON;
2449 }
2450
2451 policyFlags |= POLICY_FLAG_TRUSTED;
2452
Michael Wright78f24442014-08-06 15:55:28 -07002453 int32_t keyCode = args->keyCode;
2454 if (metaState & AMETA_META_ON && args->action == AKEY_EVENT_ACTION_DOWN) {
2455 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2456 if (keyCode == AKEYCODE_DEL) {
2457 newKeyCode = AKEYCODE_BACK;
2458 } else if (keyCode == AKEYCODE_ENTER) {
2459 newKeyCode = AKEYCODE_HOME;
2460 }
2461 if (newKeyCode != AKEYCODE_UNKNOWN) {
2462 AutoMutex _l(mLock);
2463 struct KeyReplacement replacement = {keyCode, args->deviceId};
2464 mReplacedKeys.add(replacement, newKeyCode);
2465 keyCode = newKeyCode;
Evan Roskye71f0552017-03-21 18:12:36 -07002466 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
Michael Wright78f24442014-08-06 15:55:28 -07002467 }
2468 } else if (args->action == AKEY_EVENT_ACTION_UP) {
2469 // In order to maintain a consistent stream of up and down events, check to see if the key
2470 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2471 // even if the modifier was released between the down and the up events.
2472 AutoMutex _l(mLock);
2473 struct KeyReplacement replacement = {keyCode, args->deviceId};
2474 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2475 if (index >= 0) {
2476 keyCode = mReplacedKeys.valueAt(index);
2477 mReplacedKeys.removeItemsAt(index);
Evan Roskye71f0552017-03-21 18:12:36 -07002478 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
Michael Wright78f24442014-08-06 15:55:28 -07002479 }
2480 }
2481
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 KeyEvent event;
2483 event.initialize(args->deviceId, args->source, args->action,
Michael Wright78f24442014-08-06 15:55:28 -07002484 flags, keyCode, args->scanCode, metaState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 args->downTime, args->eventTime);
2486
Michael Wright2b3c3302018-03-02 17:19:13 +00002487 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002489 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2490 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2491 std::to_string(t.duration().count()).c_str());
2492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493
Michael Wrightd02c5b62014-02-10 15:10:22 -08002494 bool needWake;
2495 { // acquire lock
2496 mLock.lock();
2497
2498 if (shouldSendKeyToInputFilterLocked(args)) {
2499 mLock.unlock();
2500
2501 policyFlags |= POLICY_FLAG_FILTERED;
2502 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2503 return; // event was consumed by the filter
2504 }
2505
2506 mLock.lock();
2507 }
2508
2509 int32_t repeatCount = 0;
2510 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2511 args->deviceId, args->source, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002512 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513 metaState, repeatCount, args->downTime);
2514
2515 needWake = enqueueInboundEventLocked(newEntry);
2516 mLock.unlock();
2517 } // release lock
2518
2519 if (needWake) {
2520 mLooper->wake();
2521 }
2522}
2523
2524bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2525 return mInputFilterEnabled;
2526}
2527
2528void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2529#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002530 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2531 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002532 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002533 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002534 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002535 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002536 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2537 for (uint32_t i = 0; i < args->pointerCount; i++) {
2538 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2539 "x=%f, y=%f, pressure=%f, size=%f, "
2540 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2541 "orientation=%f",
2542 i, args->pointerProperties[i].id,
2543 args->pointerProperties[i].toolType,
2544 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2545 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2546 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2547 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2548 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2549 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2550 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2551 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2552 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2553 }
2554#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002555 if (!validateMotionEvent(args->action, args->actionButton,
2556 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 return;
2558 }
2559
2560 uint32_t policyFlags = args->policyFlags;
2561 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002562
2563 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002565 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2566 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2567 std::to_string(t.duration().count()).c_str());
2568 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569
2570 bool needWake;
2571 { // acquire lock
2572 mLock.lock();
2573
2574 if (shouldSendMotionToInputFilterLocked(args)) {
2575 mLock.unlock();
2576
2577 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002578 event.initialize(args->deviceId, args->source, args->displayId,
2579 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002580 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2581 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 args->downTime, args->eventTime,
2583 args->pointerCount, args->pointerProperties, args->pointerCoords);
2584
2585 policyFlags |= POLICY_FLAG_FILTERED;
2586 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2587 return; // event was consumed by the filter
2588 }
2589
2590 mLock.lock();
2591 }
2592
2593 // Just enqueue a new motion event.
2594 MotionEntry* newEntry = new MotionEntry(args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002595 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002596 args->action, args->actionButton, args->flags,
2597 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002599 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600
2601 needWake = enqueueInboundEventLocked(newEntry);
2602 mLock.unlock();
2603 } // release lock
2604
2605 if (needWake) {
2606 mLooper->wake();
2607 }
2608}
2609
2610bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2611 // TODO: support sending secondary display events to input filter
2612 return mInputFilterEnabled && isMainDisplay(args->displayId);
2613}
2614
2615void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2616#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002617 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2618 "switchMask=0x%08x",
2619 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620#endif
2621
2622 uint32_t policyFlags = args->policyFlags;
2623 policyFlags |= POLICY_FLAG_TRUSTED;
2624 mPolicy->notifySwitch(args->eventTime,
2625 args->switchValues, args->switchMask, policyFlags);
2626}
2627
2628void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2629#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002630 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631 args->eventTime, args->deviceId);
2632#endif
2633
2634 bool needWake;
2635 { // acquire lock
2636 AutoMutex _l(mLock);
2637
2638 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2639 needWake = enqueueInboundEventLocked(newEntry);
2640 } // release lock
2641
2642 if (needWake) {
2643 mLooper->wake();
2644 }
2645}
2646
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002647int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2649 uint32_t policyFlags) {
2650#if DEBUG_INBOUND_EVENT_DETAILS
2651 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002652 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2653 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654#endif
2655
2656 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2657
2658 policyFlags |= POLICY_FLAG_INJECTED;
2659 if (hasInjectionPermission(injectorPid, injectorUid)) {
2660 policyFlags |= POLICY_FLAG_TRUSTED;
2661 }
2662
2663 EventEntry* firstInjectedEntry;
2664 EventEntry* lastInjectedEntry;
2665 switch (event->getType()) {
2666 case AINPUT_EVENT_TYPE_KEY: {
2667 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2668 int32_t action = keyEvent->getAction();
2669 if (! validateKeyEvent(action)) {
2670 return INPUT_EVENT_INJECTION_FAILED;
2671 }
2672
2673 int32_t flags = keyEvent->getFlags();
2674 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2675 policyFlags |= POLICY_FLAG_VIRTUAL;
2676 }
2677
2678 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002679 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002681 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2682 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2683 std::to_string(t.duration().count()).c_str());
2684 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 }
2686
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 mLock.lock();
2688 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
2689 keyEvent->getDeviceId(), keyEvent->getSource(),
2690 policyFlags, action, flags,
2691 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
2692 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2693 lastInjectedEntry = firstInjectedEntry;
2694 break;
2695 }
2696
2697 case AINPUT_EVENT_TYPE_MOTION: {
2698 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 int32_t action = motionEvent->getAction();
2700 size_t pointerCount = motionEvent->getPointerCount();
2701 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002702 int32_t actionButton = motionEvent->getActionButton();
2703 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704 return INPUT_EVENT_INJECTION_FAILED;
2705 }
2706
2707 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2708 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002709 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002711 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2712 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2713 std::to_string(t.duration().count()).c_str());
2714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002715 }
2716
2717 mLock.lock();
2718 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2719 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2720 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002721 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2722 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002723 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724 motionEvent->getMetaState(), motionEvent->getButtonState(),
2725 motionEvent->getEdgeFlags(),
2726 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002727 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002728 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2729 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 lastInjectedEntry = firstInjectedEntry;
2731 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2732 sampleEventTimes += 1;
2733 samplePointerCoords += pointerCount;
2734 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002735 motionEvent->getDeviceId(), motionEvent->getSource(),
2736 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002737 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738 motionEvent->getMetaState(), motionEvent->getButtonState(),
2739 motionEvent->getEdgeFlags(),
2740 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002741 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002742 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2743 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 lastInjectedEntry->next = nextInjectedEntry;
2745 lastInjectedEntry = nextInjectedEntry;
2746 }
2747 break;
2748 }
2749
2750 default:
2751 ALOGW("Cannot inject event of type %d", event->getType());
2752 return INPUT_EVENT_INJECTION_FAILED;
2753 }
2754
2755 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2756 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2757 injectionState->injectionIsAsync = true;
2758 }
2759
2760 injectionState->refCount += 1;
2761 lastInjectedEntry->injectionState = injectionState;
2762
2763 bool needWake = false;
2764 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2765 EventEntry* nextEntry = entry->next;
2766 needWake |= enqueueInboundEventLocked(entry);
2767 entry = nextEntry;
2768 }
2769
2770 mLock.unlock();
2771
2772 if (needWake) {
2773 mLooper->wake();
2774 }
2775
2776 int32_t injectionResult;
2777 { // acquire lock
2778 AutoMutex _l(mLock);
2779
2780 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2781 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2782 } else {
2783 for (;;) {
2784 injectionResult = injectionState->injectionResult;
2785 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2786 break;
2787 }
2788
2789 nsecs_t remainingTimeout = endTime - now();
2790 if (remainingTimeout <= 0) {
2791#if DEBUG_INJECTION
2792 ALOGD("injectInputEvent - Timed out waiting for injection result "
2793 "to become available.");
2794#endif
2795 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2796 break;
2797 }
2798
2799 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2800 }
2801
2802 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2803 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2804 while (injectionState->pendingForegroundDispatches != 0) {
2805#if DEBUG_INJECTION
2806 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2807 injectionState->pendingForegroundDispatches);
2808#endif
2809 nsecs_t remainingTimeout = endTime - now();
2810 if (remainingTimeout <= 0) {
2811#if DEBUG_INJECTION
2812 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2813 "dispatches to finish.");
2814#endif
2815 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2816 break;
2817 }
2818
2819 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2820 }
2821 }
2822 }
2823
2824 injectionState->release();
2825 } // release lock
2826
2827#if DEBUG_INJECTION
2828 ALOGD("injectInputEvent - Finished with result %d. "
2829 "injectorPid=%d, injectorUid=%d",
2830 injectionResult, injectorPid, injectorUid);
2831#endif
2832
2833 return injectionResult;
2834}
2835
2836bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2837 return injectorUid == 0
2838 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2839}
2840
2841void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2842 InjectionState* injectionState = entry->injectionState;
2843 if (injectionState) {
2844#if DEBUG_INJECTION
2845 ALOGD("Setting input event injection result to %d. "
2846 "injectorPid=%d, injectorUid=%d",
2847 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2848#endif
2849
2850 if (injectionState->injectionIsAsync
2851 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2852 // Log the outcome since the injector did not wait for the injection result.
2853 switch (injectionResult) {
2854 case INPUT_EVENT_INJECTION_SUCCEEDED:
2855 ALOGV("Asynchronous input event injection succeeded.");
2856 break;
2857 case INPUT_EVENT_INJECTION_FAILED:
2858 ALOGW("Asynchronous input event injection failed.");
2859 break;
2860 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2861 ALOGW("Asynchronous input event injection permission denied.");
2862 break;
2863 case INPUT_EVENT_INJECTION_TIMED_OUT:
2864 ALOGW("Asynchronous input event injection timed out.");
2865 break;
2866 }
2867 }
2868
2869 injectionState->injectionResult = injectionResult;
2870 mInjectionResultAvailableCondition.broadcast();
2871 }
2872}
2873
2874void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2875 InjectionState* injectionState = entry->injectionState;
2876 if (injectionState) {
2877 injectionState->pendingForegroundDispatches += 1;
2878 }
2879}
2880
2881void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2882 InjectionState* injectionState = entry->injectionState;
2883 if (injectionState) {
2884 injectionState->pendingForegroundDispatches -= 1;
2885
2886 if (injectionState->pendingForegroundDispatches == 0) {
2887 mInjectionSyncFinishedCondition.broadcast();
2888 }
2889 }
2890}
2891
2892sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2893 const sp<InputChannel>& inputChannel) const {
2894 size_t numWindows = mWindowHandles.size();
2895 for (size_t i = 0; i < numWindows; i++) {
2896 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2897 if (windowHandle->getInputChannel() == inputChannel) {
2898 return windowHandle;
2899 }
2900 }
2901 return NULL;
2902}
2903
2904bool InputDispatcher::hasWindowHandleLocked(
2905 const sp<InputWindowHandle>& windowHandle) const {
2906 size_t numWindows = mWindowHandles.size();
2907 for (size_t i = 0; i < numWindows; i++) {
2908 if (mWindowHandles.itemAt(i) == windowHandle) {
2909 return true;
2910 }
2911 }
2912 return false;
2913}
2914
2915void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
2916#if DEBUG_FOCUS
2917 ALOGD("setInputWindows");
2918#endif
2919 { // acquire lock
2920 AutoMutex _l(mLock);
2921
2922 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
2923 mWindowHandles = inputWindowHandles;
2924
2925 sp<InputWindowHandle> newFocusedWindowHandle;
2926 bool foundHoveredWindow = false;
2927 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2928 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2929 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
2930 mWindowHandles.removeAt(i--);
2931 continue;
2932 }
2933 if (windowHandle->getInfo()->hasFocus) {
2934 newFocusedWindowHandle = windowHandle;
2935 }
2936 if (windowHandle == mLastHoverWindowHandle) {
2937 foundHoveredWindow = true;
2938 }
2939 }
2940
2941 if (!foundHoveredWindow) {
2942 mLastHoverWindowHandle = NULL;
2943 }
2944
2945 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2946 if (mFocusedWindowHandle != NULL) {
2947#if DEBUG_FOCUS
2948 ALOGD("Focus left window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002949 mFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950#endif
2951 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2952 if (focusedInputChannel != NULL) {
2953 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2954 "focus left window");
2955 synthesizeCancelationEventsForInputChannelLocked(
2956 focusedInputChannel, options);
2957 }
2958 }
2959 if (newFocusedWindowHandle != NULL) {
2960#if DEBUG_FOCUS
2961 ALOGD("Focus entered window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002962 newFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963#endif
2964 }
2965 mFocusedWindowHandle = newFocusedWindowHandle;
2966 }
2967
Jeff Brownf086ddb2014-02-11 14:28:48 -08002968 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
2969 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
Ivan Lozano96f12992017-11-09 14:45:38 -08002970 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08002971 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
2972 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002973#if DEBUG_FOCUS
Jeff Brownf086ddb2014-02-11 14:28:48 -08002974 ALOGD("Touched window was removed: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002975 touchedWindow.windowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08002977 sp<InputChannel> touchedInputChannel =
2978 touchedWindow.windowHandle->getInputChannel();
2979 if (touchedInputChannel != NULL) {
2980 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2981 "touched window was removed");
2982 synthesizeCancelationEventsForInputChannelLocked(
2983 touchedInputChannel, options);
2984 }
Ivan Lozano96f12992017-11-09 14:45:38 -08002985 state.windows.removeAt(i);
2986 } else {
2987 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002989 }
2990 }
2991
2992 // Release information for windows that are no longer present.
2993 // This ensures that unused input channels are released promptly.
2994 // Otherwise, they might stick around until the window handle is destroyed
2995 // which might not happen until the next GC.
2996 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2997 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2998 if (!hasWindowHandleLocked(oldWindowHandle)) {
2999#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003000 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001#endif
3002 oldWindowHandle->releaseInfo();
3003 }
3004 }
3005 } // release lock
3006
3007 // Wake up poll loop since it may need to make new input dispatching choices.
3008 mLooper->wake();
3009}
3010
3011void InputDispatcher::setFocusedApplication(
3012 const sp<InputApplicationHandle>& inputApplicationHandle) {
3013#if DEBUG_FOCUS
3014 ALOGD("setFocusedApplication");
3015#endif
3016 { // acquire lock
3017 AutoMutex _l(mLock);
3018
3019 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
3020 if (mFocusedApplicationHandle != inputApplicationHandle) {
3021 if (mFocusedApplicationHandle != NULL) {
3022 resetANRTimeoutsLocked();
3023 mFocusedApplicationHandle->releaseInfo();
3024 }
3025 mFocusedApplicationHandle = inputApplicationHandle;
3026 }
3027 } else if (mFocusedApplicationHandle != NULL) {
3028 resetANRTimeoutsLocked();
3029 mFocusedApplicationHandle->releaseInfo();
3030 mFocusedApplicationHandle.clear();
3031 }
3032
3033#if DEBUG_FOCUS
3034 //logDispatchStateLocked();
3035#endif
3036 } // release lock
3037
3038 // Wake up poll loop since it may need to make new input dispatching choices.
3039 mLooper->wake();
3040}
3041
3042void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3043#if DEBUG_FOCUS
3044 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3045#endif
3046
3047 bool changed;
3048 { // acquire lock
3049 AutoMutex _l(mLock);
3050
3051 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3052 if (mDispatchFrozen && !frozen) {
3053 resetANRTimeoutsLocked();
3054 }
3055
3056 if (mDispatchEnabled && !enabled) {
3057 resetAndDropEverythingLocked("dispatcher is being disabled");
3058 }
3059
3060 mDispatchEnabled = enabled;
3061 mDispatchFrozen = frozen;
3062 changed = true;
3063 } else {
3064 changed = false;
3065 }
3066
3067#if DEBUG_FOCUS
3068 //logDispatchStateLocked();
3069#endif
3070 } // release lock
3071
3072 if (changed) {
3073 // Wake up poll loop since it may need to make new input dispatching choices.
3074 mLooper->wake();
3075 }
3076}
3077
3078void InputDispatcher::setInputFilterEnabled(bool enabled) {
3079#if DEBUG_FOCUS
3080 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3081#endif
3082
3083 { // acquire lock
3084 AutoMutex _l(mLock);
3085
3086 if (mInputFilterEnabled == enabled) {
3087 return;
3088 }
3089
3090 mInputFilterEnabled = enabled;
3091 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3092 } // release lock
3093
3094 // Wake up poll loop since there might be work to do to drop everything.
3095 mLooper->wake();
3096}
3097
3098bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3099 const sp<InputChannel>& toChannel) {
3100#if DEBUG_FOCUS
3101 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003102 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103#endif
3104 { // acquire lock
3105 AutoMutex _l(mLock);
3106
3107 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3108 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3109 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
3110#if DEBUG_FOCUS
3111 ALOGD("Cannot transfer focus because from or to window not found.");
3112#endif
3113 return false;
3114 }
3115 if (fromWindowHandle == toWindowHandle) {
3116#if DEBUG_FOCUS
3117 ALOGD("Trivial transfer to same window.");
3118#endif
3119 return true;
3120 }
3121 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3122#if DEBUG_FOCUS
3123 ALOGD("Cannot transfer focus because windows are on different displays.");
3124#endif
3125 return false;
3126 }
3127
3128 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003129 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3130 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3131 for (size_t i = 0; i < state.windows.size(); i++) {
3132 const TouchedWindow& touchedWindow = state.windows[i];
3133 if (touchedWindow.windowHandle == fromWindowHandle) {
3134 int32_t oldTargetFlags = touchedWindow.targetFlags;
3135 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136
Jeff Brownf086ddb2014-02-11 14:28:48 -08003137 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138
Jeff Brownf086ddb2014-02-11 14:28:48 -08003139 int32_t newTargetFlags = oldTargetFlags
3140 & (InputTarget::FLAG_FOREGROUND
3141 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3142 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143
Jeff Brownf086ddb2014-02-11 14:28:48 -08003144 found = true;
3145 goto Found;
3146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 }
3148 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003149Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150
3151 if (! found) {
3152#if DEBUG_FOCUS
3153 ALOGD("Focus transfer failed because from window did not have focus.");
3154#endif
3155 return false;
3156 }
3157
3158 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3159 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3160 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3161 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3162 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3163
3164 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3165 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3166 "transferring touch focus from this window to another window");
3167 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3168 }
3169
3170#if DEBUG_FOCUS
3171 logDispatchStateLocked();
3172#endif
3173 } // release lock
3174
3175 // Wake up poll loop since it may need to make new input dispatching choices.
3176 mLooper->wake();
3177 return true;
3178}
3179
3180void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3181#if DEBUG_FOCUS
3182 ALOGD("Resetting and dropping all events (%s).", reason);
3183#endif
3184
3185 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3186 synthesizeCancelationEventsForAllConnectionsLocked(options);
3187
3188 resetKeyRepeatLocked();
3189 releasePendingEventLocked();
3190 drainInboundQueueLocked();
3191 resetANRTimeoutsLocked();
3192
Jeff Brownf086ddb2014-02-11 14:28:48 -08003193 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003195 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196}
3197
3198void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003199 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 dumpDispatchStateLocked(dump);
3201
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003202 std::istringstream stream(dump);
3203 std::string line;
3204
3205 while (std::getline(stream, line, '\n')) {
3206 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 }
3208}
3209
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003210void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3211 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3212 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213
3214 if (mFocusedApplicationHandle != NULL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003215 dump += StringPrintf(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
3216 mFocusedApplicationHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 mFocusedApplicationHandle->getDispatchingTimeout(
3218 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3219 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003220 dump += StringPrintf(INDENT "FocusedApplication: <null>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003222 dump += StringPrintf(INDENT "FocusedWindow: name='%s'\n",
3223 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().c_str() : "<null>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224
Jeff Brownf086ddb2014-02-11 14:28:48 -08003225 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003226 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003227 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3228 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003229 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003230 state.displayId, toString(state.down), toString(state.split),
3231 state.deviceId, state.source);
3232 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003233 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003234 for (size_t i = 0; i < state.windows.size(); i++) {
3235 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003236 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3237 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003238 touchedWindow.pointerIds.value,
3239 touchedWindow.targetFlags);
3240 }
3241 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003242 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003243 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 }
3245 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003246 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247 }
3248
3249 if (!mWindowHandles.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003250 dump += INDENT "Windows:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3252 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3253 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3254
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003255 dump += StringPrintf(INDENT2 "%zu: name='%s', displayId=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3257 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3258 "frame=[%d,%d][%d,%d], scale=%f, "
3259 "touchableRegion=",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003260 i, windowInfo->name.c_str(), windowInfo->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 toString(windowInfo->paused),
3262 toString(windowInfo->hasFocus),
3263 toString(windowInfo->hasWallpaper),
3264 toString(windowInfo->visible),
3265 toString(windowInfo->canReceiveKeys),
3266 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3267 windowInfo->layer,
3268 windowInfo->frameLeft, windowInfo->frameTop,
3269 windowInfo->frameRight, windowInfo->frameBottom,
3270 windowInfo->scaleFactor);
3271 dumpRegion(dump, windowInfo->touchableRegion);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003272 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3273 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274 windowInfo->ownerPid, windowInfo->ownerUid,
3275 windowInfo->dispatchingTimeout / 1000000.0);
3276 }
3277 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003278 dump += INDENT "Windows: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279 }
3280
3281 if (!mMonitoringChannels.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003282 dump += INDENT "MonitoringChannels:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3284 const sp<InputChannel>& channel = mMonitoringChannels[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003285 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286 }
3287 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003288 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289 }
3290
3291 nsecs_t currentTime = now();
3292
3293 // Dump recently dispatched or dropped events from oldest to newest.
3294 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003295 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003297 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003298 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003299 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 (currentTime - entry->eventTime) * 0.000001f);
3301 }
3302 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003303 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304 }
3305
3306 // Dump event currently being dispatched.
3307 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003308 dump += INDENT "PendingEvent:\n";
3309 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003311 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3313 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003314 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315 }
3316
3317 // Dump inbound events from oldest to newest.
3318 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003319 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003321 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003323 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324 (currentTime - entry->eventTime) * 0.000001f);
3325 }
3326 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003327 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328 }
3329
Michael Wright78f24442014-08-06 15:55:28 -07003330 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003331 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003332 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3333 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3334 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003335 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003336 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3337 }
3338 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003339 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003340 }
3341
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003343 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3345 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003346 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003348 i, connection->getInputChannelName().c_str(),
3349 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 connection->getStatusLabel(), toString(connection->monitor),
3351 toString(connection->inputPublisherBlocked));
3352
3353 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003354 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 connection->outboundQueue.count());
3356 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3357 entry = entry->next) {
3358 dump.append(INDENT4);
3359 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003360 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361 entry->targetFlags, entry->resolvedAction,
3362 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3363 }
3364 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003365 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 }
3367
3368 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003369 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370 connection->waitQueue.count());
3371 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3372 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003373 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003375 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 "age=%0.1fms, wait=%0.1fms\n",
3377 entry->targetFlags, entry->resolvedAction,
3378 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3379 (currentTime - entry->deliveryTime) * 0.000001f);
3380 }
3381 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003382 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 }
3384 }
3385 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003386 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 }
3388
3389 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003390 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 (mAppSwitchDueTime - now()) / 1000000.0);
3392 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003393 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 }
3395
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003396 dump += INDENT "Configuration:\n";
3397 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003399 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 mConfig.keyRepeatTimeout * 0.000001f);
3401}
3402
3403status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3404 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
3405#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003406 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 toString(monitor));
3408#endif
3409
3410 { // acquire lock
3411 AutoMutex _l(mLock);
3412
3413 if (getConnectionIndexLocked(inputChannel) >= 0) {
3414 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003415 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 return BAD_VALUE;
3417 }
3418
3419 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3420
3421 int fd = inputChannel->getFd();
3422 mConnectionsByFd.add(fd, connection);
3423
3424 if (monitor) {
3425 mMonitoringChannels.push(inputChannel);
3426 }
3427
3428 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3429 } // release lock
3430
3431 // Wake the looper because some connections have changed.
3432 mLooper->wake();
3433 return OK;
3434}
3435
3436status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3437#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003438 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439#endif
3440
3441 { // acquire lock
3442 AutoMutex _l(mLock);
3443
3444 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3445 if (status) {
3446 return status;
3447 }
3448 } // release lock
3449
3450 // Wake the poll loop because removing the connection may have changed the current
3451 // synchronization state.
3452 mLooper->wake();
3453 return OK;
3454}
3455
3456status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3457 bool notify) {
3458 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3459 if (connectionIndex < 0) {
3460 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003461 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003462 return BAD_VALUE;
3463 }
3464
3465 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3466 mConnectionsByFd.removeItemsAt(connectionIndex);
3467
3468 if (connection->monitor) {
3469 removeMonitorChannelLocked(inputChannel);
3470 }
3471
3472 mLooper->removeFd(inputChannel->getFd());
3473
3474 nsecs_t currentTime = now();
3475 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3476
3477 connection->status = Connection::STATUS_ZOMBIE;
3478 return OK;
3479}
3480
3481void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3482 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3483 if (mMonitoringChannels[i] == inputChannel) {
3484 mMonitoringChannels.removeAt(i);
3485 break;
3486 }
3487 }
3488}
3489
3490ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
3491 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3492 if (connectionIndex >= 0) {
3493 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3494 if (connection->inputChannel.get() == inputChannel.get()) {
3495 return connectionIndex;
3496 }
3497 }
3498
3499 return -1;
3500}
3501
3502void InputDispatcher::onDispatchCycleFinishedLocked(
3503 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3504 CommandEntry* commandEntry = postCommandLocked(
3505 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3506 commandEntry->connection = connection;
3507 commandEntry->eventTime = currentTime;
3508 commandEntry->seq = seq;
3509 commandEntry->handled = handled;
3510}
3511
3512void InputDispatcher::onDispatchCycleBrokenLocked(
3513 nsecs_t currentTime, const sp<Connection>& connection) {
3514 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003515 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516
3517 CommandEntry* commandEntry = postCommandLocked(
3518 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3519 commandEntry->connection = connection;
3520}
3521
3522void InputDispatcher::onANRLocked(
3523 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3524 const sp<InputWindowHandle>& windowHandle,
3525 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3526 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3527 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3528 ALOGI("Application is not responding: %s. "
3529 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003530 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 dispatchLatency, waitDuration, reason);
3532
3533 // Capture a record of the InputDispatcher state at the time of the ANR.
3534 time_t t = time(NULL);
3535 struct tm tm;
3536 localtime_r(&t, &tm);
3537 char timestr[64];
3538 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3539 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003540 mLastANRState += INDENT "ANR:\n";
3541 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3542 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3543 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3544 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3545 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3546 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003547 dumpDispatchStateLocked(mLastANRState);
3548
3549 CommandEntry* commandEntry = postCommandLocked(
3550 & InputDispatcher::doNotifyANRLockedInterruptible);
3551 commandEntry->inputApplicationHandle = applicationHandle;
3552 commandEntry->inputWindowHandle = windowHandle;
3553 commandEntry->reason = reason;
3554}
3555
3556void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3557 CommandEntry* commandEntry) {
3558 mLock.unlock();
3559
3560 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3561
3562 mLock.lock();
3563}
3564
3565void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3566 CommandEntry* commandEntry) {
3567 sp<Connection> connection = commandEntry->connection;
3568
3569 if (connection->status != Connection::STATUS_ZOMBIE) {
3570 mLock.unlock();
3571
3572 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3573
3574 mLock.lock();
3575 }
3576}
3577
3578void InputDispatcher::doNotifyANRLockedInterruptible(
3579 CommandEntry* commandEntry) {
3580 mLock.unlock();
3581
3582 nsecs_t newTimeout = mPolicy->notifyANR(
3583 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3584 commandEntry->reason);
3585
3586 mLock.lock();
3587
3588 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3589 commandEntry->inputWindowHandle != NULL
3590 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
3591}
3592
3593void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3594 CommandEntry* commandEntry) {
3595 KeyEntry* entry = commandEntry->keyEntry;
3596
3597 KeyEvent event;
3598 initializeKeyEvent(&event, entry);
3599
3600 mLock.unlock();
3601
Michael Wright2b3c3302018-03-02 17:19:13 +00003602 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3604 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003605 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3606 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3607 std::to_string(t.duration().count()).c_str());
3608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609
3610 mLock.lock();
3611
3612 if (delay < 0) {
3613 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3614 } else if (!delay) {
3615 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3616 } else {
3617 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3618 entry->interceptKeyWakeupTime = now() + delay;
3619 }
3620 entry->release();
3621}
3622
3623void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3624 CommandEntry* commandEntry) {
3625 sp<Connection> connection = commandEntry->connection;
3626 nsecs_t finishTime = commandEntry->eventTime;
3627 uint32_t seq = commandEntry->seq;
3628 bool handled = commandEntry->handled;
3629
3630 // Handle post-event policy actions.
3631 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3632 if (dispatchEntry) {
3633 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3634 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003635 std::string msg =
3636 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003637 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003639 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 }
3641
3642 bool restartEvent;
3643 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3644 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3645 restartEvent = afterKeyEventLockedInterruptible(connection,
3646 dispatchEntry, keyEntry, handled);
3647 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3648 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3649 restartEvent = afterMotionEventLockedInterruptible(connection,
3650 dispatchEntry, motionEntry, handled);
3651 } else {
3652 restartEvent = false;
3653 }
3654
3655 // Dequeue the event and start the next cycle.
3656 // Note that because the lock might have been released, it is possible that the
3657 // contents of the wait queue to have been drained, so we need to double-check
3658 // a few things.
3659 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3660 connection->waitQueue.dequeue(dispatchEntry);
3661 traceWaitQueueLengthLocked(connection);
3662 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3663 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3664 traceOutboundQueueLengthLocked(connection);
3665 } else {
3666 releaseDispatchEntryLocked(dispatchEntry);
3667 }
3668 }
3669
3670 // Start the next dispatch cycle for this connection.
3671 startDispatchCycleLocked(now(), connection);
3672 }
3673}
3674
3675bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3676 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3677 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3678 // Get the fallback key state.
3679 // Clear it out after dispatching the UP.
3680 int32_t originalKeyCode = keyEntry->keyCode;
3681 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3682 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3683 connection->inputState.removeFallbackKey(originalKeyCode);
3684 }
3685
3686 if (handled || !dispatchEntry->hasForegroundTarget()) {
3687 // If the application handles the original key for which we previously
3688 // generated a fallback or if the window is not a foreground window,
3689 // then cancel the associated fallback key, if any.
3690 if (fallbackKeyCode != -1) {
3691 // Dispatch the unhandled key to the policy with the cancel flag.
3692#if DEBUG_OUTBOUND_EVENT_DETAILS
3693 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3694 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3695 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3696 keyEntry->policyFlags);
3697#endif
3698 KeyEvent event;
3699 initializeKeyEvent(&event, keyEntry);
3700 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3701
3702 mLock.unlock();
3703
3704 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3705 &event, keyEntry->policyFlags, &event);
3706
3707 mLock.lock();
3708
3709 // Cancel the fallback key.
3710 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3711 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3712 "application handled the original non-fallback key "
3713 "or is no longer a foreground target, "
3714 "canceling previously dispatched fallback key");
3715 options.keyCode = fallbackKeyCode;
3716 synthesizeCancelationEventsForConnectionLocked(connection, options);
3717 }
3718 connection->inputState.removeFallbackKey(originalKeyCode);
3719 }
3720 } else {
3721 // If the application did not handle a non-fallback key, first check
3722 // that we are in a good state to perform unhandled key event processing
3723 // Then ask the policy what to do with it.
3724 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3725 && keyEntry->repeatCount == 0;
3726 if (fallbackKeyCode == -1 && !initialDown) {
3727#if DEBUG_OUTBOUND_EVENT_DETAILS
3728 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3729 "since this is not an initial down. "
3730 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3731 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3732 keyEntry->policyFlags);
3733#endif
3734 return false;
3735 }
3736
3737 // Dispatch the unhandled key to the policy.
3738#if DEBUG_OUTBOUND_EVENT_DETAILS
3739 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
3740 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3741 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3742 keyEntry->policyFlags);
3743#endif
3744 KeyEvent event;
3745 initializeKeyEvent(&event, keyEntry);
3746
3747 mLock.unlock();
3748
3749 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3750 &event, keyEntry->policyFlags, &event);
3751
3752 mLock.lock();
3753
3754 if (connection->status != Connection::STATUS_NORMAL) {
3755 connection->inputState.removeFallbackKey(originalKeyCode);
3756 return false;
3757 }
3758
3759 // Latch the fallback keycode for this key on an initial down.
3760 // The fallback keycode cannot change at any other point in the lifecycle.
3761 if (initialDown) {
3762 if (fallback) {
3763 fallbackKeyCode = event.getKeyCode();
3764 } else {
3765 fallbackKeyCode = AKEYCODE_UNKNOWN;
3766 }
3767 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3768 }
3769
3770 ALOG_ASSERT(fallbackKeyCode != -1);
3771
3772 // Cancel the fallback key if the policy decides not to send it anymore.
3773 // We will continue to dispatch the key to the policy but we will no
3774 // longer dispatch a fallback key to the application.
3775 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3776 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3777#if DEBUG_OUTBOUND_EVENT_DETAILS
3778 if (fallback) {
3779 ALOGD("Unhandled key event: Policy requested to send key %d"
3780 "as a fallback for %d, but on the DOWN it had requested "
3781 "to send %d instead. Fallback canceled.",
3782 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3783 } else {
3784 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
3785 "but on the DOWN it had requested to send %d. "
3786 "Fallback canceled.",
3787 originalKeyCode, fallbackKeyCode);
3788 }
3789#endif
3790
3791 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3792 "canceling fallback, policy no longer desires it");
3793 options.keyCode = fallbackKeyCode;
3794 synthesizeCancelationEventsForConnectionLocked(connection, options);
3795
3796 fallback = false;
3797 fallbackKeyCode = AKEYCODE_UNKNOWN;
3798 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3799 connection->inputState.setFallbackKey(originalKeyCode,
3800 fallbackKeyCode);
3801 }
3802 }
3803
3804#if DEBUG_OUTBOUND_EVENT_DETAILS
3805 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003806 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3808 connection->inputState.getFallbackKeys();
3809 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003810 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 fallbackKeys.valueAt(i));
3812 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003813 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003814 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 }
3816#endif
3817
3818 if (fallback) {
3819 // Restart the dispatch cycle using the fallback key.
3820 keyEntry->eventTime = event.getEventTime();
3821 keyEntry->deviceId = event.getDeviceId();
3822 keyEntry->source = event.getSource();
3823 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3824 keyEntry->keyCode = fallbackKeyCode;
3825 keyEntry->scanCode = event.getScanCode();
3826 keyEntry->metaState = event.getMetaState();
3827 keyEntry->repeatCount = event.getRepeatCount();
3828 keyEntry->downTime = event.getDownTime();
3829 keyEntry->syntheticRepeat = false;
3830
3831#if DEBUG_OUTBOUND_EVENT_DETAILS
3832 ALOGD("Unhandled key event: Dispatching fallback key. "
3833 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3834 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3835#endif
3836 return true; // restart the event
3837 } else {
3838#if DEBUG_OUTBOUND_EVENT_DETAILS
3839 ALOGD("Unhandled key event: No fallback key.");
3840#endif
3841 }
3842 }
3843 }
3844 return false;
3845}
3846
3847bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3848 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3849 return false;
3850}
3851
3852void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3853 mLock.unlock();
3854
3855 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
3856
3857 mLock.lock();
3858}
3859
3860void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3861 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3862 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3863 entry->downTime, entry->eventTime);
3864}
3865
3866void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3867 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3868 // TODO Write some statistics about how long we spend waiting.
3869}
3870
3871void InputDispatcher::traceInboundQueueLengthLocked() {
3872 if (ATRACE_ENABLED()) {
3873 ATRACE_INT("iq", mInboundQueue.count());
3874 }
3875}
3876
3877void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3878 if (ATRACE_ENABLED()) {
3879 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003880 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881 ATRACE_INT(counterName, connection->outboundQueue.count());
3882 }
3883}
3884
3885void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3886 if (ATRACE_ENABLED()) {
3887 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003888 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889 ATRACE_INT(counterName, connection->waitQueue.count());
3890 }
3891}
3892
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003893void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894 AutoMutex _l(mLock);
3895
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003896 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 dumpDispatchStateLocked(dump);
3898
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003899 if (!mLastANRState.empty()) {
3900 dump += "\nInput Dispatcher State at time of last ANR:\n";
3901 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 }
3903}
3904
3905void InputDispatcher::monitor() {
3906 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3907 mLock.lock();
3908 mLooper->wake();
3909 mDispatcherIsAliveCondition.wait(mLock);
3910 mLock.unlock();
3911}
3912
3913
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914// --- InputDispatcher::InjectionState ---
3915
3916InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3917 refCount(1),
3918 injectorPid(injectorPid), injectorUid(injectorUid),
3919 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3920 pendingForegroundDispatches(0) {
3921}
3922
3923InputDispatcher::InjectionState::~InjectionState() {
3924}
3925
3926void InputDispatcher::InjectionState::release() {
3927 refCount -= 1;
3928 if (refCount == 0) {
3929 delete this;
3930 } else {
3931 ALOG_ASSERT(refCount > 0);
3932 }
3933}
3934
3935
3936// --- InputDispatcher::EventEntry ---
3937
3938InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3939 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3940 injectionState(NULL), dispatchInProgress(false) {
3941}
3942
3943InputDispatcher::EventEntry::~EventEntry() {
3944 releaseInjectionState();
3945}
3946
3947void InputDispatcher::EventEntry::release() {
3948 refCount -= 1;
3949 if (refCount == 0) {
3950 delete this;
3951 } else {
3952 ALOG_ASSERT(refCount > 0);
3953 }
3954}
3955
3956void InputDispatcher::EventEntry::releaseInjectionState() {
3957 if (injectionState) {
3958 injectionState->release();
3959 injectionState = NULL;
3960 }
3961}
3962
3963
3964// --- InputDispatcher::ConfigurationChangedEntry ---
3965
3966InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3967 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3968}
3969
3970InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3971}
3972
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003973void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
3974 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975}
3976
3977
3978// --- InputDispatcher::DeviceResetEntry ---
3979
3980InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3981 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3982 deviceId(deviceId) {
3983}
3984
3985InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3986}
3987
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003988void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
3989 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 deviceId, policyFlags);
3991}
3992
3993
3994// --- InputDispatcher::KeyEntry ---
3995
3996InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
3997 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
3998 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3999 int32_t repeatCount, nsecs_t downTime) :
4000 EventEntry(TYPE_KEY, eventTime, policyFlags),
4001 deviceId(deviceId), source(source), action(action), flags(flags),
4002 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4003 repeatCount(repeatCount), downTime(downTime),
4004 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4005 interceptKeyWakeupTime(0) {
4006}
4007
4008InputDispatcher::KeyEntry::~KeyEntry() {
4009}
4010
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004011void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004012 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004013 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4014 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004015 deviceId, source, keyActionToString(action).c_str(), flags, keyCode,
4016 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017}
4018
4019void InputDispatcher::KeyEntry::recycle() {
4020 releaseInjectionState();
4021
4022 dispatchInProgress = false;
4023 syntheticRepeat = false;
4024 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4025 interceptKeyWakeupTime = 0;
4026}
4027
4028
4029// --- InputDispatcher::MotionEntry ---
4030
Michael Wright7b159c92015-05-14 14:48:03 +01004031InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004032 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4033 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004034 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4035 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004036 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004037 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4038 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004039 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4040 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004041 deviceId(deviceId), source(source), displayId(displayId), action(action),
4042 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004043 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004044 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045 for (uint32_t i = 0; i < pointerCount; i++) {
4046 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4047 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004048 if (xOffset || yOffset) {
4049 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4050 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 }
4052}
4053
4054InputDispatcher::MotionEntry::~MotionEntry() {
4055}
4056
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004057void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004058 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004059 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004060 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004061 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4062 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4063
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064 for (uint32_t i = 0; i < pointerCount; i++) {
4065 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004066 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004068 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069 pointerCoords[i].getX(), pointerCoords[i].getY());
4070 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004071 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004072}
4073
4074
4075// --- InputDispatcher::DispatchEntry ---
4076
4077volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4078
4079InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4080 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4081 seq(nextSeq()),
4082 eventEntry(eventEntry), targetFlags(targetFlags),
4083 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4084 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4085 eventEntry->refCount += 1;
4086}
4087
4088InputDispatcher::DispatchEntry::~DispatchEntry() {
4089 eventEntry->release();
4090}
4091
4092uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4093 // Sequence number 0 is reserved and will never be returned.
4094 uint32_t seq;
4095 do {
4096 seq = android_atomic_inc(&sNextSeqAtomic);
4097 } while (!seq);
4098 return seq;
4099}
4100
4101
4102// --- InputDispatcher::InputState ---
4103
4104InputDispatcher::InputState::InputState() {
4105}
4106
4107InputDispatcher::InputState::~InputState() {
4108}
4109
4110bool InputDispatcher::InputState::isNeutral() const {
4111 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4112}
4113
4114bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4115 int32_t displayId) const {
4116 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4117 const MotionMemento& memento = mMotionMementos.itemAt(i);
4118 if (memento.deviceId == deviceId
4119 && memento.source == source
4120 && memento.displayId == displayId
4121 && memento.hovering) {
4122 return true;
4123 }
4124 }
4125 return false;
4126}
4127
4128bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4129 int32_t action, int32_t flags) {
4130 switch (action) {
4131 case AKEY_EVENT_ACTION_UP: {
4132 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4133 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4134 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4135 mFallbackKeys.removeItemsAt(i);
4136 } else {
4137 i += 1;
4138 }
4139 }
4140 }
4141 ssize_t index = findKeyMemento(entry);
4142 if (index >= 0) {
4143 mKeyMementos.removeAt(index);
4144 return true;
4145 }
4146 /* FIXME: We can't just drop the key up event because that prevents creating
4147 * popup windows that are automatically shown when a key is held and then
4148 * dismissed when the key is released. The problem is that the popup will
4149 * not have received the original key down, so the key up will be considered
4150 * to be inconsistent with its observed state. We could perhaps handle this
4151 * by synthesizing a key down but that will cause other problems.
4152 *
4153 * So for now, allow inconsistent key up events to be dispatched.
4154 *
4155#if DEBUG_OUTBOUND_EVENT_DETAILS
4156 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4157 "keyCode=%d, scanCode=%d",
4158 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4159#endif
4160 return false;
4161 */
4162 return true;
4163 }
4164
4165 case AKEY_EVENT_ACTION_DOWN: {
4166 ssize_t index = findKeyMemento(entry);
4167 if (index >= 0) {
4168 mKeyMementos.removeAt(index);
4169 }
4170 addKeyMemento(entry, flags);
4171 return true;
4172 }
4173
4174 default:
4175 return true;
4176 }
4177}
4178
4179bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4180 int32_t action, int32_t flags) {
4181 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4182 switch (actionMasked) {
4183 case AMOTION_EVENT_ACTION_UP:
4184 case AMOTION_EVENT_ACTION_CANCEL: {
4185 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4186 if (index >= 0) {
4187 mMotionMementos.removeAt(index);
4188 return true;
4189 }
4190#if DEBUG_OUTBOUND_EVENT_DETAILS
4191 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004192 "displayId=%" PRId32 ", actionMasked=%d",
4193 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194#endif
4195 return false;
4196 }
4197
4198 case AMOTION_EVENT_ACTION_DOWN: {
4199 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4200 if (index >= 0) {
4201 mMotionMementos.removeAt(index);
4202 }
4203 addMotionMemento(entry, flags, false /*hovering*/);
4204 return true;
4205 }
4206
4207 case AMOTION_EVENT_ACTION_POINTER_UP:
4208 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4209 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004210 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4211 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4212 // generate cancellation events for these since they're based in relative rather than
4213 // absolute units.
4214 return true;
4215 }
4216
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004218
4219 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4220 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4221 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4222 // other value and we need to track the motion so we can send cancellation events for
4223 // anything generating fallback events (e.g. DPad keys for joystick movements).
4224 if (index >= 0) {
4225 if (entry->pointerCoords[0].isEmpty()) {
4226 mMotionMementos.removeAt(index);
4227 } else {
4228 MotionMemento& memento = mMotionMementos.editItemAt(index);
4229 memento.setPointers(entry);
4230 }
4231 } else if (!entry->pointerCoords[0].isEmpty()) {
4232 addMotionMemento(entry, flags, false /*hovering*/);
4233 }
4234
4235 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4236 return true;
4237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 if (index >= 0) {
4239 MotionMemento& memento = mMotionMementos.editItemAt(index);
4240 memento.setPointers(entry);
4241 return true;
4242 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243#if DEBUG_OUTBOUND_EVENT_DETAILS
4244 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004245 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4246 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247#endif
4248 return false;
4249 }
4250
4251 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4252 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4253 if (index >= 0) {
4254 mMotionMementos.removeAt(index);
4255 return true;
4256 }
4257#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004258 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4259 "displayId=%" PRId32,
4260 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261#endif
4262 return false;
4263 }
4264
4265 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4266 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4267 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4268 if (index >= 0) {
4269 mMotionMementos.removeAt(index);
4270 }
4271 addMotionMemento(entry, flags, true /*hovering*/);
4272 return true;
4273 }
4274
4275 default:
4276 return true;
4277 }
4278}
4279
4280ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4281 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4282 const KeyMemento& memento = mKeyMementos.itemAt(i);
4283 if (memento.deviceId == entry->deviceId
4284 && memento.source == entry->source
4285 && memento.keyCode == entry->keyCode
4286 && memento.scanCode == entry->scanCode) {
4287 return i;
4288 }
4289 }
4290 return -1;
4291}
4292
4293ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4294 bool hovering) const {
4295 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4296 const MotionMemento& memento = mMotionMementos.itemAt(i);
4297 if (memento.deviceId == entry->deviceId
4298 && memento.source == entry->source
4299 && memento.displayId == entry->displayId
4300 && memento.hovering == hovering) {
4301 return i;
4302 }
4303 }
4304 return -1;
4305}
4306
4307void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4308 mKeyMementos.push();
4309 KeyMemento& memento = mKeyMementos.editTop();
4310 memento.deviceId = entry->deviceId;
4311 memento.source = entry->source;
4312 memento.keyCode = entry->keyCode;
4313 memento.scanCode = entry->scanCode;
4314 memento.metaState = entry->metaState;
4315 memento.flags = flags;
4316 memento.downTime = entry->downTime;
4317 memento.policyFlags = entry->policyFlags;
4318}
4319
4320void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4321 int32_t flags, bool hovering) {
4322 mMotionMementos.push();
4323 MotionMemento& memento = mMotionMementos.editTop();
4324 memento.deviceId = entry->deviceId;
4325 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004326 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 memento.flags = flags;
4328 memento.xPrecision = entry->xPrecision;
4329 memento.yPrecision = entry->yPrecision;
4330 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 memento.setPointers(entry);
4332 memento.hovering = hovering;
4333 memento.policyFlags = entry->policyFlags;
4334}
4335
4336void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4337 pointerCount = entry->pointerCount;
4338 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4339 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4340 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4341 }
4342}
4343
4344void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4345 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4346 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4347 const KeyMemento& memento = mKeyMementos.itemAt(i);
4348 if (shouldCancelKey(memento, options)) {
4349 outEvents.push(new KeyEntry(currentTime,
4350 memento.deviceId, memento.source, memento.policyFlags,
4351 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4352 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4353 }
4354 }
4355
4356 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4357 const MotionMemento& memento = mMotionMementos.itemAt(i);
4358 if (shouldCancelMotion(memento, options)) {
4359 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004360 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 memento.hovering
4362 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4363 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004364 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004366 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4367 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368 }
4369 }
4370}
4371
4372void InputDispatcher::InputState::clear() {
4373 mKeyMementos.clear();
4374 mMotionMementos.clear();
4375 mFallbackKeys.clear();
4376}
4377
4378void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4379 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4380 const MotionMemento& memento = mMotionMementos.itemAt(i);
4381 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4382 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4383 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4384 if (memento.deviceId == otherMemento.deviceId
4385 && memento.source == otherMemento.source
4386 && memento.displayId == otherMemento.displayId) {
4387 other.mMotionMementos.removeAt(j);
4388 } else {
4389 j += 1;
4390 }
4391 }
4392 other.mMotionMementos.push(memento);
4393 }
4394 }
4395}
4396
4397int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4398 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4399 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4400}
4401
4402void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4403 int32_t fallbackKeyCode) {
4404 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4405 if (index >= 0) {
4406 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4407 } else {
4408 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4409 }
4410}
4411
4412void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4413 mFallbackKeys.removeItem(originalKeyCode);
4414}
4415
4416bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4417 const CancelationOptions& options) {
4418 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4419 return false;
4420 }
4421
4422 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4423 return false;
4424 }
4425
4426 switch (options.mode) {
4427 case CancelationOptions::CANCEL_ALL_EVENTS:
4428 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4429 return true;
4430 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4431 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4432 default:
4433 return false;
4434 }
4435}
4436
4437bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4438 const CancelationOptions& options) {
4439 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4440 return false;
4441 }
4442
4443 switch (options.mode) {
4444 case CancelationOptions::CANCEL_ALL_EVENTS:
4445 return true;
4446 case CancelationOptions::CANCEL_POINTER_EVENTS:
4447 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4448 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4449 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4450 default:
4451 return false;
4452 }
4453}
4454
4455
4456// --- InputDispatcher::Connection ---
4457
4458InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4459 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4460 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4461 monitor(monitor),
4462 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4463}
4464
4465InputDispatcher::Connection::~Connection() {
4466}
4467
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004468const std::string InputDispatcher::Connection::getWindowName() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469 if (inputWindowHandle != NULL) {
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004470 return inputWindowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 }
4472 if (monitor) {
4473 return "monitor";
4474 }
4475 return "?";
4476}
4477
4478const char* InputDispatcher::Connection::getStatusLabel() const {
4479 switch (status) {
4480 case STATUS_NORMAL:
4481 return "NORMAL";
4482
4483 case STATUS_BROKEN:
4484 return "BROKEN";
4485
4486 case STATUS_ZOMBIE:
4487 return "ZOMBIE";
4488
4489 default:
4490 return "UNKNOWN";
4491 }
4492}
4493
4494InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4495 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4496 if (entry->seq == seq) {
4497 return entry;
4498 }
4499 }
4500 return NULL;
4501}
4502
4503
4504// --- InputDispatcher::CommandEntry ---
4505
4506InputDispatcher::CommandEntry::CommandEntry(Command command) :
4507 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4508 seq(0), handled(false) {
4509}
4510
4511InputDispatcher::CommandEntry::~CommandEntry() {
4512}
4513
4514
4515// --- InputDispatcher::TouchState ---
4516
4517InputDispatcher::TouchState::TouchState() :
4518 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
4519}
4520
4521InputDispatcher::TouchState::~TouchState() {
4522}
4523
4524void InputDispatcher::TouchState::reset() {
4525 down = false;
4526 split = false;
4527 deviceId = -1;
4528 source = 0;
4529 displayId = -1;
4530 windows.clear();
4531}
4532
4533void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4534 down = other.down;
4535 split = other.split;
4536 deviceId = other.deviceId;
4537 source = other.source;
4538 displayId = other.displayId;
4539 windows = other.windows;
4540}
4541
4542void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4543 int32_t targetFlags, BitSet32 pointerIds) {
4544 if (targetFlags & InputTarget::FLAG_SPLIT) {
4545 split = true;
4546 }
4547
4548 for (size_t i = 0; i < windows.size(); i++) {
4549 TouchedWindow& touchedWindow = windows.editItemAt(i);
4550 if (touchedWindow.windowHandle == windowHandle) {
4551 touchedWindow.targetFlags |= targetFlags;
4552 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4553 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4554 }
4555 touchedWindow.pointerIds.value |= pointerIds.value;
4556 return;
4557 }
4558 }
4559
4560 windows.push();
4561
4562 TouchedWindow& touchedWindow = windows.editTop();
4563 touchedWindow.windowHandle = windowHandle;
4564 touchedWindow.targetFlags = targetFlags;
4565 touchedWindow.pointerIds = pointerIds;
4566}
4567
4568void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4569 for (size_t i = 0; i < windows.size(); i++) {
4570 if (windows.itemAt(i).windowHandle == windowHandle) {
4571 windows.removeAt(i);
4572 return;
4573 }
4574 }
4575}
4576
4577void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4578 for (size_t i = 0 ; i < windows.size(); ) {
4579 TouchedWindow& window = windows.editItemAt(i);
4580 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4581 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4582 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4583 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4584 i += 1;
4585 } else {
4586 windows.removeAt(i);
4587 }
4588 }
4589}
4590
4591sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4592 for (size_t i = 0; i < windows.size(); i++) {
4593 const TouchedWindow& window = windows.itemAt(i);
4594 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4595 return window.windowHandle;
4596 }
4597 }
4598 return NULL;
4599}
4600
4601bool InputDispatcher::TouchState::isSlippery() const {
4602 // Must have exactly one foreground window.
4603 bool haveSlipperyForegroundWindow = false;
4604 for (size_t i = 0; i < windows.size(); i++) {
4605 const TouchedWindow& window = windows.itemAt(i);
4606 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4607 if (haveSlipperyForegroundWindow
4608 || !(window.windowHandle->getInfo()->layoutParamsFlags
4609 & InputWindowInfo::FLAG_SLIPPERY)) {
4610 return false;
4611 }
4612 haveSlipperyForegroundWindow = true;
4613 }
4614 }
4615 return haveSlipperyForegroundWindow;
4616}
4617
4618
4619// --- InputDispatcherThread ---
4620
4621InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4622 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4623}
4624
4625InputDispatcherThread::~InputDispatcherThread() {
4626}
4627
4628bool InputDispatcherThread::threadLoop() {
4629 mDispatcher->dispatchOnce();
4630 return true;
4631}
4632
4633} // namespace android