blob: c3f4f58f58d4373ab9d96a0b9ab65c1276b92136 [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
108static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
109 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
110 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
111}
112
113static bool isValidKeyAction(int32_t action) {
114 switch (action) {
115 case AKEY_EVENT_ACTION_DOWN:
116 case AKEY_EVENT_ACTION_UP:
117 return true;
118 default:
119 return false;
120 }
121}
122
123static bool validateKeyEvent(int32_t action) {
124 if (! isValidKeyAction(action)) {
125 ALOGE("Key event has invalid action code 0x%x", action);
126 return false;
127 }
128 return true;
129}
130
Michael Wright7b159c92015-05-14 14:48:03 +0100131static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800132 switch (action & AMOTION_EVENT_ACTION_MASK) {
133 case AMOTION_EVENT_ACTION_DOWN:
134 case AMOTION_EVENT_ACTION_UP:
135 case AMOTION_EVENT_ACTION_CANCEL:
136 case AMOTION_EVENT_ACTION_MOVE:
137 case AMOTION_EVENT_ACTION_OUTSIDE:
138 case AMOTION_EVENT_ACTION_HOVER_ENTER:
139 case AMOTION_EVENT_ACTION_HOVER_MOVE:
140 case AMOTION_EVENT_ACTION_HOVER_EXIT:
141 case AMOTION_EVENT_ACTION_SCROLL:
142 return true;
143 case AMOTION_EVENT_ACTION_POINTER_DOWN:
144 case AMOTION_EVENT_ACTION_POINTER_UP: {
145 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800146 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800147 }
Michael Wright7b159c92015-05-14 14:48:03 +0100148 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
149 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
150 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800151 default:
152 return false;
153 }
154}
155
Michael Wright7b159c92015-05-14 14:48:03 +0100156static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800157 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100158 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800159 ALOGE("Motion event has invalid action code 0x%x", action);
160 return false;
161 }
162 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000163 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800164 pointerCount, MAX_POINTERS);
165 return false;
166 }
167 BitSet32 pointerIdBits;
168 for (size_t i = 0; i < pointerCount; i++) {
169 int32_t id = pointerProperties[i].id;
170 if (id < 0 || id > MAX_POINTER_ID) {
171 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
172 id, MAX_POINTER_ID);
173 return false;
174 }
175 if (pointerIdBits.hasBit(id)) {
176 ALOGE("Motion event has duplicate pointer id %d", id);
177 return false;
178 }
179 pointerIdBits.markBit(id);
180 }
181 return true;
182}
183
184static bool isMainDisplay(int32_t displayId) {
185 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
186}
187
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800188static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800190 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 return;
192 }
193
194 bool first = true;
195 Region::const_iterator cur = region.begin();
196 Region::const_iterator const tail = region.end();
197 while (cur != tail) {
198 if (first) {
199 first = false;
200 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800201 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800203 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800204 cur++;
205 }
206}
207
208
209// --- InputDispatcher ---
210
211InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
212 mPolicy(policy),
Michael Wright3a981722015-06-10 15:26:13 +0100213 mPendingEvent(NULL), mLastDropReason(DROP_REASON_NOT_DROPPED),
214 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215 mNextUnblockedEvent(NULL),
216 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
217 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
218 mLooper = new Looper(false);
219
220 mKeyRepeatState.lastKeyEntry = NULL;
221
222 policy->getDispatcherConfiguration(&mConfig);
223}
224
225InputDispatcher::~InputDispatcher() {
226 { // acquire lock
227 AutoMutex _l(mLock);
228
229 resetKeyRepeatLocked();
230 releasePendingEventLocked();
231 drainInboundQueueLocked();
232 }
233
234 while (mConnectionsByFd.size() != 0) {
235 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
236 }
237}
238
239void InputDispatcher::dispatchOnce() {
240 nsecs_t nextWakeupTime = LONG_LONG_MAX;
241 { // acquire lock
242 AutoMutex _l(mLock);
243 mDispatcherIsAliveCondition.broadcast();
244
245 // Run a dispatch loop if there are no pending commands.
246 // The dispatch loop might enqueue commands to run afterwards.
247 if (!haveCommandsLocked()) {
248 dispatchOnceInnerLocked(&nextWakeupTime);
249 }
250
251 // Run all pending commands if there are any.
252 // If any commands were run then force the next poll to wake up immediately.
253 if (runCommandsLockedInterruptible()) {
254 nextWakeupTime = LONG_LONG_MIN;
255 }
256 } // release lock
257
258 // Wait for callback or timeout or wake. (make sure we round up, not down)
259 nsecs_t currentTime = now();
260 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
261 mLooper->pollOnce(timeoutMillis);
262}
263
264void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
265 nsecs_t currentTime = now();
266
Jeff Browndc5992e2014-04-11 01:27:26 -0700267 // Reset the key repeat timer whenever normal dispatch is suspended while the
268 // device is in a non-interactive state. This is to ensure that we abort a key
269 // repeat if the device is just coming out of sleep.
270 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800271 resetKeyRepeatLocked();
272 }
273
274 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
275 if (mDispatchFrozen) {
276#if DEBUG_FOCUS
277 ALOGD("Dispatch frozen. Waiting some more.");
278#endif
279 return;
280 }
281
282 // Optimize latency of app switches.
283 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
284 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
285 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
286 if (mAppSwitchDueTime < *nextWakeupTime) {
287 *nextWakeupTime = mAppSwitchDueTime;
288 }
289
290 // Ready to start a new event.
291 // If we don't already have a pending event, go grab one.
292 if (! mPendingEvent) {
293 if (mInboundQueue.isEmpty()) {
294 if (isAppSwitchDue) {
295 // The inbound queue is empty so the app switch key we were waiting
296 // for will never arrive. Stop waiting for it.
297 resetPendingAppSwitchLocked(false);
298 isAppSwitchDue = false;
299 }
300
301 // Synthesize a key repeat if appropriate.
302 if (mKeyRepeatState.lastKeyEntry) {
303 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
304 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
305 } else {
306 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
307 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
308 }
309 }
310 }
311
312 // Nothing to do if there is no pending event.
313 if (!mPendingEvent) {
314 return;
315 }
316 } else {
317 // Inbound queue has at least one entry.
318 mPendingEvent = mInboundQueue.dequeueAtHead();
319 traceInboundQueueLengthLocked();
320 }
321
322 // Poke user activity for this event.
323 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
324 pokeUserActivityLocked(mPendingEvent);
325 }
326
327 // Get ready to dispatch the event.
328 resetANRTimeoutsLocked();
329 }
330
331 // Now we have an event to dispatch.
332 // All events are eventually dequeued and processed this way, even if we intend to drop them.
333 ALOG_ASSERT(mPendingEvent != NULL);
334 bool done = false;
335 DropReason dropReason = DROP_REASON_NOT_DROPPED;
336 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
337 dropReason = DROP_REASON_POLICY;
338 } else if (!mDispatchEnabled) {
339 dropReason = DROP_REASON_DISABLED;
340 }
341
342 if (mNextUnblockedEvent == mPendingEvent) {
343 mNextUnblockedEvent = NULL;
344 }
345
346 switch (mPendingEvent->type) {
347 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
348 ConfigurationChangedEntry* typedEntry =
349 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
350 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
351 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
352 break;
353 }
354
355 case EventEntry::TYPE_DEVICE_RESET: {
356 DeviceResetEntry* typedEntry =
357 static_cast<DeviceResetEntry*>(mPendingEvent);
358 done = dispatchDeviceResetLocked(currentTime, typedEntry);
359 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
360 break;
361 }
362
363 case EventEntry::TYPE_KEY: {
364 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
365 if (isAppSwitchDue) {
366 if (isAppSwitchKeyEventLocked(typedEntry)) {
367 resetPendingAppSwitchLocked(true);
368 isAppSwitchDue = false;
369 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
370 dropReason = DROP_REASON_APP_SWITCH;
371 }
372 }
373 if (dropReason == DROP_REASON_NOT_DROPPED
374 && isStaleEventLocked(currentTime, typedEntry)) {
375 dropReason = DROP_REASON_STALE;
376 }
377 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
378 dropReason = DROP_REASON_BLOCKED;
379 }
380 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
381 break;
382 }
383
384 case EventEntry::TYPE_MOTION: {
385 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
386 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
387 dropReason = DROP_REASON_APP_SWITCH;
388 }
389 if (dropReason == DROP_REASON_NOT_DROPPED
390 && isStaleEventLocked(currentTime, typedEntry)) {
391 dropReason = DROP_REASON_STALE;
392 }
393 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
394 dropReason = DROP_REASON_BLOCKED;
395 }
396 done = dispatchMotionLocked(currentTime, typedEntry,
397 &dropReason, nextWakeupTime);
398 break;
399 }
400
401 default:
402 ALOG_ASSERT(false);
403 break;
404 }
405
406 if (done) {
407 if (dropReason != DROP_REASON_NOT_DROPPED) {
408 dropInboundEventLocked(mPendingEvent, dropReason);
409 }
Michael Wright3a981722015-06-10 15:26:13 +0100410 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411
412 releasePendingEventLocked();
413 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
414 }
415}
416
417bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
418 bool needWake = mInboundQueue.isEmpty();
419 mInboundQueue.enqueueAtTail(entry);
420 traceInboundQueueLengthLocked();
421
422 switch (entry->type) {
423 case EventEntry::TYPE_KEY: {
424 // Optimize app switch latency.
425 // If the application takes too long to catch up then we drop all events preceding
426 // the app switch key.
427 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
428 if (isAppSwitchKeyEventLocked(keyEntry)) {
429 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
430 mAppSwitchSawKeyDown = true;
431 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
432 if (mAppSwitchSawKeyDown) {
433#if DEBUG_APP_SWITCH
434 ALOGD("App switch is pending!");
435#endif
436 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
437 mAppSwitchSawKeyDown = false;
438 needWake = true;
439 }
440 }
441 }
442 break;
443 }
444
445 case EventEntry::TYPE_MOTION: {
446 // Optimize case where the current application is unresponsive and the user
447 // decides to touch a window in a different application.
448 // If the application takes too long to catch up then we drop all events preceding
449 // the touch into the other window.
450 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
451 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
452 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
453 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
454 && mInputTargetWaitApplicationHandle != NULL) {
455 int32_t displayId = motionEntry->displayId;
456 int32_t x = int32_t(motionEntry->pointerCoords[0].
457 getAxisValue(AMOTION_EVENT_AXIS_X));
458 int32_t y = int32_t(motionEntry->pointerCoords[0].
459 getAxisValue(AMOTION_EVENT_AXIS_Y));
460 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
461 if (touchedWindowHandle != NULL
462 && touchedWindowHandle->inputApplicationHandle
463 != mInputTargetWaitApplicationHandle) {
464 // User touched a different application than the one we are waiting on.
465 // Flag the event, and start pruning the input queue.
466 mNextUnblockedEvent = motionEntry;
467 needWake = true;
468 }
469 }
470 break;
471 }
472 }
473
474 return needWake;
475}
476
477void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
478 entry->refCount += 1;
479 mRecentQueue.enqueueAtTail(entry);
480 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
481 mRecentQueue.dequeueAtHead()->release();
482 }
483}
484
485sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
486 int32_t x, int32_t y) {
487 // Traverse windows from front to back to find touched window.
488 size_t numWindows = mWindowHandles.size();
489 for (size_t i = 0; i < numWindows; i++) {
490 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
491 const InputWindowInfo* windowInfo = windowHandle->getInfo();
492 if (windowInfo->displayId == displayId) {
493 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494
495 if (windowInfo->visible) {
496 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
497 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
498 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
499 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
500 // Found window.
501 return windowHandle;
502 }
503 }
504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 }
506 }
507 return NULL;
508}
509
510void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
511 const char* reason;
512 switch (dropReason) {
513 case DROP_REASON_POLICY:
514#if DEBUG_INBOUND_EVENT_DETAILS
515 ALOGD("Dropped event because policy consumed it.");
516#endif
517 reason = "inbound event was dropped because the policy consumed it";
518 break;
519 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100520 if (mLastDropReason != DROP_REASON_DISABLED) {
521 ALOGI("Dropped event because input dispatch is disabled.");
522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800523 reason = "inbound event was dropped because input dispatch is disabled";
524 break;
525 case DROP_REASON_APP_SWITCH:
526 ALOGI("Dropped event because of pending overdue app switch.");
527 reason = "inbound event was dropped because of pending overdue app switch";
528 break;
529 case DROP_REASON_BLOCKED:
530 ALOGI("Dropped event because the current application is not responding and the user "
531 "has started interacting with a different application.");
532 reason = "inbound event was dropped because the current application is not responding "
533 "and the user has started interacting with a different application";
534 break;
535 case DROP_REASON_STALE:
536 ALOGI("Dropped event because it is stale.");
537 reason = "inbound event was dropped because it is stale";
538 break;
539 default:
540 ALOG_ASSERT(false);
541 return;
542 }
543
544 switch (entry->type) {
545 case EventEntry::TYPE_KEY: {
546 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
547 synthesizeCancelationEventsForAllConnectionsLocked(options);
548 break;
549 }
550 case EventEntry::TYPE_MOTION: {
551 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
552 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
553 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
554 synthesizeCancelationEventsForAllConnectionsLocked(options);
555 } else {
556 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
557 synthesizeCancelationEventsForAllConnectionsLocked(options);
558 }
559 break;
560 }
561 }
562}
563
564bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
565 return keyCode == AKEYCODE_HOME
566 || keyCode == AKEYCODE_ENDCALL
567 || keyCode == AKEYCODE_APP_SWITCH;
568}
569
570bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
571 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
572 && isAppSwitchKeyCode(keyEntry->keyCode)
573 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
574 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
575}
576
577bool InputDispatcher::isAppSwitchPendingLocked() {
578 return mAppSwitchDueTime != LONG_LONG_MAX;
579}
580
581void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
582 mAppSwitchDueTime = LONG_LONG_MAX;
583
584#if DEBUG_APP_SWITCH
585 if (handled) {
586 ALOGD("App switch has arrived.");
587 } else {
588 ALOGD("App switch was abandoned.");
589 }
590#endif
591}
592
593bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
594 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
595}
596
597bool InputDispatcher::haveCommandsLocked() const {
598 return !mCommandQueue.isEmpty();
599}
600
601bool InputDispatcher::runCommandsLockedInterruptible() {
602 if (mCommandQueue.isEmpty()) {
603 return false;
604 }
605
606 do {
607 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
608
609 Command command = commandEntry->command;
610 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
611
612 commandEntry->connection.clear();
613 delete commandEntry;
614 } while (! mCommandQueue.isEmpty());
615 return true;
616}
617
618InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
619 CommandEntry* commandEntry = new CommandEntry(command);
620 mCommandQueue.enqueueAtTail(commandEntry);
621 return commandEntry;
622}
623
624void InputDispatcher::drainInboundQueueLocked() {
625 while (! mInboundQueue.isEmpty()) {
626 EventEntry* entry = mInboundQueue.dequeueAtHead();
627 releaseInboundEventLocked(entry);
628 }
629 traceInboundQueueLengthLocked();
630}
631
632void InputDispatcher::releasePendingEventLocked() {
633 if (mPendingEvent) {
634 resetANRTimeoutsLocked();
635 releaseInboundEventLocked(mPendingEvent);
636 mPendingEvent = NULL;
637 }
638}
639
640void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
641 InjectionState* injectionState = entry->injectionState;
642 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
643#if DEBUG_DISPATCH_CYCLE
644 ALOGD("Injected inbound event was dropped.");
645#endif
646 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
647 }
648 if (entry == mNextUnblockedEvent) {
649 mNextUnblockedEvent = NULL;
650 }
651 addRecentEventLocked(entry);
652 entry->release();
653}
654
655void InputDispatcher::resetKeyRepeatLocked() {
656 if (mKeyRepeatState.lastKeyEntry) {
657 mKeyRepeatState.lastKeyEntry->release();
658 mKeyRepeatState.lastKeyEntry = NULL;
659 }
660}
661
662InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
663 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
664
665 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700666 uint32_t policyFlags = entry->policyFlags &
667 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 if (entry->refCount == 1) {
669 entry->recycle();
670 entry->eventTime = currentTime;
671 entry->policyFlags = policyFlags;
672 entry->repeatCount += 1;
673 } else {
674 KeyEntry* newEntry = new KeyEntry(currentTime,
675 entry->deviceId, entry->source, policyFlags,
676 entry->action, entry->flags, entry->keyCode, entry->scanCode,
677 entry->metaState, entry->repeatCount + 1, entry->downTime);
678
679 mKeyRepeatState.lastKeyEntry = newEntry;
680 entry->release();
681
682 entry = newEntry;
683 }
684 entry->syntheticRepeat = true;
685
686 // Increment reference count since we keep a reference to the event in
687 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
688 entry->refCount += 1;
689
690 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
691 return entry;
692}
693
694bool InputDispatcher::dispatchConfigurationChangedLocked(
695 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
696#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700697 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698#endif
699
700 // Reset key repeating in case a keyboard device was added or removed or something.
701 resetKeyRepeatLocked();
702
703 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
704 CommandEntry* commandEntry = postCommandLocked(
705 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
706 commandEntry->eventTime = entry->eventTime;
707 return true;
708}
709
710bool InputDispatcher::dispatchDeviceResetLocked(
711 nsecs_t currentTime, DeviceResetEntry* entry) {
712#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700713 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
714 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715#endif
716
717 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
718 "device was reset");
719 options.deviceId = entry->deviceId;
720 synthesizeCancelationEventsForAllConnectionsLocked(options);
721 return true;
722}
723
724bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
725 DropReason* dropReason, nsecs_t* nextWakeupTime) {
726 // Preprocessing.
727 if (! entry->dispatchInProgress) {
728 if (entry->repeatCount == 0
729 && entry->action == AKEY_EVENT_ACTION_DOWN
730 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
731 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
732 if (mKeyRepeatState.lastKeyEntry
733 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
734 // We have seen two identical key downs in a row which indicates that the device
735 // driver is automatically generating key repeats itself. We take note of the
736 // repeat here, but we disable our own next key repeat timer since it is clear that
737 // we will not need to synthesize key repeats ourselves.
738 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
739 resetKeyRepeatLocked();
740 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
741 } else {
742 // Not a repeat. Save key down state in case we do see a repeat later.
743 resetKeyRepeatLocked();
744 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
745 }
746 mKeyRepeatState.lastKeyEntry = entry;
747 entry->refCount += 1;
748 } else if (! entry->syntheticRepeat) {
749 resetKeyRepeatLocked();
750 }
751
752 if (entry->repeatCount == 1) {
753 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
754 } else {
755 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
756 }
757
758 entry->dispatchInProgress = true;
759
760 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
761 }
762
763 // Handle case where the policy asked us to try again later last time.
764 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
765 if (currentTime < entry->interceptKeyWakeupTime) {
766 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
767 *nextWakeupTime = entry->interceptKeyWakeupTime;
768 }
769 return false; // wait until next wakeup
770 }
771 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
772 entry->interceptKeyWakeupTime = 0;
773 }
774
775 // Give the policy a chance to intercept the key.
776 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
777 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
778 CommandEntry* commandEntry = postCommandLocked(
779 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
780 if (mFocusedWindowHandle != NULL) {
781 commandEntry->inputWindowHandle = mFocusedWindowHandle;
782 }
783 commandEntry->keyEntry = entry;
784 entry->refCount += 1;
785 return false; // wait for the command to run
786 } else {
787 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
788 }
789 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
790 if (*dropReason == DROP_REASON_NOT_DROPPED) {
791 *dropReason = DROP_REASON_POLICY;
792 }
793 }
794
795 // Clean up if dropping the event.
796 if (*dropReason != DROP_REASON_NOT_DROPPED) {
797 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
798 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
799 return true;
800 }
801
802 // Identify targets.
803 Vector<InputTarget> inputTargets;
804 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
805 entry, inputTargets, nextWakeupTime);
806 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
807 return false;
808 }
809
810 setInjectionResultLocked(entry, injectionResult);
811 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
812 return true;
813 }
814
815 addMonitoringTargetsLocked(inputTargets);
816
817 // Dispatch the key.
818 dispatchEventLocked(currentTime, entry, inputTargets);
819 return true;
820}
821
822void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
823#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700824 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, policyFlags=0x%x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825 "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700826 "repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 prefix,
828 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
829 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
830 entry->repeatCount, entry->downTime);
831#endif
832}
833
834bool InputDispatcher::dispatchMotionLocked(
835 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
836 // Preprocessing.
837 if (! entry->dispatchInProgress) {
838 entry->dispatchInProgress = true;
839
840 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
841 }
842
843 // Clean up if dropping the event.
844 if (*dropReason != DROP_REASON_NOT_DROPPED) {
845 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
846 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
847 return true;
848 }
849
850 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
851
852 // Identify targets.
853 Vector<InputTarget> inputTargets;
854
855 bool conflictingPointerActions = false;
856 int32_t injectionResult;
857 if (isPointerEvent) {
858 // Pointer event. (eg. touchscreen)
859 injectionResult = findTouchedWindowTargetsLocked(currentTime,
860 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
861 } else {
862 // Non touch event. (eg. trackball)
863 injectionResult = findFocusedWindowTargetsLocked(currentTime,
864 entry, inputTargets, nextWakeupTime);
865 }
866 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
867 return false;
868 }
869
870 setInjectionResultLocked(entry, injectionResult);
871 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100872 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
873 CancelationOptions::Mode mode(isPointerEvent ?
874 CancelationOptions::CANCEL_POINTER_EVENTS :
875 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
876 CancelationOptions options(mode, "input event injection failed");
877 synthesizeCancelationEventsForMonitorsLocked(options);
878 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879 return true;
880 }
881
Tarandeep Singh48aeb512017-07-17 11:22:52 -0700882 addMonitoringTargetsLocked(inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883
884 // Dispatch the motion.
885 if (conflictingPointerActions) {
886 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
887 "conflicting pointer actions");
888 synthesizeCancelationEventsForAllConnectionsLocked(options);
889 }
890 dispatchEventLocked(currentTime, entry, inputTargets);
891 return true;
892}
893
894
895void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
896#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700897 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100898 "action=0x%x, actionButton=0x%x, flags=0x%x, "
899 "metaState=0x%x, buttonState=0x%x,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700900 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 prefix,
902 entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100903 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 entry->metaState, entry->buttonState,
905 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
906 entry->downTime);
907
908 for (uint32_t i = 0; i < entry->pointerCount; i++) {
909 ALOGD(" Pointer %d: id=%d, toolType=%d, "
910 "x=%f, y=%f, pressure=%f, size=%f, "
911 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800912 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913 i, entry->pointerProperties[i].id,
914 entry->pointerProperties[i].toolType,
915 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
916 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
917 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
918 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
919 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
920 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
921 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
922 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800923 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 }
925#endif
926}
927
928void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
929 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
930#if DEBUG_DISPATCH_CYCLE
931 ALOGD("dispatchEventToCurrentInputTargets");
932#endif
933
934 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
935
936 pokeUserActivityLocked(eventEntry);
937
938 for (size_t i = 0; i < inputTargets.size(); i++) {
939 const InputTarget& inputTarget = inputTargets.itemAt(i);
940
941 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
942 if (connectionIndex >= 0) {
943 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
944 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
945 } else {
946#if DEBUG_FOCUS
947 ALOGD("Dropping event delivery to target with channel '%s' because it "
948 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800949 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950#endif
951 }
952 }
953}
954
955int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
956 const EventEntry* entry,
957 const sp<InputApplicationHandle>& applicationHandle,
958 const sp<InputWindowHandle>& windowHandle,
959 nsecs_t* nextWakeupTime, const char* reason) {
960 if (applicationHandle == NULL && windowHandle == NULL) {
961 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
962#if DEBUG_FOCUS
963 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
964#endif
965 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
966 mInputTargetWaitStartTime = currentTime;
967 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
968 mInputTargetWaitTimeoutExpired = false;
969 mInputTargetWaitApplicationHandle.clear();
970 }
971 } else {
972 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
973#if DEBUG_FOCUS
974 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800975 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976 reason);
977#endif
978 nsecs_t timeout;
979 if (windowHandle != NULL) {
980 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
981 } else if (applicationHandle != NULL) {
982 timeout = applicationHandle->getDispatchingTimeout(
983 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
984 } else {
985 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
986 }
987
988 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
989 mInputTargetWaitStartTime = currentTime;
990 mInputTargetWaitTimeoutTime = currentTime + timeout;
991 mInputTargetWaitTimeoutExpired = false;
992 mInputTargetWaitApplicationHandle.clear();
993
994 if (windowHandle != NULL) {
995 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
996 }
997 if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
998 mInputTargetWaitApplicationHandle = applicationHandle;
999 }
1000 }
1001 }
1002
1003 if (mInputTargetWaitTimeoutExpired) {
1004 return INPUT_EVENT_INJECTION_TIMED_OUT;
1005 }
1006
1007 if (currentTime >= mInputTargetWaitTimeoutTime) {
1008 onANRLocked(currentTime, applicationHandle, windowHandle,
1009 entry->eventTime, mInputTargetWaitStartTime, reason);
1010
1011 // Force poll loop to wake up immediately on next iteration once we get the
1012 // ANR response back from the policy.
1013 *nextWakeupTime = LONG_LONG_MIN;
1014 return INPUT_EVENT_INJECTION_PENDING;
1015 } else {
1016 // Force poll loop to wake up when timeout is due.
1017 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1018 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1019 }
1020 return INPUT_EVENT_INJECTION_PENDING;
1021 }
1022}
1023
1024void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1025 const sp<InputChannel>& inputChannel) {
1026 if (newTimeout > 0) {
1027 // Extend the timeout.
1028 mInputTargetWaitTimeoutTime = now() + newTimeout;
1029 } else {
1030 // Give up.
1031 mInputTargetWaitTimeoutExpired = true;
1032
1033 // Input state will not be realistic. Mark it out of sync.
1034 if (inputChannel.get()) {
1035 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1036 if (connectionIndex >= 0) {
1037 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1038 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1039
1040 if (windowHandle != NULL) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001041 const InputWindowInfo* info = windowHandle->getInfo();
1042 if (info) {
1043 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId);
1044 if (stateIndex >= 0) {
1045 mTouchStatesByDisplay.editValueAt(stateIndex).removeWindow(
1046 windowHandle);
1047 }
1048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 }
1050
1051 if (connection->status == Connection::STATUS_NORMAL) {
1052 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1053 "application not responding");
1054 synthesizeCancelationEventsForConnectionLocked(connection, options);
1055 }
1056 }
1057 }
1058 }
1059}
1060
1061nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1062 nsecs_t currentTime) {
1063 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1064 return currentTime - mInputTargetWaitStartTime;
1065 }
1066 return 0;
1067}
1068
1069void InputDispatcher::resetANRTimeoutsLocked() {
1070#if DEBUG_FOCUS
1071 ALOGD("Resetting ANR timeouts.");
1072#endif
1073
1074 // Reset input target wait timeout.
1075 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1076 mInputTargetWaitApplicationHandle.clear();
1077}
1078
1079int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1080 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1081 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001082 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083
1084 // If there is no currently focused window and no focused application
1085 // then drop the event.
1086 if (mFocusedWindowHandle == NULL) {
1087 if (mFocusedApplicationHandle != NULL) {
1088 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
1089 mFocusedApplicationHandle, NULL, nextWakeupTime,
1090 "Waiting because no window has focus but there is a "
1091 "focused application that may eventually add a window "
1092 "when it finishes starting up.");
1093 goto Unresponsive;
1094 }
1095
1096 ALOGI("Dropping event because there is no focused window or focused application.");
1097 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1098 goto Failed;
1099 }
1100
1101 // Check permissions.
1102 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
1103 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1104 goto Failed;
1105 }
1106
Jeff Brownffb49772014-10-10 19:01:34 -07001107 // Check whether the window is ready for more input.
1108 reason = checkWindowReadyForMoreInputLocked(currentTime,
1109 mFocusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001110 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001112 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 goto Unresponsive;
1114 }
1115
1116 // Success! Output targets.
1117 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1118 addWindowTargetLocked(mFocusedWindowHandle,
1119 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1120 inputTargets);
1121
1122 // Done.
1123Failed:
1124Unresponsive:
1125 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1126 updateDispatchStatisticsLocked(currentTime, entry,
1127 injectionResult, timeSpentWaitingForApplication);
1128#if DEBUG_FOCUS
1129 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1130 "timeSpentWaitingForApplication=%0.1fms",
1131 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1132#endif
1133 return injectionResult;
1134}
1135
1136int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1137 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1138 bool* outConflictingPointerActions) {
1139 enum InjectionPermission {
1140 INJECTION_PERMISSION_UNKNOWN,
1141 INJECTION_PERMISSION_GRANTED,
1142 INJECTION_PERMISSION_DENIED
1143 };
1144
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145 // For security reasons, we defer updating the touch state until we are sure that
1146 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 int32_t displayId = entry->displayId;
1148 int32_t action = entry->action;
1149 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1150
1151 // Update the touch state as needed based on the properties of the touch event.
1152 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1153 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1154 sp<InputWindowHandle> newHoverWindowHandle;
1155
Jeff Brownf086ddb2014-02-11 14:28:48 -08001156 // Copy current touch state into mTempTouchState.
1157 // This state is always reset at the end of this function, so if we don't find state
1158 // for the specified display then our initial state will be empty.
1159 const TouchState* oldState = NULL;
1160 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1161 if (oldStateIndex >= 0) {
1162 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1163 mTempTouchState.copyFrom(*oldState);
1164 }
1165
1166 bool isSplit = mTempTouchState.split;
1167 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1168 && (mTempTouchState.deviceId != entry->deviceId
1169 || mTempTouchState.source != entry->source
1170 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1172 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1173 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1174 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1175 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1176 || isHoverAction);
1177 bool wrongDevice = false;
1178 if (newGesture) {
1179 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001180 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181#if DEBUG_FOCUS
1182 ALOGD("Dropping event because a pointer for a different device is already down.");
1183#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001184 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1186 switchedDevice = false;
1187 wrongDevice = true;
1188 goto Failed;
1189 }
1190 mTempTouchState.reset();
1191 mTempTouchState.down = down;
1192 mTempTouchState.deviceId = entry->deviceId;
1193 mTempTouchState.source = entry->source;
1194 mTempTouchState.displayId = displayId;
1195 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001196 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1197#if DEBUG_FOCUS
1198 ALOGI("Dropping move event because a pointer for a different device is already active.");
1199#endif
1200 // TODO: test multiple simultaneous input streams.
1201 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1202 switchedDevice = false;
1203 wrongDevice = true;
1204 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 }
1206
1207 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1208 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1209
1210 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1211 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1212 getAxisValue(AMOTION_EVENT_AXIS_X));
1213 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1214 getAxisValue(AMOTION_EVENT_AXIS_Y));
1215 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 bool isTouchModal = false;
1217
1218 // Traverse windows from front to back to find touched window and outside targets.
1219 size_t numWindows = mWindowHandles.size();
1220 for (size_t i = 0; i < numWindows; i++) {
1221 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1222 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1223 if (windowInfo->displayId != displayId) {
1224 continue; // wrong display
1225 }
1226
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 int32_t flags = windowInfo->layoutParamsFlags;
1228 if (windowInfo->visible) {
1229 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1230 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1231 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1232 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001233 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 break; // found touched window, exit window loop
1235 }
1236 }
1237
1238 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1239 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001241 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001242 }
1243 }
1244 }
1245
Michael Wrightd02c5b62014-02-10 15:10:22 -08001246 // Figure out whether splitting will be allowed for this window.
1247 if (newTouchedWindowHandle != NULL
1248 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1249 // New window supports splitting.
1250 isSplit = true;
1251 } else if (isSplit) {
1252 // New window does not support splitting but we have already split events.
1253 // Ignore the new window.
1254 newTouchedWindowHandle = NULL;
1255 }
1256
1257 // Handle the case where we did not find a window.
1258 if (newTouchedWindowHandle == NULL) {
1259 // Try to assign the pointer to the first foreground window we find, if there is one.
1260 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
1261 if (newTouchedWindowHandle == NULL) {
1262 ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y);
1263 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1264 goto Failed;
1265 }
1266 }
1267
1268 // Set target flags.
1269 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1270 if (isSplit) {
1271 targetFlags |= InputTarget::FLAG_SPLIT;
1272 }
1273 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1274 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001275 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1276 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 }
1278
1279 // Update hover state.
1280 if (isHoverAction) {
1281 newHoverWindowHandle = newTouchedWindowHandle;
1282 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1283 newHoverWindowHandle = mLastHoverWindowHandle;
1284 }
1285
1286 // Update the temporary touch state.
1287 BitSet32 pointerIds;
1288 if (isSplit) {
1289 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1290 pointerIds.markBit(pointerId);
1291 }
1292 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1293 } else {
1294 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1295
1296 // If the pointer is not currently down, then ignore the event.
1297 if (! mTempTouchState.down) {
1298#if DEBUG_FOCUS
1299 ALOGD("Dropping event because the pointer is not down or we previously "
1300 "dropped the pointer down event.");
1301#endif
1302 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1303 goto Failed;
1304 }
1305
1306 // Check whether touches should slip outside of the current foreground window.
1307 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1308 && entry->pointerCount == 1
1309 && mTempTouchState.isSlippery()) {
1310 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1311 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1312
1313 sp<InputWindowHandle> oldTouchedWindowHandle =
1314 mTempTouchState.getFirstForegroundWindowHandle();
1315 sp<InputWindowHandle> newTouchedWindowHandle =
1316 findTouchedWindowAtLocked(displayId, x, y);
1317 if (oldTouchedWindowHandle != newTouchedWindowHandle
1318 && newTouchedWindowHandle != NULL) {
1319#if DEBUG_FOCUS
1320 ALOGD("Touch is slipping out of window %s into window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001321 oldTouchedWindowHandle->getName().c_str(),
1322 newTouchedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323#endif
1324 // Make a slippery exit from the old window.
1325 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1326 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1327
1328 // Make a slippery entrance into the new window.
1329 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1330 isSplit = true;
1331 }
1332
1333 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1334 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1335 if (isSplit) {
1336 targetFlags |= InputTarget::FLAG_SPLIT;
1337 }
1338 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1339 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1340 }
1341
1342 BitSet32 pointerIds;
1343 if (isSplit) {
1344 pointerIds.markBit(entry->pointerProperties[0].id);
1345 }
1346 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1347 }
1348 }
1349 }
1350
1351 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1352 // Let the previous window know that the hover sequence is over.
1353 if (mLastHoverWindowHandle != NULL) {
1354#if DEBUG_HOVER
1355 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001356 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357#endif
1358 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1359 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1360 }
1361
1362 // Let the new window know that the hover sequence is starting.
1363 if (newHoverWindowHandle != NULL) {
1364#if DEBUG_HOVER
1365 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001366 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001367#endif
1368 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1369 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1370 }
1371 }
1372
1373 // Check permission to inject into all touched foreground windows and ensure there
1374 // is at least one touched foreground window.
1375 {
1376 bool haveForegroundWindow = false;
1377 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1378 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1379 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1380 haveForegroundWindow = true;
1381 if (! checkInjectionPermission(touchedWindow.windowHandle,
1382 entry->injectionState)) {
1383 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1384 injectionPermission = INJECTION_PERMISSION_DENIED;
1385 goto Failed;
1386 }
1387 }
1388 }
1389 if (! haveForegroundWindow) {
1390#if DEBUG_FOCUS
1391 ALOGD("Dropping event because there is no touched foreground window to receive it.");
1392#endif
1393 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1394 goto Failed;
1395 }
1396
1397 // Permission granted to injection into all touched foreground windows.
1398 injectionPermission = INJECTION_PERMISSION_GRANTED;
1399 }
1400
1401 // Check whether windows listening for outside touches are owned by the same UID. If it is
1402 // set the policy flag that we will not reveal coordinate information to this window.
1403 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1404 sp<InputWindowHandle> foregroundWindowHandle =
1405 mTempTouchState.getFirstForegroundWindowHandle();
1406 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1407 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1408 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1409 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1410 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1411 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1412 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1413 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1414 }
1415 }
1416 }
1417 }
1418
1419 // Ensure all touched foreground windows are ready for new input.
1420 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1421 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1422 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001423 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001424 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001425 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001426 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001428 NULL, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429 goto Unresponsive;
1430 }
1431 }
1432 }
1433
1434 // If this is the first pointer going down and the touched window has a wallpaper
1435 // then also add the touched wallpaper windows so they are locked in for the duration
1436 // of the touch gesture.
1437 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1438 // engine only supports touch events. We would need to add a mechanism similar
1439 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1440 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1441 sp<InputWindowHandle> foregroundWindowHandle =
1442 mTempTouchState.getFirstForegroundWindowHandle();
1443 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
1444 for (size_t i = 0; i < mWindowHandles.size(); i++) {
1445 sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
1446 const InputWindowInfo* info = windowHandle->getInfo();
1447 if (info->displayId == displayId
1448 && windowHandle->getInfo()->layoutParamsType
1449 == InputWindowInfo::TYPE_WALLPAPER) {
1450 mTempTouchState.addOrUpdateWindow(windowHandle,
1451 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001452 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 | InputTarget::FLAG_DISPATCH_AS_IS,
1454 BitSet32(0));
1455 }
1456 }
1457 }
1458 }
1459
1460 // Success! Output targets.
1461 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1462
1463 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1464 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1465 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1466 touchedWindow.pointerIds, inputTargets);
1467 }
1468
1469 // Drop the outside or hover touch windows since we will not care about them
1470 // in the next iteration.
1471 mTempTouchState.filterNonAsIsTouchWindows();
1472
1473Failed:
1474 // Check injection permission once and for all.
1475 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
1476 if (checkInjectionPermission(NULL, entry->injectionState)) {
1477 injectionPermission = INJECTION_PERMISSION_GRANTED;
1478 } else {
1479 injectionPermission = INJECTION_PERMISSION_DENIED;
1480 }
1481 }
1482
1483 // Update final pieces of touch state if the injector had permission.
1484 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1485 if (!wrongDevice) {
1486 if (switchedDevice) {
1487#if DEBUG_FOCUS
1488 ALOGD("Conflicting pointer actions: Switched to a different device.");
1489#endif
1490 *outConflictingPointerActions = true;
1491 }
1492
1493 if (isHoverAction) {
1494 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001495 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496#if DEBUG_FOCUS
1497 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1498#endif
1499 *outConflictingPointerActions = true;
1500 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001501 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1503 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001504 mTempTouchState.deviceId = entry->deviceId;
1505 mTempTouchState.source = entry->source;
1506 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 }
1508 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1509 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1510 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001511 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1513 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001514 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515#if DEBUG_FOCUS
1516 ALOGD("Conflicting pointer actions: Down received while already down.");
1517#endif
1518 *outConflictingPointerActions = true;
1519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001520 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1521 // One pointer went up.
1522 if (isSplit) {
1523 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1524 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1525
1526 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1527 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1528 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1529 touchedWindow.pointerIds.clearBit(pointerId);
1530 if (touchedWindow.pointerIds.isEmpty()) {
1531 mTempTouchState.windows.removeAt(i);
1532 continue;
1533 }
1534 }
1535 i += 1;
1536 }
1537 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001538 }
1539
1540 // Save changes unless the action was scroll in which case the temporary touch
1541 // state was only valid for this one action.
1542 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1543 if (mTempTouchState.displayId >= 0) {
1544 if (oldStateIndex >= 0) {
1545 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1546 } else {
1547 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1548 }
1549 } else if (oldStateIndex >= 0) {
1550 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 }
1553
1554 // Update hover state.
1555 mLastHoverWindowHandle = newHoverWindowHandle;
1556 }
1557 } else {
1558#if DEBUG_FOCUS
1559 ALOGD("Not updating touch focus because injection was denied.");
1560#endif
1561 }
1562
1563Unresponsive:
1564 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1565 mTempTouchState.reset();
1566
1567 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1568 updateDispatchStatisticsLocked(currentTime, entry,
1569 injectionResult, timeSpentWaitingForApplication);
1570#if DEBUG_FOCUS
1571 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1572 "timeSpentWaitingForApplication=%0.1fms",
1573 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1574#endif
1575 return injectionResult;
1576}
1577
1578void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1579 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1580 inputTargets.push();
1581
1582 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1583 InputTarget& target = inputTargets.editTop();
1584 target.inputChannel = windowInfo->inputChannel;
1585 target.flags = targetFlags;
1586 target.xOffset = - windowInfo->frameLeft;
1587 target.yOffset = - windowInfo->frameTop;
1588 target.scaleFactor = windowInfo->scaleFactor;
1589 target.pointerIds = pointerIds;
1590}
1591
1592void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
1593 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1594 inputTargets.push();
1595
1596 InputTarget& target = inputTargets.editTop();
1597 target.inputChannel = mMonitoringChannels[i];
1598 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1599 target.xOffset = 0;
1600 target.yOffset = 0;
1601 target.pointerIds.clear();
1602 target.scaleFactor = 1.0f;
1603 }
1604}
1605
1606bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1607 const InjectionState* injectionState) {
1608 if (injectionState
1609 && (windowHandle == NULL
1610 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1611 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
1612 if (windowHandle != NULL) {
1613 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1614 "owned by uid %d",
1615 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001616 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617 windowHandle->getInfo()->ownerUid);
1618 } else {
1619 ALOGW("Permission denied: injecting event from pid %d uid %d",
1620 injectionState->injectorPid, injectionState->injectorUid);
1621 }
1622 return false;
1623 }
1624 return true;
1625}
1626
1627bool InputDispatcher::isWindowObscuredAtPointLocked(
1628 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1629 int32_t displayId = windowHandle->getInfo()->displayId;
1630 size_t numWindows = mWindowHandles.size();
1631 for (size_t i = 0; i < numWindows; i++) {
1632 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1633 if (otherHandle == windowHandle) {
1634 break;
1635 }
1636
1637 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1638 if (otherInfo->displayId == displayId
1639 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1640 && otherInfo->frameContainsPoint(x, y)) {
1641 return true;
1642 }
1643 }
1644 return false;
1645}
1646
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001647
1648bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1649 int32_t displayId = windowHandle->getInfo()->displayId;
1650 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1651 size_t numWindows = mWindowHandles.size();
1652 for (size_t i = 0; i < numWindows; i++) {
1653 sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
1654 if (otherHandle == windowHandle) {
1655 break;
1656 }
1657
1658 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1659 if (otherInfo->displayId == displayId
1660 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1661 && otherInfo->overlaps(windowInfo)) {
1662 return true;
1663 }
1664 }
1665 return false;
1666}
1667
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001668std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001669 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1670 const char* targetType) {
1671 // If the window is paused then keep waiting.
1672 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001673 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001674 }
1675
1676 // If the window's connection is not registered then keep waiting.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brownffb49772014-10-10 19:01:34 -07001678 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001679 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001680 "registered with the input dispatcher. The window may be in the process "
1681 "of being removed.", targetType);
1682 }
1683
1684 // If the connection is dead then keep waiting.
1685 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1686 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001687 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001688 "The window may be in the process of being removed.", targetType,
1689 connection->getStatusLabel());
1690 }
1691
1692 // If the connection is backed up then keep waiting.
1693 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001694 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001695 "Outbound queue length: %d. Wait queue length: %d.",
1696 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1697 }
1698
1699 // Ensure that the dispatch queues aren't too far backed up for this event.
1700 if (eventEntry->type == EventEntry::TYPE_KEY) {
1701 // If the event is a key event, then we must wait for all previous events to
1702 // complete before delivering it because previous events may have the
1703 // side-effect of transferring focus to a different window and we want to
1704 // ensure that the following keys are sent to the new window.
1705 //
1706 // Suppose the user touches a button in a window then immediately presses "A".
1707 // If the button causes a pop-up window to appear then we want to ensure that
1708 // the "A" key is delivered to the new pop-up window. This is because users
1709 // often anticipate pending UI changes when typing on a keyboard.
1710 // To obtain this behavior, we must serialize key events with respect to all
1711 // prior input events.
1712 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001713 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001714 "finished processing all of the input events that were previously "
1715 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1716 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 }
Jeff Brownffb49772014-10-10 19:01:34 -07001718 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 // Touch events can always be sent to a window immediately because the user intended
1720 // to touch whatever was visible at the time. Even if focus changes or a new
1721 // window appears moments later, the touch event was meant to be delivered to
1722 // whatever window happened to be on screen at the time.
1723 //
1724 // Generic motion events, such as trackball or joystick events are a little trickier.
1725 // Like key events, generic motion events are delivered to the focused window.
1726 // Unlike key events, generic motion events don't tend to transfer focus to other
1727 // windows and it is not important for them to be serialized. So we prefer to deliver
1728 // generic motion events as soon as possible to improve efficiency and reduce lag
1729 // through batching.
1730 //
1731 // The one case where we pause input event delivery is when the wait queue is piling
1732 // up with lots of events because the application is not responding.
1733 // This condition ensures that ANRs are detected reliably.
1734 if (!connection->waitQueue.isEmpty()
1735 && currentTime >= connection->waitQueue.head->deliveryTime
1736 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001737 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001738 "finished processing certain input events that were delivered to it over "
1739 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1740 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1741 connection->waitQueue.count(),
1742 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 }
1744 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001745 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746}
1747
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001748std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 const sp<InputApplicationHandle>& applicationHandle,
1750 const sp<InputWindowHandle>& windowHandle) {
1751 if (applicationHandle != NULL) {
1752 if (windowHandle != NULL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001753 std::string label(applicationHandle->getName());
1754 label += " - ";
1755 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 return label;
1757 } else {
1758 return applicationHandle->getName();
1759 }
1760 } else if (windowHandle != NULL) {
1761 return windowHandle->getName();
1762 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001763 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764 }
1765}
1766
1767void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
1768 if (mFocusedWindowHandle != NULL) {
1769 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1770 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1771#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001772 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773#endif
1774 return;
1775 }
1776 }
1777
1778 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1779 switch (eventEntry->type) {
1780 case EventEntry::TYPE_MOTION: {
1781 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1782 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1783 return;
1784 }
1785
1786 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1787 eventType = USER_ACTIVITY_EVENT_TOUCH;
1788 }
1789 break;
1790 }
1791 case EventEntry::TYPE_KEY: {
1792 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1793 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1794 return;
1795 }
1796 eventType = USER_ACTIVITY_EVENT_BUTTON;
1797 break;
1798 }
1799 }
1800
1801 CommandEntry* commandEntry = postCommandLocked(
1802 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1803 commandEntry->eventTime = eventEntry->eventTime;
1804 commandEntry->userActivityEventType = eventType;
1805}
1806
1807void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1808 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1809#if DEBUG_DISPATCH_CYCLE
1810 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1811 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1812 "pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001813 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001814 inputTarget->xOffset, inputTarget->yOffset,
1815 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1816#endif
1817
1818 // Skip this event if the connection status is not normal.
1819 // We don't want to enqueue additional outbound events if the connection is broken.
1820 if (connection->status != Connection::STATUS_NORMAL) {
1821#if DEBUG_DISPATCH_CYCLE
1822 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001823 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001824#endif
1825 return;
1826 }
1827
1828 // Split a motion event if needed.
1829 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1830 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1831
1832 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1833 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1834 MotionEntry* splitMotionEntry = splitMotionEvent(
1835 originalMotionEntry, inputTarget->pointerIds);
1836 if (!splitMotionEntry) {
1837 return; // split event was dropped
1838 }
1839#if DEBUG_FOCUS
1840 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001841 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1843#endif
1844 enqueueDispatchEntriesLocked(currentTime, connection,
1845 splitMotionEntry, inputTarget);
1846 splitMotionEntry->release();
1847 return;
1848 }
1849 }
1850
1851 // Not splitting. Enqueue dispatch entries for the event as is.
1852 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1853}
1854
1855void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1856 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1857 bool wasEmpty = connection->outboundQueue.isEmpty();
1858
1859 // Enqueue dispatch entries for the requested modes.
1860 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1861 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1862 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1863 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1864 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1865 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1866 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1867 InputTarget::FLAG_DISPATCH_AS_IS);
1868 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1869 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1870 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1871 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1872
1873 // If the outbound queue was previously empty, start the dispatch cycle going.
1874 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1875 startDispatchCycleLocked(currentTime, connection);
1876 }
1877}
1878
1879void InputDispatcher::enqueueDispatchEntryLocked(
1880 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1881 int32_t dispatchMode) {
1882 int32_t inputTargetFlags = inputTarget->flags;
1883 if (!(inputTargetFlags & dispatchMode)) {
1884 return;
1885 }
1886 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1887
1888 // This is a new event.
1889 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1890 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1891 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1892 inputTarget->scaleFactor);
1893
1894 // Apply target flags and update the connection's input state.
1895 switch (eventEntry->type) {
1896 case EventEntry::TYPE_KEY: {
1897 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1898 dispatchEntry->resolvedAction = keyEntry->action;
1899 dispatchEntry->resolvedFlags = keyEntry->flags;
1900
1901 if (!connection->inputState.trackKey(keyEntry,
1902 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1903#if DEBUG_DISPATCH_CYCLE
1904 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001905 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906#endif
1907 delete dispatchEntry;
1908 return; // skip the inconsistent event
1909 }
1910 break;
1911 }
1912
1913 case EventEntry::TYPE_MOTION: {
1914 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1915 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1916 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1917 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1918 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1919 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1920 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1921 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1922 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1923 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1924 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1925 } else {
1926 dispatchEntry->resolvedAction = motionEntry->action;
1927 }
1928 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1929 && !connection->inputState.isHovering(
1930 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
1931#if DEBUG_DISPATCH_CYCLE
1932 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001933 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001934#endif
1935 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1936 }
1937
1938 dispatchEntry->resolvedFlags = motionEntry->flags;
1939 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1940 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1941 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001942 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
1943 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1944 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945
1946 if (!connection->inputState.trackMotion(motionEntry,
1947 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1948#if DEBUG_DISPATCH_CYCLE
1949 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001950 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001951#endif
1952 delete dispatchEntry;
1953 return; // skip the inconsistent event
1954 }
1955 break;
1956 }
1957 }
1958
1959 // Remember that we are waiting for this dispatch to complete.
1960 if (dispatchEntry->hasForegroundTarget()) {
1961 incrementPendingForegroundDispatchesLocked(eventEntry);
1962 }
1963
1964 // Enqueue the dispatch entry.
1965 connection->outboundQueue.enqueueAtTail(dispatchEntry);
1966 traceOutboundQueueLengthLocked(connection);
1967}
1968
1969void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
1970 const sp<Connection>& connection) {
1971#if DEBUG_DISPATCH_CYCLE
1972 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001973 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974#endif
1975
1976 while (connection->status == Connection::STATUS_NORMAL
1977 && !connection->outboundQueue.isEmpty()) {
1978 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
1979 dispatchEntry->deliveryTime = currentTime;
1980
1981 // Publish the event.
1982 status_t status;
1983 EventEntry* eventEntry = dispatchEntry->eventEntry;
1984 switch (eventEntry->type) {
1985 case EventEntry::TYPE_KEY: {
1986 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1987
1988 // Publish the key event.
1989 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
1990 keyEntry->deviceId, keyEntry->source,
1991 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
1992 keyEntry->keyCode, keyEntry->scanCode,
1993 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
1994 keyEntry->eventTime);
1995 break;
1996 }
1997
1998 case EventEntry::TYPE_MOTION: {
1999 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2000
2001 PointerCoords scaledCoords[MAX_POINTERS];
2002 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2003
2004 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002005 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2007 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002008 float scaleFactor = dispatchEntry->scaleFactor;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009 xOffset = dispatchEntry->xOffset * scaleFactor;
2010 yOffset = dispatchEntry->yOffset * scaleFactor;
2011 if (scaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002012 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 scaledCoords[i] = motionEntry->pointerCoords[i];
2014 scaledCoords[i].scale(scaleFactor);
2015 }
2016 usingCoords = scaledCoords;
2017 }
2018 } else {
2019 xOffset = 0.0f;
2020 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021
2022 // We don't want the dispatch target to know.
2023 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002024 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025 scaledCoords[i].clear();
2026 }
2027 usingCoords = scaledCoords;
2028 }
2029 }
2030
2031 // Publish the motion event.
2032 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002033 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002034 dispatchEntry->resolvedAction, motionEntry->actionButton,
2035 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2036 motionEntry->metaState, motionEntry->buttonState,
2037 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 motionEntry->downTime, motionEntry->eventTime,
2039 motionEntry->pointerCount, motionEntry->pointerProperties,
2040 usingCoords);
2041 break;
2042 }
2043
2044 default:
2045 ALOG_ASSERT(false);
2046 return;
2047 }
2048
2049 // Check the result.
2050 if (status) {
2051 if (status == WOULD_BLOCK) {
2052 if (connection->waitQueue.isEmpty()) {
2053 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2054 "This is unexpected because the wait queue is empty, so the pipe "
2055 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002056 "event to it, status=%d", connection->getInputChannelName().c_str(),
2057 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2059 } else {
2060 // Pipe is full and we are waiting for the app to finish process some events
2061 // before sending more events to it.
2062#if DEBUG_DISPATCH_CYCLE
2063 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2064 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002065 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066#endif
2067 connection->inputPublisherBlocked = true;
2068 }
2069 } else {
2070 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002071 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2073 }
2074 return;
2075 }
2076
2077 // Re-enqueue the event on the wait queue.
2078 connection->outboundQueue.dequeue(dispatchEntry);
2079 traceOutboundQueueLengthLocked(connection);
2080 connection->waitQueue.enqueueAtTail(dispatchEntry);
2081 traceWaitQueueLengthLocked(connection);
2082 }
2083}
2084
2085void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2086 const sp<Connection>& connection, uint32_t seq, bool handled) {
2087#if DEBUG_DISPATCH_CYCLE
2088 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002089 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090#endif
2091
2092 connection->inputPublisherBlocked = false;
2093
2094 if (connection->status == Connection::STATUS_BROKEN
2095 || connection->status == Connection::STATUS_ZOMBIE) {
2096 return;
2097 }
2098
2099 // Notify other system components and prepare to start the next dispatch cycle.
2100 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2101}
2102
2103void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2104 const sp<Connection>& connection, bool notify) {
2105#if DEBUG_DISPATCH_CYCLE
2106 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002107 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108#endif
2109
2110 // Clear the dispatch queues.
2111 drainDispatchQueueLocked(&connection->outboundQueue);
2112 traceOutboundQueueLengthLocked(connection);
2113 drainDispatchQueueLocked(&connection->waitQueue);
2114 traceWaitQueueLengthLocked(connection);
2115
2116 // The connection appears to be unrecoverably broken.
2117 // Ignore already broken or zombie connections.
2118 if (connection->status == Connection::STATUS_NORMAL) {
2119 connection->status = Connection::STATUS_BROKEN;
2120
2121 if (notify) {
2122 // Notify other system components.
2123 onDispatchCycleBrokenLocked(currentTime, connection);
2124 }
2125 }
2126}
2127
2128void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2129 while (!queue->isEmpty()) {
2130 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2131 releaseDispatchEntryLocked(dispatchEntry);
2132 }
2133}
2134
2135void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2136 if (dispatchEntry->hasForegroundTarget()) {
2137 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2138 }
2139 delete dispatchEntry;
2140}
2141
2142int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2143 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2144
2145 { // acquire lock
2146 AutoMutex _l(d->mLock);
2147
2148 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2149 if (connectionIndex < 0) {
2150 ALOGE("Received spurious receive callback for unknown input channel. "
2151 "fd=%d, events=0x%x", fd, events);
2152 return 0; // remove the callback
2153 }
2154
2155 bool notify;
2156 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2157 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2158 if (!(events & ALOOPER_EVENT_INPUT)) {
2159 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002160 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 return 1;
2162 }
2163
2164 nsecs_t currentTime = now();
2165 bool gotOne = false;
2166 status_t status;
2167 for (;;) {
2168 uint32_t seq;
2169 bool handled;
2170 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2171 if (status) {
2172 break;
2173 }
2174 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2175 gotOne = true;
2176 }
2177 if (gotOne) {
2178 d->runCommandsLockedInterruptible();
2179 if (status == WOULD_BLOCK) {
2180 return 1;
2181 }
2182 }
2183
2184 notify = status != DEAD_OBJECT || !connection->monitor;
2185 if (notify) {
2186 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002187 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 }
2189 } else {
2190 // Monitor channels are never explicitly unregistered.
2191 // We do it automatically when the remote endpoint is closed so don't warn
2192 // about them.
2193 notify = !connection->monitor;
2194 if (notify) {
2195 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002196 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197 }
2198 }
2199
2200 // Unregister the channel.
2201 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2202 return 0; // remove the callback
2203 } // release lock
2204}
2205
2206void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2207 const CancelationOptions& options) {
2208 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2209 synthesizeCancelationEventsForConnectionLocked(
2210 mConnectionsByFd.valueAt(i), options);
2211 }
2212}
2213
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002214void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2215 const CancelationOptions& options) {
2216 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2217 synthesizeCancelationEventsForInputChannelLocked(mMonitoringChannels[i], options);
2218 }
2219}
2220
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2222 const sp<InputChannel>& channel, const CancelationOptions& options) {
2223 ssize_t index = getConnectionIndexLocked(channel);
2224 if (index >= 0) {
2225 synthesizeCancelationEventsForConnectionLocked(
2226 mConnectionsByFd.valueAt(index), options);
2227 }
2228}
2229
2230void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2231 const sp<Connection>& connection, const CancelationOptions& options) {
2232 if (connection->status == Connection::STATUS_BROKEN) {
2233 return;
2234 }
2235
2236 nsecs_t currentTime = now();
2237
2238 Vector<EventEntry*> cancelationEvents;
2239 connection->inputState.synthesizeCancelationEvents(currentTime,
2240 cancelationEvents, options);
2241
2242 if (!cancelationEvents.isEmpty()) {
2243#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002244 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002246 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 options.reason, options.mode);
2248#endif
2249 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2250 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2251 switch (cancelationEventEntry->type) {
2252 case EventEntry::TYPE_KEY:
2253 logOutboundKeyDetailsLocked("cancel - ",
2254 static_cast<KeyEntry*>(cancelationEventEntry));
2255 break;
2256 case EventEntry::TYPE_MOTION:
2257 logOutboundMotionDetailsLocked("cancel - ",
2258 static_cast<MotionEntry*>(cancelationEventEntry));
2259 break;
2260 }
2261
2262 InputTarget target;
2263 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
2264 if (windowHandle != NULL) {
2265 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2266 target.xOffset = -windowInfo->frameLeft;
2267 target.yOffset = -windowInfo->frameTop;
2268 target.scaleFactor = windowInfo->scaleFactor;
2269 } else {
2270 target.xOffset = 0;
2271 target.yOffset = 0;
2272 target.scaleFactor = 1.0f;
2273 }
2274 target.inputChannel = connection->inputChannel;
2275 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2276
2277 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2278 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2279
2280 cancelationEventEntry->release();
2281 }
2282
2283 startDispatchCycleLocked(currentTime, connection);
2284 }
2285}
2286
2287InputDispatcher::MotionEntry*
2288InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2289 ALOG_ASSERT(pointerIds.value != 0);
2290
2291 uint32_t splitPointerIndexMap[MAX_POINTERS];
2292 PointerProperties splitPointerProperties[MAX_POINTERS];
2293 PointerCoords splitPointerCoords[MAX_POINTERS];
2294
2295 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2296 uint32_t splitPointerCount = 0;
2297
2298 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2299 originalPointerIndex++) {
2300 const PointerProperties& pointerProperties =
2301 originalMotionEntry->pointerProperties[originalPointerIndex];
2302 uint32_t pointerId = uint32_t(pointerProperties.id);
2303 if (pointerIds.hasBit(pointerId)) {
2304 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2305 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2306 splitPointerCoords[splitPointerCount].copyFrom(
2307 originalMotionEntry->pointerCoords[originalPointerIndex]);
2308 splitPointerCount += 1;
2309 }
2310 }
2311
2312 if (splitPointerCount != pointerIds.count()) {
2313 // This is bad. We are missing some of the pointers that we expected to deliver.
2314 // Most likely this indicates that we received an ACTION_MOVE events that has
2315 // different pointer ids than we expected based on the previous ACTION_DOWN
2316 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2317 // in this way.
2318 ALOGW("Dropping split motion event because the pointer count is %d but "
2319 "we expected there to be %d pointers. This probably means we received "
2320 "a broken sequence of pointer ids from the input device.",
2321 splitPointerCount, pointerIds.count());
2322 return NULL;
2323 }
2324
2325 int32_t action = originalMotionEntry->action;
2326 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2327 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2328 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2329 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2330 const PointerProperties& pointerProperties =
2331 originalMotionEntry->pointerProperties[originalPointerIndex];
2332 uint32_t pointerId = uint32_t(pointerProperties.id);
2333 if (pointerIds.hasBit(pointerId)) {
2334 if (pointerIds.count() == 1) {
2335 // The first/last pointer went down/up.
2336 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2337 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2338 } else {
2339 // A secondary pointer went down/up.
2340 uint32_t splitPointerIndex = 0;
2341 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2342 splitPointerIndex += 1;
2343 }
2344 action = maskedAction | (splitPointerIndex
2345 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2346 }
2347 } else {
2348 // An unrelated pointer changed.
2349 action = AMOTION_EVENT_ACTION_MOVE;
2350 }
2351 }
2352
2353 MotionEntry* splitMotionEntry = new MotionEntry(
2354 originalMotionEntry->eventTime,
2355 originalMotionEntry->deviceId,
2356 originalMotionEntry->source,
2357 originalMotionEntry->policyFlags,
2358 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002359 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360 originalMotionEntry->flags,
2361 originalMotionEntry->metaState,
2362 originalMotionEntry->buttonState,
2363 originalMotionEntry->edgeFlags,
2364 originalMotionEntry->xPrecision,
2365 originalMotionEntry->yPrecision,
2366 originalMotionEntry->downTime,
2367 originalMotionEntry->displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002368 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369
2370 if (originalMotionEntry->injectionState) {
2371 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2372 splitMotionEntry->injectionState->refCount += 1;
2373 }
2374
2375 return splitMotionEntry;
2376}
2377
2378void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2379#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002380 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381#endif
2382
2383 bool needWake;
2384 { // acquire lock
2385 AutoMutex _l(mLock);
2386
2387 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2388 needWake = enqueueInboundEventLocked(newEntry);
2389 } // release lock
2390
2391 if (needWake) {
2392 mLooper->wake();
2393 }
2394}
2395
2396void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2397#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002398 ALOGD("notifyKey - eventTime=%" PRId64
2399 ", deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
2400 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401 args->eventTime, args->deviceId, args->source, args->policyFlags,
2402 args->action, args->flags, args->keyCode, args->scanCode,
2403 args->metaState, args->downTime);
2404#endif
2405 if (!validateKeyEvent(args->action)) {
2406 return;
2407 }
2408
2409 uint32_t policyFlags = args->policyFlags;
2410 int32_t flags = args->flags;
2411 int32_t metaState = args->metaState;
2412 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2413 policyFlags |= POLICY_FLAG_VIRTUAL;
2414 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416 if (policyFlags & POLICY_FLAG_FUNCTION) {
2417 metaState |= AMETA_FUNCTION_ON;
2418 }
2419
2420 policyFlags |= POLICY_FLAG_TRUSTED;
2421
Michael Wright78f24442014-08-06 15:55:28 -07002422 int32_t keyCode = args->keyCode;
2423 if (metaState & AMETA_META_ON && args->action == AKEY_EVENT_ACTION_DOWN) {
2424 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2425 if (keyCode == AKEYCODE_DEL) {
2426 newKeyCode = AKEYCODE_BACK;
2427 } else if (keyCode == AKEYCODE_ENTER) {
2428 newKeyCode = AKEYCODE_HOME;
2429 }
2430 if (newKeyCode != AKEYCODE_UNKNOWN) {
2431 AutoMutex _l(mLock);
2432 struct KeyReplacement replacement = {keyCode, args->deviceId};
2433 mReplacedKeys.add(replacement, newKeyCode);
2434 keyCode = newKeyCode;
Evan Roskye71f0552017-03-21 18:12:36 -07002435 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
Michael Wright78f24442014-08-06 15:55:28 -07002436 }
2437 } else if (args->action == AKEY_EVENT_ACTION_UP) {
2438 // In order to maintain a consistent stream of up and down events, check to see if the key
2439 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2440 // even if the modifier was released between the down and the up events.
2441 AutoMutex _l(mLock);
2442 struct KeyReplacement replacement = {keyCode, args->deviceId};
2443 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2444 if (index >= 0) {
2445 keyCode = mReplacedKeys.valueAt(index);
2446 mReplacedKeys.removeItemsAt(index);
Evan Roskye71f0552017-03-21 18:12:36 -07002447 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
Michael Wright78f24442014-08-06 15:55:28 -07002448 }
2449 }
2450
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 KeyEvent event;
2452 event.initialize(args->deviceId, args->source, args->action,
Michael Wright78f24442014-08-06 15:55:28 -07002453 flags, keyCode, args->scanCode, metaState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 args->downTime, args->eventTime);
2455
Michael Wright2b3c3302018-03-02 17:19:13 +00002456 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002458 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2459 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2460 std::to_string(t.duration().count()).c_str());
2461 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 bool needWake;
2464 { // acquire lock
2465 mLock.lock();
2466
2467 if (shouldSendKeyToInputFilterLocked(args)) {
2468 mLock.unlock();
2469
2470 policyFlags |= POLICY_FLAG_FILTERED;
2471 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2472 return; // event was consumed by the filter
2473 }
2474
2475 mLock.lock();
2476 }
2477
2478 int32_t repeatCount = 0;
2479 KeyEntry* newEntry = new KeyEntry(args->eventTime,
2480 args->deviceId, args->source, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002481 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 metaState, repeatCount, args->downTime);
2483
2484 needWake = enqueueInboundEventLocked(newEntry);
2485 mLock.unlock();
2486 } // release lock
2487
2488 if (needWake) {
2489 mLooper->wake();
2490 }
2491}
2492
2493bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2494 return mInputFilterEnabled;
2495}
2496
2497void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2498#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002499 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002500 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002501 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502 args->eventTime, args->deviceId, args->source, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002503 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2505 for (uint32_t i = 0; i < args->pointerCount; i++) {
2506 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2507 "x=%f, y=%f, pressure=%f, size=%f, "
2508 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2509 "orientation=%f",
2510 i, args->pointerProperties[i].id,
2511 args->pointerProperties[i].toolType,
2512 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2513 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2514 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2515 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2516 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2517 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2518 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2519 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2520 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2521 }
2522#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002523 if (!validateMotionEvent(args->action, args->actionButton,
2524 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002525 return;
2526 }
2527
2528 uint32_t policyFlags = args->policyFlags;
2529 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002530
2531 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002533 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2534 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2535 std::to_string(t.duration().count()).c_str());
2536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537
2538 bool needWake;
2539 { // acquire lock
2540 mLock.lock();
2541
2542 if (shouldSendMotionToInputFilterLocked(args)) {
2543 mLock.unlock();
2544
2545 MotionEvent event;
Michael Wright7b159c92015-05-14 14:48:03 +01002546 event.initialize(args->deviceId, args->source, args->action, args->actionButton,
2547 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2548 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 args->downTime, args->eventTime,
2550 args->pointerCount, args->pointerProperties, args->pointerCoords);
2551
2552 policyFlags |= POLICY_FLAG_FILTERED;
2553 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2554 return; // event was consumed by the filter
2555 }
2556
2557 mLock.lock();
2558 }
2559
2560 // Just enqueue a new motion event.
2561 MotionEntry* newEntry = new MotionEntry(args->eventTime,
2562 args->deviceId, args->source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002563 args->action, args->actionButton, args->flags,
2564 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
2566 args->displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002567 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568
2569 needWake = enqueueInboundEventLocked(newEntry);
2570 mLock.unlock();
2571 } // release lock
2572
2573 if (needWake) {
2574 mLooper->wake();
2575 }
2576}
2577
2578bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2579 // TODO: support sending secondary display events to input filter
2580 return mInputFilterEnabled && isMainDisplay(args->displayId);
2581}
2582
2583void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2584#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002585 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2586 "switchMask=0x%08x",
2587 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588#endif
2589
2590 uint32_t policyFlags = args->policyFlags;
2591 policyFlags |= POLICY_FLAG_TRUSTED;
2592 mPolicy->notifySwitch(args->eventTime,
2593 args->switchValues, args->switchMask, policyFlags);
2594}
2595
2596void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2597#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002598 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 args->eventTime, args->deviceId);
2600#endif
2601
2602 bool needWake;
2603 { // acquire lock
2604 AutoMutex _l(mLock);
2605
2606 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2607 needWake = enqueueInboundEventLocked(newEntry);
2608 } // release lock
2609
2610 if (needWake) {
2611 mLooper->wake();
2612 }
2613}
2614
Jeff Brownf086ddb2014-02-11 14:28:48 -08002615int32_t InputDispatcher::injectInputEvent(const InputEvent* event, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2617 uint32_t policyFlags) {
2618#if DEBUG_INBOUND_EVENT_DETAILS
2619 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Tarandeep Singh58641502017-07-31 10:51:54 -07002620 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x, displayId=%d",
2621 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags,
2622 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623#endif
2624
2625 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2626
2627 policyFlags |= POLICY_FLAG_INJECTED;
2628 if (hasInjectionPermission(injectorPid, injectorUid)) {
2629 policyFlags |= POLICY_FLAG_TRUSTED;
2630 }
2631
2632 EventEntry* firstInjectedEntry;
2633 EventEntry* lastInjectedEntry;
2634 switch (event->getType()) {
2635 case AINPUT_EVENT_TYPE_KEY: {
2636 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
2637 int32_t action = keyEvent->getAction();
2638 if (! validateKeyEvent(action)) {
2639 return INPUT_EVENT_INJECTION_FAILED;
2640 }
2641
2642 int32_t flags = keyEvent->getFlags();
2643 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2644 policyFlags |= POLICY_FLAG_VIRTUAL;
2645 }
2646
2647 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002648 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002650 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2651 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2652 std::to_string(t.duration().count()).c_str());
2653 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654 }
2655
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 mLock.lock();
2657 firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
2658 keyEvent->getDeviceId(), keyEvent->getSource(),
2659 policyFlags, action, flags,
2660 keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
2661 keyEvent->getRepeatCount(), keyEvent->getDownTime());
2662 lastInjectedEntry = firstInjectedEntry;
2663 break;
2664 }
2665
2666 case AINPUT_EVENT_TYPE_MOTION: {
2667 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668 int32_t action = motionEvent->getAction();
2669 size_t pointerCount = motionEvent->getPointerCount();
2670 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002671 int32_t actionButton = motionEvent->getActionButton();
2672 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002673 return INPUT_EVENT_INJECTION_FAILED;
2674 }
2675
2676 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2677 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002678 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002680 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2681 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2682 std::to_string(t.duration().count()).c_str());
2683 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684 }
2685
2686 mLock.lock();
2687 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2688 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2689 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
2690 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002691 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 motionEvent->getMetaState(), motionEvent->getButtonState(),
2693 motionEvent->getEdgeFlags(),
2694 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2695 motionEvent->getDownTime(), displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002696 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2697 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 lastInjectedEntry = firstInjectedEntry;
2699 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2700 sampleEventTimes += 1;
2701 samplePointerCoords += pointerCount;
2702 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
2703 motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002704 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705 motionEvent->getMetaState(), motionEvent->getButtonState(),
2706 motionEvent->getEdgeFlags(),
2707 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
2708 motionEvent->getDownTime(), displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002709 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2710 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 lastInjectedEntry->next = nextInjectedEntry;
2712 lastInjectedEntry = nextInjectedEntry;
2713 }
2714 break;
2715 }
2716
2717 default:
2718 ALOGW("Cannot inject event of type %d", event->getType());
2719 return INPUT_EVENT_INJECTION_FAILED;
2720 }
2721
2722 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2723 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2724 injectionState->injectionIsAsync = true;
2725 }
2726
2727 injectionState->refCount += 1;
2728 lastInjectedEntry->injectionState = injectionState;
2729
2730 bool needWake = false;
2731 for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
2732 EventEntry* nextEntry = entry->next;
2733 needWake |= enqueueInboundEventLocked(entry);
2734 entry = nextEntry;
2735 }
2736
2737 mLock.unlock();
2738
2739 if (needWake) {
2740 mLooper->wake();
2741 }
2742
2743 int32_t injectionResult;
2744 { // acquire lock
2745 AutoMutex _l(mLock);
2746
2747 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2748 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2749 } else {
2750 for (;;) {
2751 injectionResult = injectionState->injectionResult;
2752 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2753 break;
2754 }
2755
2756 nsecs_t remainingTimeout = endTime - now();
2757 if (remainingTimeout <= 0) {
2758#if DEBUG_INJECTION
2759 ALOGD("injectInputEvent - Timed out waiting for injection result "
2760 "to become available.");
2761#endif
2762 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2763 break;
2764 }
2765
2766 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2767 }
2768
2769 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2770 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2771 while (injectionState->pendingForegroundDispatches != 0) {
2772#if DEBUG_INJECTION
2773 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2774 injectionState->pendingForegroundDispatches);
2775#endif
2776 nsecs_t remainingTimeout = endTime - now();
2777 if (remainingTimeout <= 0) {
2778#if DEBUG_INJECTION
2779 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2780 "dispatches to finish.");
2781#endif
2782 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2783 break;
2784 }
2785
2786 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2787 }
2788 }
2789 }
2790
2791 injectionState->release();
2792 } // release lock
2793
2794#if DEBUG_INJECTION
2795 ALOGD("injectInputEvent - Finished with result %d. "
2796 "injectorPid=%d, injectorUid=%d",
2797 injectionResult, injectorPid, injectorUid);
2798#endif
2799
2800 return injectionResult;
2801}
2802
2803bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2804 return injectorUid == 0
2805 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2806}
2807
2808void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2809 InjectionState* injectionState = entry->injectionState;
2810 if (injectionState) {
2811#if DEBUG_INJECTION
2812 ALOGD("Setting input event injection result to %d. "
2813 "injectorPid=%d, injectorUid=%d",
2814 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2815#endif
2816
2817 if (injectionState->injectionIsAsync
2818 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2819 // Log the outcome since the injector did not wait for the injection result.
2820 switch (injectionResult) {
2821 case INPUT_EVENT_INJECTION_SUCCEEDED:
2822 ALOGV("Asynchronous input event injection succeeded.");
2823 break;
2824 case INPUT_EVENT_INJECTION_FAILED:
2825 ALOGW("Asynchronous input event injection failed.");
2826 break;
2827 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2828 ALOGW("Asynchronous input event injection permission denied.");
2829 break;
2830 case INPUT_EVENT_INJECTION_TIMED_OUT:
2831 ALOGW("Asynchronous input event injection timed out.");
2832 break;
2833 }
2834 }
2835
2836 injectionState->injectionResult = injectionResult;
2837 mInjectionResultAvailableCondition.broadcast();
2838 }
2839}
2840
2841void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2842 InjectionState* injectionState = entry->injectionState;
2843 if (injectionState) {
2844 injectionState->pendingForegroundDispatches += 1;
2845 }
2846}
2847
2848void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2849 InjectionState* injectionState = entry->injectionState;
2850 if (injectionState) {
2851 injectionState->pendingForegroundDispatches -= 1;
2852
2853 if (injectionState->pendingForegroundDispatches == 0) {
2854 mInjectionSyncFinishedCondition.broadcast();
2855 }
2856 }
2857}
2858
2859sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2860 const sp<InputChannel>& inputChannel) const {
2861 size_t numWindows = mWindowHandles.size();
2862 for (size_t i = 0; i < numWindows; i++) {
2863 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2864 if (windowHandle->getInputChannel() == inputChannel) {
2865 return windowHandle;
2866 }
2867 }
2868 return NULL;
2869}
2870
2871bool InputDispatcher::hasWindowHandleLocked(
2872 const sp<InputWindowHandle>& windowHandle) const {
2873 size_t numWindows = mWindowHandles.size();
2874 for (size_t i = 0; i < numWindows; i++) {
2875 if (mWindowHandles.itemAt(i) == windowHandle) {
2876 return true;
2877 }
2878 }
2879 return false;
2880}
2881
2882void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
2883#if DEBUG_FOCUS
2884 ALOGD("setInputWindows");
2885#endif
2886 { // acquire lock
2887 AutoMutex _l(mLock);
2888
2889 Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
2890 mWindowHandles = inputWindowHandles;
2891
2892 sp<InputWindowHandle> newFocusedWindowHandle;
2893 bool foundHoveredWindow = false;
2894 for (size_t i = 0; i < mWindowHandles.size(); i++) {
2895 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
2896 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
2897 mWindowHandles.removeAt(i--);
2898 continue;
2899 }
2900 if (windowHandle->getInfo()->hasFocus) {
2901 newFocusedWindowHandle = windowHandle;
2902 }
2903 if (windowHandle == mLastHoverWindowHandle) {
2904 foundHoveredWindow = true;
2905 }
2906 }
2907
2908 if (!foundHoveredWindow) {
2909 mLastHoverWindowHandle = NULL;
2910 }
2911
2912 if (mFocusedWindowHandle != newFocusedWindowHandle) {
2913 if (mFocusedWindowHandle != NULL) {
2914#if DEBUG_FOCUS
2915 ALOGD("Focus left window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002916 mFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917#endif
2918 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
2919 if (focusedInputChannel != NULL) {
2920 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
2921 "focus left window");
2922 synthesizeCancelationEventsForInputChannelLocked(
2923 focusedInputChannel, options);
2924 }
2925 }
2926 if (newFocusedWindowHandle != NULL) {
2927#if DEBUG_FOCUS
2928 ALOGD("Focus entered window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002929 newFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930#endif
2931 }
2932 mFocusedWindowHandle = newFocusedWindowHandle;
2933 }
2934
Jeff Brownf086ddb2014-02-11 14:28:48 -08002935 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
2936 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
Ivan Lozano96f12992017-11-09 14:45:38 -08002937 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08002938 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
2939 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940#if DEBUG_FOCUS
Jeff Brownf086ddb2014-02-11 14:28:48 -08002941 ALOGD("Touched window was removed: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002942 touchedWindow.windowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08002944 sp<InputChannel> touchedInputChannel =
2945 touchedWindow.windowHandle->getInputChannel();
2946 if (touchedInputChannel != NULL) {
2947 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
2948 "touched window was removed");
2949 synthesizeCancelationEventsForInputChannelLocked(
2950 touchedInputChannel, options);
2951 }
Ivan Lozano96f12992017-11-09 14:45:38 -08002952 state.windows.removeAt(i);
2953 } else {
2954 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002955 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002956 }
2957 }
2958
2959 // Release information for windows that are no longer present.
2960 // This ensures that unused input channels are released promptly.
2961 // Otherwise, they might stick around until the window handle is destroyed
2962 // which might not happen until the next GC.
2963 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
2964 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
2965 if (!hasWindowHandleLocked(oldWindowHandle)) {
2966#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002967 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968#endif
2969 oldWindowHandle->releaseInfo();
2970 }
2971 }
2972 } // release lock
2973
2974 // Wake up poll loop since it may need to make new input dispatching choices.
2975 mLooper->wake();
2976}
2977
2978void InputDispatcher::setFocusedApplication(
2979 const sp<InputApplicationHandle>& inputApplicationHandle) {
2980#if DEBUG_FOCUS
2981 ALOGD("setFocusedApplication");
2982#endif
2983 { // acquire lock
2984 AutoMutex _l(mLock);
2985
2986 if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
2987 if (mFocusedApplicationHandle != inputApplicationHandle) {
2988 if (mFocusedApplicationHandle != NULL) {
2989 resetANRTimeoutsLocked();
2990 mFocusedApplicationHandle->releaseInfo();
2991 }
2992 mFocusedApplicationHandle = inputApplicationHandle;
2993 }
2994 } else if (mFocusedApplicationHandle != NULL) {
2995 resetANRTimeoutsLocked();
2996 mFocusedApplicationHandle->releaseInfo();
2997 mFocusedApplicationHandle.clear();
2998 }
2999
3000#if DEBUG_FOCUS
3001 //logDispatchStateLocked();
3002#endif
3003 } // release lock
3004
3005 // Wake up poll loop since it may need to make new input dispatching choices.
3006 mLooper->wake();
3007}
3008
3009void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3010#if DEBUG_FOCUS
3011 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3012#endif
3013
3014 bool changed;
3015 { // acquire lock
3016 AutoMutex _l(mLock);
3017
3018 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3019 if (mDispatchFrozen && !frozen) {
3020 resetANRTimeoutsLocked();
3021 }
3022
3023 if (mDispatchEnabled && !enabled) {
3024 resetAndDropEverythingLocked("dispatcher is being disabled");
3025 }
3026
3027 mDispatchEnabled = enabled;
3028 mDispatchFrozen = frozen;
3029 changed = true;
3030 } else {
3031 changed = false;
3032 }
3033
3034#if DEBUG_FOCUS
3035 //logDispatchStateLocked();
3036#endif
3037 } // release lock
3038
3039 if (changed) {
3040 // Wake up poll loop since it may need to make new input dispatching choices.
3041 mLooper->wake();
3042 }
3043}
3044
3045void InputDispatcher::setInputFilterEnabled(bool enabled) {
3046#if DEBUG_FOCUS
3047 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3048#endif
3049
3050 { // acquire lock
3051 AutoMutex _l(mLock);
3052
3053 if (mInputFilterEnabled == enabled) {
3054 return;
3055 }
3056
3057 mInputFilterEnabled = enabled;
3058 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3059 } // release lock
3060
3061 // Wake up poll loop since there might be work to do to drop everything.
3062 mLooper->wake();
3063}
3064
3065bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3066 const sp<InputChannel>& toChannel) {
3067#if DEBUG_FOCUS
3068 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003069 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070#endif
3071 { // acquire lock
3072 AutoMutex _l(mLock);
3073
3074 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3075 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
3076 if (fromWindowHandle == NULL || toWindowHandle == NULL) {
3077#if DEBUG_FOCUS
3078 ALOGD("Cannot transfer focus because from or to window not found.");
3079#endif
3080 return false;
3081 }
3082 if (fromWindowHandle == toWindowHandle) {
3083#if DEBUG_FOCUS
3084 ALOGD("Trivial transfer to same window.");
3085#endif
3086 return true;
3087 }
3088 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3089#if DEBUG_FOCUS
3090 ALOGD("Cannot transfer focus because windows are on different displays.");
3091#endif
3092 return false;
3093 }
3094
3095 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003096 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3097 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3098 for (size_t i = 0; i < state.windows.size(); i++) {
3099 const TouchedWindow& touchedWindow = state.windows[i];
3100 if (touchedWindow.windowHandle == fromWindowHandle) {
3101 int32_t oldTargetFlags = touchedWindow.targetFlags;
3102 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103
Jeff Brownf086ddb2014-02-11 14:28:48 -08003104 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105
Jeff Brownf086ddb2014-02-11 14:28:48 -08003106 int32_t newTargetFlags = oldTargetFlags
3107 & (InputTarget::FLAG_FOREGROUND
3108 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3109 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110
Jeff Brownf086ddb2014-02-11 14:28:48 -08003111 found = true;
3112 goto Found;
3113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114 }
3115 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003116Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117
3118 if (! found) {
3119#if DEBUG_FOCUS
3120 ALOGD("Focus transfer failed because from window did not have focus.");
3121#endif
3122 return false;
3123 }
3124
3125 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3126 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3127 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3128 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3129 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3130
3131 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3132 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3133 "transferring touch focus from this window to another window");
3134 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3135 }
3136
3137#if DEBUG_FOCUS
3138 logDispatchStateLocked();
3139#endif
3140 } // release lock
3141
3142 // Wake up poll loop since it may need to make new input dispatching choices.
3143 mLooper->wake();
3144 return true;
3145}
3146
3147void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3148#if DEBUG_FOCUS
3149 ALOGD("Resetting and dropping all events (%s).", reason);
3150#endif
3151
3152 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3153 synthesizeCancelationEventsForAllConnectionsLocked(options);
3154
3155 resetKeyRepeatLocked();
3156 releasePendingEventLocked();
3157 drainInboundQueueLocked();
3158 resetANRTimeoutsLocked();
3159
Jeff Brownf086ddb2014-02-11 14:28:48 -08003160 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003162 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163}
3164
3165void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003166 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 dumpDispatchStateLocked(dump);
3168
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003169 std::istringstream stream(dump);
3170 std::string line;
3171
3172 while (std::getline(stream, line, '\n')) {
3173 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 }
3175}
3176
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003177void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3178 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3179 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180
3181 if (mFocusedApplicationHandle != NULL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003182 dump += StringPrintf(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
3183 mFocusedApplicationHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 mFocusedApplicationHandle->getDispatchingTimeout(
3185 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3186 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003187 dump += StringPrintf(INDENT "FocusedApplication: <null>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003189 dump += StringPrintf(INDENT "FocusedWindow: name='%s'\n",
3190 mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().c_str() : "<null>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191
Jeff Brownf086ddb2014-02-11 14:28:48 -08003192 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003193 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003194 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3195 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003196 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003197 state.displayId, toString(state.down), toString(state.split),
3198 state.deviceId, state.source);
3199 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003200 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003201 for (size_t i = 0; i < state.windows.size(); i++) {
3202 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003203 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3204 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003205 touchedWindow.pointerIds.value,
3206 touchedWindow.targetFlags);
3207 }
3208 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003209 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003210 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211 }
3212 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003213 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 }
3215
3216 if (!mWindowHandles.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003217 dump += INDENT "Windows:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 for (size_t i = 0; i < mWindowHandles.size(); i++) {
3219 const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
3220 const InputWindowInfo* windowInfo = windowHandle->getInfo();
3221
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003222 dump += StringPrintf(INDENT2 "%zu: name='%s', displayId=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3224 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3225 "frame=[%d,%d][%d,%d], scale=%f, "
3226 "touchableRegion=",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003227 i, windowInfo->name.c_str(), windowInfo->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 toString(windowInfo->paused),
3229 toString(windowInfo->hasFocus),
3230 toString(windowInfo->hasWallpaper),
3231 toString(windowInfo->visible),
3232 toString(windowInfo->canReceiveKeys),
3233 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3234 windowInfo->layer,
3235 windowInfo->frameLeft, windowInfo->frameTop,
3236 windowInfo->frameRight, windowInfo->frameBottom,
3237 windowInfo->scaleFactor);
3238 dumpRegion(dump, windowInfo->touchableRegion);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003239 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3240 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 windowInfo->ownerPid, windowInfo->ownerUid,
3242 windowInfo->dispatchingTimeout / 1000000.0);
3243 }
3244 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003245 dump += INDENT "Windows: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 }
3247
3248 if (!mMonitoringChannels.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003249 dump += INDENT "MonitoringChannels:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3251 const sp<InputChannel>& channel = mMonitoringChannels[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003252 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 }
3254 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003255 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 }
3257
3258 nsecs_t currentTime = now();
3259
3260 // Dump recently dispatched or dropped events from oldest to newest.
3261 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003262 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003264 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003266 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267 (currentTime - entry->eventTime) * 0.000001f);
3268 }
3269 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003270 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003271 }
3272
3273 // Dump event currently being dispatched.
3274 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003275 dump += INDENT "PendingEvent:\n";
3276 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003278 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3280 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003281 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282 }
3283
3284 // Dump inbound events from oldest to newest.
3285 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003286 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003288 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003290 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 (currentTime - entry->eventTime) * 0.000001f);
3292 }
3293 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003294 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295 }
3296
Michael Wright78f24442014-08-06 15:55:28 -07003297 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003298 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003299 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3300 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3301 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003302 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003303 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3304 }
3305 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003306 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003307 }
3308
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003310 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3312 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003313 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003315 i, connection->getInputChannelName().c_str(),
3316 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003317 connection->getStatusLabel(), toString(connection->monitor),
3318 toString(connection->inputPublisherBlocked));
3319
3320 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003321 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322 connection->outboundQueue.count());
3323 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3324 entry = entry->next) {
3325 dump.append(INDENT4);
3326 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003327 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328 entry->targetFlags, entry->resolvedAction,
3329 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3330 }
3331 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003332 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333 }
3334
3335 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003336 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 connection->waitQueue.count());
3338 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3339 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003340 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003342 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343 "age=%0.1fms, wait=%0.1fms\n",
3344 entry->targetFlags, entry->resolvedAction,
3345 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3346 (currentTime - entry->deliveryTime) * 0.000001f);
3347 }
3348 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003349 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 }
3351 }
3352 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003353 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354 }
3355
3356 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003357 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358 (mAppSwitchDueTime - now()) / 1000000.0);
3359 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003360 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361 }
3362
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003363 dump += INDENT "Configuration:\n";
3364 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003366 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 mConfig.keyRepeatTimeout * 0.000001f);
3368}
3369
3370status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3371 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
3372#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003373 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 toString(monitor));
3375#endif
3376
3377 { // acquire lock
3378 AutoMutex _l(mLock);
3379
3380 if (getConnectionIndexLocked(inputChannel) >= 0) {
3381 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003382 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 return BAD_VALUE;
3384 }
3385
3386 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3387
3388 int fd = inputChannel->getFd();
3389 mConnectionsByFd.add(fd, connection);
3390
3391 if (monitor) {
3392 mMonitoringChannels.push(inputChannel);
3393 }
3394
3395 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3396 } // release lock
3397
3398 // Wake the looper because some connections have changed.
3399 mLooper->wake();
3400 return OK;
3401}
3402
3403status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3404#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003405 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406#endif
3407
3408 { // acquire lock
3409 AutoMutex _l(mLock);
3410
3411 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3412 if (status) {
3413 return status;
3414 }
3415 } // release lock
3416
3417 // Wake the poll loop because removing the connection may have changed the current
3418 // synchronization state.
3419 mLooper->wake();
3420 return OK;
3421}
3422
3423status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3424 bool notify) {
3425 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3426 if (connectionIndex < 0) {
3427 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003428 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 return BAD_VALUE;
3430 }
3431
3432 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3433 mConnectionsByFd.removeItemsAt(connectionIndex);
3434
3435 if (connection->monitor) {
3436 removeMonitorChannelLocked(inputChannel);
3437 }
3438
3439 mLooper->removeFd(inputChannel->getFd());
3440
3441 nsecs_t currentTime = now();
3442 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3443
3444 connection->status = Connection::STATUS_ZOMBIE;
3445 return OK;
3446}
3447
3448void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3449 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3450 if (mMonitoringChannels[i] == inputChannel) {
3451 mMonitoringChannels.removeAt(i);
3452 break;
3453 }
3454 }
3455}
3456
3457ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
3458 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3459 if (connectionIndex >= 0) {
3460 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3461 if (connection->inputChannel.get() == inputChannel.get()) {
3462 return connectionIndex;
3463 }
3464 }
3465
3466 return -1;
3467}
3468
3469void InputDispatcher::onDispatchCycleFinishedLocked(
3470 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3471 CommandEntry* commandEntry = postCommandLocked(
3472 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3473 commandEntry->connection = connection;
3474 commandEntry->eventTime = currentTime;
3475 commandEntry->seq = seq;
3476 commandEntry->handled = handled;
3477}
3478
3479void InputDispatcher::onDispatchCycleBrokenLocked(
3480 nsecs_t currentTime, const sp<Connection>& connection) {
3481 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003482 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483
3484 CommandEntry* commandEntry = postCommandLocked(
3485 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3486 commandEntry->connection = connection;
3487}
3488
3489void InputDispatcher::onANRLocked(
3490 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3491 const sp<InputWindowHandle>& windowHandle,
3492 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3493 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3494 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3495 ALOGI("Application is not responding: %s. "
3496 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003497 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498 dispatchLatency, waitDuration, reason);
3499
3500 // Capture a record of the InputDispatcher state at the time of the ANR.
3501 time_t t = time(NULL);
3502 struct tm tm;
3503 localtime_r(&t, &tm);
3504 char timestr[64];
3505 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3506 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003507 mLastANRState += INDENT "ANR:\n";
3508 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3509 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3510 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3511 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3512 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3513 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514 dumpDispatchStateLocked(mLastANRState);
3515
3516 CommandEntry* commandEntry = postCommandLocked(
3517 & InputDispatcher::doNotifyANRLockedInterruptible);
3518 commandEntry->inputApplicationHandle = applicationHandle;
3519 commandEntry->inputWindowHandle = windowHandle;
3520 commandEntry->reason = reason;
3521}
3522
3523void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3524 CommandEntry* commandEntry) {
3525 mLock.unlock();
3526
3527 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3528
3529 mLock.lock();
3530}
3531
3532void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3533 CommandEntry* commandEntry) {
3534 sp<Connection> connection = commandEntry->connection;
3535
3536 if (connection->status != Connection::STATUS_ZOMBIE) {
3537 mLock.unlock();
3538
3539 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3540
3541 mLock.lock();
3542 }
3543}
3544
3545void InputDispatcher::doNotifyANRLockedInterruptible(
3546 CommandEntry* commandEntry) {
3547 mLock.unlock();
3548
3549 nsecs_t newTimeout = mPolicy->notifyANR(
3550 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3551 commandEntry->reason);
3552
3553 mLock.lock();
3554
3555 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
3556 commandEntry->inputWindowHandle != NULL
3557 ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
3558}
3559
3560void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3561 CommandEntry* commandEntry) {
3562 KeyEntry* entry = commandEntry->keyEntry;
3563
3564 KeyEvent event;
3565 initializeKeyEvent(&event, entry);
3566
3567 mLock.unlock();
3568
Michael Wright2b3c3302018-03-02 17:19:13 +00003569 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3571 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003572 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3573 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3574 std::to_string(t.duration().count()).c_str());
3575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576
3577 mLock.lock();
3578
3579 if (delay < 0) {
3580 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3581 } else if (!delay) {
3582 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3583 } else {
3584 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3585 entry->interceptKeyWakeupTime = now() + delay;
3586 }
3587 entry->release();
3588}
3589
3590void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3591 CommandEntry* commandEntry) {
3592 sp<Connection> connection = commandEntry->connection;
3593 nsecs_t finishTime = commandEntry->eventTime;
3594 uint32_t seq = commandEntry->seq;
3595 bool handled = commandEntry->handled;
3596
3597 // Handle post-event policy actions.
3598 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3599 if (dispatchEntry) {
3600 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3601 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003602 std::string msg =
3603 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003604 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003606 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 }
3608
3609 bool restartEvent;
3610 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3611 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3612 restartEvent = afterKeyEventLockedInterruptible(connection,
3613 dispatchEntry, keyEntry, handled);
3614 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3615 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3616 restartEvent = afterMotionEventLockedInterruptible(connection,
3617 dispatchEntry, motionEntry, handled);
3618 } else {
3619 restartEvent = false;
3620 }
3621
3622 // Dequeue the event and start the next cycle.
3623 // Note that because the lock might have been released, it is possible that the
3624 // contents of the wait queue to have been drained, so we need to double-check
3625 // a few things.
3626 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3627 connection->waitQueue.dequeue(dispatchEntry);
3628 traceWaitQueueLengthLocked(connection);
3629 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3630 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3631 traceOutboundQueueLengthLocked(connection);
3632 } else {
3633 releaseDispatchEntryLocked(dispatchEntry);
3634 }
3635 }
3636
3637 // Start the next dispatch cycle for this connection.
3638 startDispatchCycleLocked(now(), connection);
3639 }
3640}
3641
3642bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3643 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3644 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3645 // Get the fallback key state.
3646 // Clear it out after dispatching the UP.
3647 int32_t originalKeyCode = keyEntry->keyCode;
3648 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3649 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3650 connection->inputState.removeFallbackKey(originalKeyCode);
3651 }
3652
3653 if (handled || !dispatchEntry->hasForegroundTarget()) {
3654 // If the application handles the original key for which we previously
3655 // generated a fallback or if the window is not a foreground window,
3656 // then cancel the associated fallback key, if any.
3657 if (fallbackKeyCode != -1) {
3658 // Dispatch the unhandled key to the policy with the cancel flag.
3659#if DEBUG_OUTBOUND_EVENT_DETAILS
3660 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3661 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3662 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3663 keyEntry->policyFlags);
3664#endif
3665 KeyEvent event;
3666 initializeKeyEvent(&event, keyEntry);
3667 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3668
3669 mLock.unlock();
3670
3671 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3672 &event, keyEntry->policyFlags, &event);
3673
3674 mLock.lock();
3675
3676 // Cancel the fallback key.
3677 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3678 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3679 "application handled the original non-fallback key "
3680 "or is no longer a foreground target, "
3681 "canceling previously dispatched fallback key");
3682 options.keyCode = fallbackKeyCode;
3683 synthesizeCancelationEventsForConnectionLocked(connection, options);
3684 }
3685 connection->inputState.removeFallbackKey(originalKeyCode);
3686 }
3687 } else {
3688 // If the application did not handle a non-fallback key, first check
3689 // that we are in a good state to perform unhandled key event processing
3690 // Then ask the policy what to do with it.
3691 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3692 && keyEntry->repeatCount == 0;
3693 if (fallbackKeyCode == -1 && !initialDown) {
3694#if DEBUG_OUTBOUND_EVENT_DETAILS
3695 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3696 "since this is not an initial down. "
3697 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3698 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3699 keyEntry->policyFlags);
3700#endif
3701 return false;
3702 }
3703
3704 // Dispatch the unhandled key to the policy.
3705#if DEBUG_OUTBOUND_EVENT_DETAILS
3706 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
3707 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3708 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3709 keyEntry->policyFlags);
3710#endif
3711 KeyEvent event;
3712 initializeKeyEvent(&event, keyEntry);
3713
3714 mLock.unlock();
3715
3716 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3717 &event, keyEntry->policyFlags, &event);
3718
3719 mLock.lock();
3720
3721 if (connection->status != Connection::STATUS_NORMAL) {
3722 connection->inputState.removeFallbackKey(originalKeyCode);
3723 return false;
3724 }
3725
3726 // Latch the fallback keycode for this key on an initial down.
3727 // The fallback keycode cannot change at any other point in the lifecycle.
3728 if (initialDown) {
3729 if (fallback) {
3730 fallbackKeyCode = event.getKeyCode();
3731 } else {
3732 fallbackKeyCode = AKEYCODE_UNKNOWN;
3733 }
3734 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3735 }
3736
3737 ALOG_ASSERT(fallbackKeyCode != -1);
3738
3739 // Cancel the fallback key if the policy decides not to send it anymore.
3740 // We will continue to dispatch the key to the policy but we will no
3741 // longer dispatch a fallback key to the application.
3742 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3743 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3744#if DEBUG_OUTBOUND_EVENT_DETAILS
3745 if (fallback) {
3746 ALOGD("Unhandled key event: Policy requested to send key %d"
3747 "as a fallback for %d, but on the DOWN it had requested "
3748 "to send %d instead. Fallback canceled.",
3749 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3750 } else {
3751 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
3752 "but on the DOWN it had requested to send %d. "
3753 "Fallback canceled.",
3754 originalKeyCode, fallbackKeyCode);
3755 }
3756#endif
3757
3758 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3759 "canceling fallback, policy no longer desires it");
3760 options.keyCode = fallbackKeyCode;
3761 synthesizeCancelationEventsForConnectionLocked(connection, options);
3762
3763 fallback = false;
3764 fallbackKeyCode = AKEYCODE_UNKNOWN;
3765 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3766 connection->inputState.setFallbackKey(originalKeyCode,
3767 fallbackKeyCode);
3768 }
3769 }
3770
3771#if DEBUG_OUTBOUND_EVENT_DETAILS
3772 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003773 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3775 connection->inputState.getFallbackKeys();
3776 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003777 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 fallbackKeys.valueAt(i));
3779 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003780 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003781 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782 }
3783#endif
3784
3785 if (fallback) {
3786 // Restart the dispatch cycle using the fallback key.
3787 keyEntry->eventTime = event.getEventTime();
3788 keyEntry->deviceId = event.getDeviceId();
3789 keyEntry->source = event.getSource();
3790 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3791 keyEntry->keyCode = fallbackKeyCode;
3792 keyEntry->scanCode = event.getScanCode();
3793 keyEntry->metaState = event.getMetaState();
3794 keyEntry->repeatCount = event.getRepeatCount();
3795 keyEntry->downTime = event.getDownTime();
3796 keyEntry->syntheticRepeat = false;
3797
3798#if DEBUG_OUTBOUND_EVENT_DETAILS
3799 ALOGD("Unhandled key event: Dispatching fallback key. "
3800 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3801 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3802#endif
3803 return true; // restart the event
3804 } else {
3805#if DEBUG_OUTBOUND_EVENT_DETAILS
3806 ALOGD("Unhandled key event: No fallback key.");
3807#endif
3808 }
3809 }
3810 }
3811 return false;
3812}
3813
3814bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3815 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3816 return false;
3817}
3818
3819void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3820 mLock.unlock();
3821
3822 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
3823
3824 mLock.lock();
3825}
3826
3827void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
3828 event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
3829 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3830 entry->downTime, entry->eventTime);
3831}
3832
3833void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3834 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3835 // TODO Write some statistics about how long we spend waiting.
3836}
3837
3838void InputDispatcher::traceInboundQueueLengthLocked() {
3839 if (ATRACE_ENABLED()) {
3840 ATRACE_INT("iq", mInboundQueue.count());
3841 }
3842}
3843
3844void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3845 if (ATRACE_ENABLED()) {
3846 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003847 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 ATRACE_INT(counterName, connection->outboundQueue.count());
3849 }
3850}
3851
3852void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3853 if (ATRACE_ENABLED()) {
3854 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003855 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 ATRACE_INT(counterName, connection->waitQueue.count());
3857 }
3858}
3859
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003860void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861 AutoMutex _l(mLock);
3862
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003863 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864 dumpDispatchStateLocked(dump);
3865
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003866 if (!mLastANRState.empty()) {
3867 dump += "\nInput Dispatcher State at time of last ANR:\n";
3868 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869 }
3870}
3871
3872void InputDispatcher::monitor() {
3873 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3874 mLock.lock();
3875 mLooper->wake();
3876 mDispatcherIsAliveCondition.wait(mLock);
3877 mLock.unlock();
3878}
3879
3880
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881// --- InputDispatcher::InjectionState ---
3882
3883InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3884 refCount(1),
3885 injectorPid(injectorPid), injectorUid(injectorUid),
3886 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3887 pendingForegroundDispatches(0) {
3888}
3889
3890InputDispatcher::InjectionState::~InjectionState() {
3891}
3892
3893void InputDispatcher::InjectionState::release() {
3894 refCount -= 1;
3895 if (refCount == 0) {
3896 delete this;
3897 } else {
3898 ALOG_ASSERT(refCount > 0);
3899 }
3900}
3901
3902
3903// --- InputDispatcher::EventEntry ---
3904
3905InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
3906 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
3907 injectionState(NULL), dispatchInProgress(false) {
3908}
3909
3910InputDispatcher::EventEntry::~EventEntry() {
3911 releaseInjectionState();
3912}
3913
3914void InputDispatcher::EventEntry::release() {
3915 refCount -= 1;
3916 if (refCount == 0) {
3917 delete this;
3918 } else {
3919 ALOG_ASSERT(refCount > 0);
3920 }
3921}
3922
3923void InputDispatcher::EventEntry::releaseInjectionState() {
3924 if (injectionState) {
3925 injectionState->release();
3926 injectionState = NULL;
3927 }
3928}
3929
3930
3931// --- InputDispatcher::ConfigurationChangedEntry ---
3932
3933InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
3934 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
3935}
3936
3937InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
3938}
3939
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003940void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
3941 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942}
3943
3944
3945// --- InputDispatcher::DeviceResetEntry ---
3946
3947InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
3948 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
3949 deviceId(deviceId) {
3950}
3951
3952InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
3953}
3954
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003955void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
3956 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 deviceId, policyFlags);
3958}
3959
3960
3961// --- InputDispatcher::KeyEntry ---
3962
3963InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
3964 int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
3965 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
3966 int32_t repeatCount, nsecs_t downTime) :
3967 EventEntry(TYPE_KEY, eventTime, policyFlags),
3968 deviceId(deviceId), source(source), action(action), flags(flags),
3969 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
3970 repeatCount(repeatCount), downTime(downTime),
3971 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
3972 interceptKeyWakeupTime(0) {
3973}
3974
3975InputDispatcher::KeyEntry::~KeyEntry() {
3976}
3977
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003978void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
3979 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, action=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
3981 "repeatCount=%d), policyFlags=0x%08x",
3982 deviceId, source, action, flags, keyCode, scanCode, metaState,
3983 repeatCount, policyFlags);
3984}
3985
3986void InputDispatcher::KeyEntry::recycle() {
3987 releaseInjectionState();
3988
3989 dispatchInProgress = false;
3990 syntheticRepeat = false;
3991 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
3992 interceptKeyWakeupTime = 0;
3993}
3994
3995
3996// --- InputDispatcher::MotionEntry ---
3997
Michael Wright7b159c92015-05-14 14:48:03 +01003998InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
3999 uint32_t source, uint32_t policyFlags, int32_t action, int32_t actionButton,
4000 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4001 float xPrecision, float yPrecision, nsecs_t downTime,
4002 int32_t displayId, uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004003 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4004 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004005 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4006 eventTime(eventTime),
Michael Wright7b159c92015-05-14 14:48:03 +01004007 deviceId(deviceId), source(source), action(action), actionButton(actionButton),
4008 flags(flags), metaState(metaState), buttonState(buttonState),
4009 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
4011 for (uint32_t i = 0; i < pointerCount; i++) {
4012 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4013 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004014 if (xOffset || yOffset) {
4015 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4016 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 }
4018}
4019
4020InputDispatcher::MotionEntry::~MotionEntry() {
4021}
4022
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004023void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
4024 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, action=%d, actionButton=0x%08x, "
Michael Wright7b159c92015-05-14 14:48:03 +01004025 "flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
4026 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, displayId=%d, pointers=[",
4027 deviceId, source, action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028 xPrecision, yPrecision, displayId);
4029 for (uint32_t i = 0; i < pointerCount; i++) {
4030 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004031 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004033 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034 pointerCoords[i].getX(), pointerCoords[i].getY());
4035 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004036 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037}
4038
4039
4040// --- InputDispatcher::DispatchEntry ---
4041
4042volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4043
4044InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4045 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4046 seq(nextSeq()),
4047 eventEntry(eventEntry), targetFlags(targetFlags),
4048 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4049 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4050 eventEntry->refCount += 1;
4051}
4052
4053InputDispatcher::DispatchEntry::~DispatchEntry() {
4054 eventEntry->release();
4055}
4056
4057uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4058 // Sequence number 0 is reserved and will never be returned.
4059 uint32_t seq;
4060 do {
4061 seq = android_atomic_inc(&sNextSeqAtomic);
4062 } while (!seq);
4063 return seq;
4064}
4065
4066
4067// --- InputDispatcher::InputState ---
4068
4069InputDispatcher::InputState::InputState() {
4070}
4071
4072InputDispatcher::InputState::~InputState() {
4073}
4074
4075bool InputDispatcher::InputState::isNeutral() const {
4076 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4077}
4078
4079bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4080 int32_t displayId) const {
4081 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4082 const MotionMemento& memento = mMotionMementos.itemAt(i);
4083 if (memento.deviceId == deviceId
4084 && memento.source == source
4085 && memento.displayId == displayId
4086 && memento.hovering) {
4087 return true;
4088 }
4089 }
4090 return false;
4091}
4092
4093bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4094 int32_t action, int32_t flags) {
4095 switch (action) {
4096 case AKEY_EVENT_ACTION_UP: {
4097 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4098 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4099 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4100 mFallbackKeys.removeItemsAt(i);
4101 } else {
4102 i += 1;
4103 }
4104 }
4105 }
4106 ssize_t index = findKeyMemento(entry);
4107 if (index >= 0) {
4108 mKeyMementos.removeAt(index);
4109 return true;
4110 }
4111 /* FIXME: We can't just drop the key up event because that prevents creating
4112 * popup windows that are automatically shown when a key is held and then
4113 * dismissed when the key is released. The problem is that the popup will
4114 * not have received the original key down, so the key up will be considered
4115 * to be inconsistent with its observed state. We could perhaps handle this
4116 * by synthesizing a key down but that will cause other problems.
4117 *
4118 * So for now, allow inconsistent key up events to be dispatched.
4119 *
4120#if DEBUG_OUTBOUND_EVENT_DETAILS
4121 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4122 "keyCode=%d, scanCode=%d",
4123 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4124#endif
4125 return false;
4126 */
4127 return true;
4128 }
4129
4130 case AKEY_EVENT_ACTION_DOWN: {
4131 ssize_t index = findKeyMemento(entry);
4132 if (index >= 0) {
4133 mKeyMementos.removeAt(index);
4134 }
4135 addKeyMemento(entry, flags);
4136 return true;
4137 }
4138
4139 default:
4140 return true;
4141 }
4142}
4143
4144bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4145 int32_t action, int32_t flags) {
4146 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4147 switch (actionMasked) {
4148 case AMOTION_EVENT_ACTION_UP:
4149 case AMOTION_EVENT_ACTION_CANCEL: {
4150 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4151 if (index >= 0) {
4152 mMotionMementos.removeAt(index);
4153 return true;
4154 }
4155#if DEBUG_OUTBOUND_EVENT_DETAILS
4156 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
4157 "actionMasked=%d",
4158 entry->deviceId, entry->source, actionMasked);
4159#endif
4160 return false;
4161 }
4162
4163 case AMOTION_EVENT_ACTION_DOWN: {
4164 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4165 if (index >= 0) {
4166 mMotionMementos.removeAt(index);
4167 }
4168 addMotionMemento(entry, flags, false /*hovering*/);
4169 return true;
4170 }
4171
4172 case AMOTION_EVENT_ACTION_POINTER_UP:
4173 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4174 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004175 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4176 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4177 // generate cancellation events for these since they're based in relative rather than
4178 // absolute units.
4179 return true;
4180 }
4181
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004183
4184 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4185 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4186 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4187 // other value and we need to track the motion so we can send cancellation events for
4188 // anything generating fallback events (e.g. DPad keys for joystick movements).
4189 if (index >= 0) {
4190 if (entry->pointerCoords[0].isEmpty()) {
4191 mMotionMementos.removeAt(index);
4192 } else {
4193 MotionMemento& memento = mMotionMementos.editItemAt(index);
4194 memento.setPointers(entry);
4195 }
4196 } else if (!entry->pointerCoords[0].isEmpty()) {
4197 addMotionMemento(entry, flags, false /*hovering*/);
4198 }
4199
4200 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4201 return true;
4202 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 if (index >= 0) {
4204 MotionMemento& memento = mMotionMementos.editItemAt(index);
4205 memento.setPointers(entry);
4206 return true;
4207 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208#if DEBUG_OUTBOUND_EVENT_DETAILS
4209 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
4210 "deviceId=%d, source=%08x, actionMasked=%d",
4211 entry->deviceId, entry->source, actionMasked);
4212#endif
4213 return false;
4214 }
4215
4216 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4217 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4218 if (index >= 0) {
4219 mMotionMementos.removeAt(index);
4220 return true;
4221 }
4222#if DEBUG_OUTBOUND_EVENT_DETAILS
4223 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
4224 entry->deviceId, entry->source);
4225#endif
4226 return false;
4227 }
4228
4229 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4230 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4231 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4232 if (index >= 0) {
4233 mMotionMementos.removeAt(index);
4234 }
4235 addMotionMemento(entry, flags, true /*hovering*/);
4236 return true;
4237 }
4238
4239 default:
4240 return true;
4241 }
4242}
4243
4244ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4245 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4246 const KeyMemento& memento = mKeyMementos.itemAt(i);
4247 if (memento.deviceId == entry->deviceId
4248 && memento.source == entry->source
4249 && memento.keyCode == entry->keyCode
4250 && memento.scanCode == entry->scanCode) {
4251 return i;
4252 }
4253 }
4254 return -1;
4255}
4256
4257ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4258 bool hovering) const {
4259 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4260 const MotionMemento& memento = mMotionMementos.itemAt(i);
4261 if (memento.deviceId == entry->deviceId
4262 && memento.source == entry->source
4263 && memento.displayId == entry->displayId
4264 && memento.hovering == hovering) {
4265 return i;
4266 }
4267 }
4268 return -1;
4269}
4270
4271void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4272 mKeyMementos.push();
4273 KeyMemento& memento = mKeyMementos.editTop();
4274 memento.deviceId = entry->deviceId;
4275 memento.source = entry->source;
4276 memento.keyCode = entry->keyCode;
4277 memento.scanCode = entry->scanCode;
4278 memento.metaState = entry->metaState;
4279 memento.flags = flags;
4280 memento.downTime = entry->downTime;
4281 memento.policyFlags = entry->policyFlags;
4282}
4283
4284void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4285 int32_t flags, bool hovering) {
4286 mMotionMementos.push();
4287 MotionMemento& memento = mMotionMementos.editTop();
4288 memento.deviceId = entry->deviceId;
4289 memento.source = entry->source;
4290 memento.flags = flags;
4291 memento.xPrecision = entry->xPrecision;
4292 memento.yPrecision = entry->yPrecision;
4293 memento.downTime = entry->downTime;
4294 memento.displayId = entry->displayId;
4295 memento.setPointers(entry);
4296 memento.hovering = hovering;
4297 memento.policyFlags = entry->policyFlags;
4298}
4299
4300void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4301 pointerCount = entry->pointerCount;
4302 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4303 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4304 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4305 }
4306}
4307
4308void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4309 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4310 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4311 const KeyMemento& memento = mKeyMementos.itemAt(i);
4312 if (shouldCancelKey(memento, options)) {
4313 outEvents.push(new KeyEntry(currentTime,
4314 memento.deviceId, memento.source, memento.policyFlags,
4315 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4316 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4317 }
4318 }
4319
4320 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4321 const MotionMemento& memento = mMotionMementos.itemAt(i);
4322 if (shouldCancelMotion(memento, options)) {
4323 outEvents.push(new MotionEntry(currentTime,
4324 memento.deviceId, memento.source, memento.policyFlags,
4325 memento.hovering
4326 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4327 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004328 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 memento.xPrecision, memento.yPrecision, memento.downTime,
4330 memento.displayId,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004331 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4332 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 }
4334 }
4335}
4336
4337void InputDispatcher::InputState::clear() {
4338 mKeyMementos.clear();
4339 mMotionMementos.clear();
4340 mFallbackKeys.clear();
4341}
4342
4343void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4344 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4345 const MotionMemento& memento = mMotionMementos.itemAt(i);
4346 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4347 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4348 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4349 if (memento.deviceId == otherMemento.deviceId
4350 && memento.source == otherMemento.source
4351 && memento.displayId == otherMemento.displayId) {
4352 other.mMotionMementos.removeAt(j);
4353 } else {
4354 j += 1;
4355 }
4356 }
4357 other.mMotionMementos.push(memento);
4358 }
4359 }
4360}
4361
4362int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4363 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4364 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4365}
4366
4367void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4368 int32_t fallbackKeyCode) {
4369 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4370 if (index >= 0) {
4371 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4372 } else {
4373 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4374 }
4375}
4376
4377void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4378 mFallbackKeys.removeItem(originalKeyCode);
4379}
4380
4381bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4382 const CancelationOptions& options) {
4383 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4384 return false;
4385 }
4386
4387 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4388 return false;
4389 }
4390
4391 switch (options.mode) {
4392 case CancelationOptions::CANCEL_ALL_EVENTS:
4393 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4394 return true;
4395 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4396 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4397 default:
4398 return false;
4399 }
4400}
4401
4402bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4403 const CancelationOptions& options) {
4404 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4405 return false;
4406 }
4407
4408 switch (options.mode) {
4409 case CancelationOptions::CANCEL_ALL_EVENTS:
4410 return true;
4411 case CancelationOptions::CANCEL_POINTER_EVENTS:
4412 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4413 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4414 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4415 default:
4416 return false;
4417 }
4418}
4419
4420
4421// --- InputDispatcher::Connection ---
4422
4423InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4424 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4425 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4426 monitor(monitor),
4427 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4428}
4429
4430InputDispatcher::Connection::~Connection() {
4431}
4432
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004433const std::string InputDispatcher::Connection::getWindowName() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434 if (inputWindowHandle != NULL) {
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004435 return inputWindowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004436 }
4437 if (monitor) {
4438 return "monitor";
4439 }
4440 return "?";
4441}
4442
4443const char* InputDispatcher::Connection::getStatusLabel() const {
4444 switch (status) {
4445 case STATUS_NORMAL:
4446 return "NORMAL";
4447
4448 case STATUS_BROKEN:
4449 return "BROKEN";
4450
4451 case STATUS_ZOMBIE:
4452 return "ZOMBIE";
4453
4454 default:
4455 return "UNKNOWN";
4456 }
4457}
4458
4459InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
4460 for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
4461 if (entry->seq == seq) {
4462 return entry;
4463 }
4464 }
4465 return NULL;
4466}
4467
4468
4469// --- InputDispatcher::CommandEntry ---
4470
4471InputDispatcher::CommandEntry::CommandEntry(Command command) :
4472 command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
4473 seq(0), handled(false) {
4474}
4475
4476InputDispatcher::CommandEntry::~CommandEntry() {
4477}
4478
4479
4480// --- InputDispatcher::TouchState ---
4481
4482InputDispatcher::TouchState::TouchState() :
4483 down(false), split(false), deviceId(-1), source(0), displayId(-1) {
4484}
4485
4486InputDispatcher::TouchState::~TouchState() {
4487}
4488
4489void InputDispatcher::TouchState::reset() {
4490 down = false;
4491 split = false;
4492 deviceId = -1;
4493 source = 0;
4494 displayId = -1;
4495 windows.clear();
4496}
4497
4498void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4499 down = other.down;
4500 split = other.split;
4501 deviceId = other.deviceId;
4502 source = other.source;
4503 displayId = other.displayId;
4504 windows = other.windows;
4505}
4506
4507void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4508 int32_t targetFlags, BitSet32 pointerIds) {
4509 if (targetFlags & InputTarget::FLAG_SPLIT) {
4510 split = true;
4511 }
4512
4513 for (size_t i = 0; i < windows.size(); i++) {
4514 TouchedWindow& touchedWindow = windows.editItemAt(i);
4515 if (touchedWindow.windowHandle == windowHandle) {
4516 touchedWindow.targetFlags |= targetFlags;
4517 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4518 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4519 }
4520 touchedWindow.pointerIds.value |= pointerIds.value;
4521 return;
4522 }
4523 }
4524
4525 windows.push();
4526
4527 TouchedWindow& touchedWindow = windows.editTop();
4528 touchedWindow.windowHandle = windowHandle;
4529 touchedWindow.targetFlags = targetFlags;
4530 touchedWindow.pointerIds = pointerIds;
4531}
4532
4533void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4534 for (size_t i = 0; i < windows.size(); i++) {
4535 if (windows.itemAt(i).windowHandle == windowHandle) {
4536 windows.removeAt(i);
4537 return;
4538 }
4539 }
4540}
4541
4542void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4543 for (size_t i = 0 ; i < windows.size(); ) {
4544 TouchedWindow& window = windows.editItemAt(i);
4545 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4546 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4547 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4548 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4549 i += 1;
4550 } else {
4551 windows.removeAt(i);
4552 }
4553 }
4554}
4555
4556sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4557 for (size_t i = 0; i < windows.size(); i++) {
4558 const TouchedWindow& window = windows.itemAt(i);
4559 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4560 return window.windowHandle;
4561 }
4562 }
4563 return NULL;
4564}
4565
4566bool InputDispatcher::TouchState::isSlippery() const {
4567 // Must have exactly one foreground window.
4568 bool haveSlipperyForegroundWindow = false;
4569 for (size_t i = 0; i < windows.size(); i++) {
4570 const TouchedWindow& window = windows.itemAt(i);
4571 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4572 if (haveSlipperyForegroundWindow
4573 || !(window.windowHandle->getInfo()->layoutParamsFlags
4574 & InputWindowInfo::FLAG_SLIPPERY)) {
4575 return false;
4576 }
4577 haveSlipperyForegroundWindow = true;
4578 }
4579 }
4580 return haveSlipperyForegroundWindow;
4581}
4582
4583
4584// --- InputDispatcherThread ---
4585
4586InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4587 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4588}
4589
4590InputDispatcherThread::~InputDispatcherThread() {
4591}
4592
4593bool InputDispatcherThread::threadLoop() {
4594 mDispatcher->dispatchOnce();
4595 return true;
4596}
4597
4598} // namespace android