blob: d60957370d16665edc9db1666ab13e0215c83fba [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
20//#define LOG_NDEBUG 0
21
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
38#define DEBUG_FOCUS 0
39
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wrightd02c5b62014-02-10 15:10:22 -080048#include <errno.h>
49#include <limits.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080050#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070051#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070053#include <unistd.h>
54
Michael Wright2b3c3302018-03-02 17:19:13 +000055#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080056#include <android-base/stringprintf.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070057#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <utils/Trace.h>
59#include <powermanager/PowerManager.h>
60#include <ui/Region.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080061
62#define INDENT " "
63#define INDENT2 " "
64#define INDENT3 " "
65#define INDENT4 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
71// Default input dispatching timeout if there is no focused application or paused window
72// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000073constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080074
75// Amount of time to allow for all pending events to be processed when an app switch
76// key is on the way. This is used to preempt input dispatch and drop input events
77// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000078constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Amount of time to allow for an event to be dispatched (measured since its eventTime)
81// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000082constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080083
84// Amount of time to allow touch events to be streamed out to a connection before requiring
85// that the first event be finished. This value extends the ANR timeout by the specified
86// amount. For example, if streaming is allowed to get ahead by one second relative to the
87// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000091constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
92
93// Log a warning when an interception call takes longer than this to process.
94constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
96// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +000097constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
98
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
100static inline nsecs_t now() {
101 return systemTime(SYSTEM_TIME_MONOTONIC);
102}
103
104static inline const char* toString(bool value) {
105 return value ? "true" : "false";
106}
107
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800108static std::string motionActionToString(int32_t action) {
109 // Convert MotionEvent action to string
110 switch(action & AMOTION_EVENT_ACTION_MASK) {
111 case AMOTION_EVENT_ACTION_DOWN:
112 return "DOWN";
113 case AMOTION_EVENT_ACTION_MOVE:
114 return "MOVE";
115 case AMOTION_EVENT_ACTION_UP:
116 return "UP";
117 case AMOTION_EVENT_ACTION_POINTER_DOWN:
118 return "POINTER_DOWN";
119 case AMOTION_EVENT_ACTION_POINTER_UP:
120 return "POINTER_UP";
121 }
122 return StringPrintf("%" PRId32, action);
123}
124
125static std::string keyActionToString(int32_t action) {
126 // Convert KeyEvent action to string
127 switch(action) {
128 case AKEY_EVENT_ACTION_DOWN:
129 return "DOWN";
130 case AKEY_EVENT_ACTION_UP:
131 return "UP";
132 case AKEY_EVENT_ACTION_MULTIPLE:
133 return "MULTIPLE";
134 }
135 return StringPrintf("%" PRId32, action);
136}
137
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
139 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
140 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
141}
142
143static bool isValidKeyAction(int32_t action) {
144 switch (action) {
145 case AKEY_EVENT_ACTION_DOWN:
146 case AKEY_EVENT_ACTION_UP:
147 return true;
148 default:
149 return false;
150 }
151}
152
153static bool validateKeyEvent(int32_t action) {
154 if (! isValidKeyAction(action)) {
155 ALOGE("Key event has invalid action code 0x%x", action);
156 return false;
157 }
158 return true;
159}
160
Michael Wright7b159c92015-05-14 14:48:03 +0100161static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800162 switch (action & AMOTION_EVENT_ACTION_MASK) {
163 case AMOTION_EVENT_ACTION_DOWN:
164 case AMOTION_EVENT_ACTION_UP:
165 case AMOTION_EVENT_ACTION_CANCEL:
166 case AMOTION_EVENT_ACTION_MOVE:
167 case AMOTION_EVENT_ACTION_OUTSIDE:
168 case AMOTION_EVENT_ACTION_HOVER_ENTER:
169 case AMOTION_EVENT_ACTION_HOVER_MOVE:
170 case AMOTION_EVENT_ACTION_HOVER_EXIT:
171 case AMOTION_EVENT_ACTION_SCROLL:
172 return true;
173 case AMOTION_EVENT_ACTION_POINTER_DOWN:
174 case AMOTION_EVENT_ACTION_POINTER_UP: {
175 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800176 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 }
Michael Wright7b159c92015-05-14 14:48:03 +0100178 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
179 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
180 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 default:
182 return false;
183 }
184}
185
Michael Wright7b159c92015-05-14 14:48:03 +0100186static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100188 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 ALOGE("Motion event has invalid action code 0x%x", action);
190 return false;
191 }
192 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000193 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 pointerCount, MAX_POINTERS);
195 return false;
196 }
197 BitSet32 pointerIdBits;
198 for (size_t i = 0; i < pointerCount; i++) {
199 int32_t id = pointerProperties[i].id;
200 if (id < 0 || id > MAX_POINTER_ID) {
201 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
202 id, MAX_POINTER_ID);
203 return false;
204 }
205 if (pointerIdBits.hasBit(id)) {
206 ALOGE("Motion event has duplicate pointer id %d", id);
207 return false;
208 }
209 pointerIdBits.markBit(id);
210 }
211 return true;
212}
213
214static bool isMainDisplay(int32_t displayId) {
215 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
216}
217
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800218static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800220 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 return;
222 }
223
224 bool first = true;
225 Region::const_iterator cur = region.begin();
226 Region::const_iterator const tail = region.end();
227 while (cur != tail) {
228 if (first) {
229 first = false;
230 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800231 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800233 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 cur++;
235 }
236}
237
238
239// --- InputDispatcher ---
240
241InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
242 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700243 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100244 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700245 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800246 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
247 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
248 mLooper = new Looper(false);
249
Yi Kong9b14ac62018-07-17 13:48:38 -0700250 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251
252 policy->getDispatcherConfiguration(&mConfig);
253}
254
255InputDispatcher::~InputDispatcher() {
256 { // acquire lock
257 AutoMutex _l(mLock);
258
259 resetKeyRepeatLocked();
260 releasePendingEventLocked();
261 drainInboundQueueLocked();
262 }
263
264 while (mConnectionsByFd.size() != 0) {
265 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
266 }
267}
268
269void InputDispatcher::dispatchOnce() {
270 nsecs_t nextWakeupTime = LONG_LONG_MAX;
271 { // acquire lock
272 AutoMutex _l(mLock);
273 mDispatcherIsAliveCondition.broadcast();
274
275 // Run a dispatch loop if there are no pending commands.
276 // The dispatch loop might enqueue commands to run afterwards.
277 if (!haveCommandsLocked()) {
278 dispatchOnceInnerLocked(&nextWakeupTime);
279 }
280
281 // Run all pending commands if there are any.
282 // If any commands were run then force the next poll to wake up immediately.
283 if (runCommandsLockedInterruptible()) {
284 nextWakeupTime = LONG_LONG_MIN;
285 }
286 } // release lock
287
288 // Wait for callback or timeout or wake. (make sure we round up, not down)
289 nsecs_t currentTime = now();
290 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
291 mLooper->pollOnce(timeoutMillis);
292}
293
294void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
295 nsecs_t currentTime = now();
296
Jeff Browndc5992e2014-04-11 01:27:26 -0700297 // Reset the key repeat timer whenever normal dispatch is suspended while the
298 // device is in a non-interactive state. This is to ensure that we abort a key
299 // repeat if the device is just coming out of sleep.
300 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800301 resetKeyRepeatLocked();
302 }
303
304 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
305 if (mDispatchFrozen) {
306#if DEBUG_FOCUS
307 ALOGD("Dispatch frozen. Waiting some more.");
308#endif
309 return;
310 }
311
312 // Optimize latency of app switches.
313 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
314 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
315 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
316 if (mAppSwitchDueTime < *nextWakeupTime) {
317 *nextWakeupTime = mAppSwitchDueTime;
318 }
319
320 // Ready to start a new event.
321 // If we don't already have a pending event, go grab one.
322 if (! mPendingEvent) {
323 if (mInboundQueue.isEmpty()) {
324 if (isAppSwitchDue) {
325 // The inbound queue is empty so the app switch key we were waiting
326 // for will never arrive. Stop waiting for it.
327 resetPendingAppSwitchLocked(false);
328 isAppSwitchDue = false;
329 }
330
331 // Synthesize a key repeat if appropriate.
332 if (mKeyRepeatState.lastKeyEntry) {
333 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
334 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
335 } else {
336 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
337 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
338 }
339 }
340 }
341
342 // Nothing to do if there is no pending event.
343 if (!mPendingEvent) {
344 return;
345 }
346 } else {
347 // Inbound queue has at least one entry.
348 mPendingEvent = mInboundQueue.dequeueAtHead();
349 traceInboundQueueLengthLocked();
350 }
351
352 // Poke user activity for this event.
353 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
354 pokeUserActivityLocked(mPendingEvent);
355 }
356
357 // Get ready to dispatch the event.
358 resetANRTimeoutsLocked();
359 }
360
361 // Now we have an event to dispatch.
362 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700363 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800364 bool done = false;
365 DropReason dropReason = DROP_REASON_NOT_DROPPED;
366 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
367 dropReason = DROP_REASON_POLICY;
368 } else if (!mDispatchEnabled) {
369 dropReason = DROP_REASON_DISABLED;
370 }
371
372 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700373 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800374 }
375
376 switch (mPendingEvent->type) {
377 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
378 ConfigurationChangedEntry* typedEntry =
379 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
380 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
381 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
382 break;
383 }
384
385 case EventEntry::TYPE_DEVICE_RESET: {
386 DeviceResetEntry* typedEntry =
387 static_cast<DeviceResetEntry*>(mPendingEvent);
388 done = dispatchDeviceResetLocked(currentTime, typedEntry);
389 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
390 break;
391 }
392
393 case EventEntry::TYPE_KEY: {
394 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
395 if (isAppSwitchDue) {
396 if (isAppSwitchKeyEventLocked(typedEntry)) {
397 resetPendingAppSwitchLocked(true);
398 isAppSwitchDue = false;
399 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
400 dropReason = DROP_REASON_APP_SWITCH;
401 }
402 }
403 if (dropReason == DROP_REASON_NOT_DROPPED
404 && isStaleEventLocked(currentTime, typedEntry)) {
405 dropReason = DROP_REASON_STALE;
406 }
407 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
408 dropReason = DROP_REASON_BLOCKED;
409 }
410 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
411 break;
412 }
413
414 case EventEntry::TYPE_MOTION: {
415 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
416 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
417 dropReason = DROP_REASON_APP_SWITCH;
418 }
419 if (dropReason == DROP_REASON_NOT_DROPPED
420 && isStaleEventLocked(currentTime, typedEntry)) {
421 dropReason = DROP_REASON_STALE;
422 }
423 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
424 dropReason = DROP_REASON_BLOCKED;
425 }
426 done = dispatchMotionLocked(currentTime, typedEntry,
427 &dropReason, nextWakeupTime);
428 break;
429 }
430
431 default:
432 ALOG_ASSERT(false);
433 break;
434 }
435
436 if (done) {
437 if (dropReason != DROP_REASON_NOT_DROPPED) {
438 dropInboundEventLocked(mPendingEvent, dropReason);
439 }
Michael Wright3a981722015-06-10 15:26:13 +0100440 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800441
442 releasePendingEventLocked();
443 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
444 }
445}
446
447bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
448 bool needWake = mInboundQueue.isEmpty();
449 mInboundQueue.enqueueAtTail(entry);
450 traceInboundQueueLengthLocked();
451
452 switch (entry->type) {
453 case EventEntry::TYPE_KEY: {
454 // Optimize app switch latency.
455 // If the application takes too long to catch up then we drop all events preceding
456 // the app switch key.
457 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
458 if (isAppSwitchKeyEventLocked(keyEntry)) {
459 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
460 mAppSwitchSawKeyDown = true;
461 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
462 if (mAppSwitchSawKeyDown) {
463#if DEBUG_APP_SWITCH
464 ALOGD("App switch is pending!");
465#endif
466 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
467 mAppSwitchSawKeyDown = false;
468 needWake = true;
469 }
470 }
471 }
472 break;
473 }
474
475 case EventEntry::TYPE_MOTION: {
476 // Optimize case where the current application is unresponsive and the user
477 // decides to touch a window in a different application.
478 // If the application takes too long to catch up then we drop all events preceding
479 // the touch into the other window.
480 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
481 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
482 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
483 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Yi Kong9b14ac62018-07-17 13:48:38 -0700484 && mInputTargetWaitApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485 int32_t displayId = motionEntry->displayId;
486 int32_t x = int32_t(motionEntry->pointerCoords[0].
487 getAxisValue(AMOTION_EVENT_AXIS_X));
488 int32_t y = int32_t(motionEntry->pointerCoords[0].
489 getAxisValue(AMOTION_EVENT_AXIS_Y));
490 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700491 if (touchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492 && touchedWindowHandle->inputApplicationHandle
493 != mInputTargetWaitApplicationHandle) {
494 // User touched a different application than the one we are waiting on.
495 // Flag the event, and start pruning the input queue.
496 mNextUnblockedEvent = motionEntry;
497 needWake = true;
498 }
499 }
500 break;
501 }
502 }
503
504 return needWake;
505}
506
507void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
508 entry->refCount += 1;
509 mRecentQueue.enqueueAtTail(entry);
510 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
511 mRecentQueue.dequeueAtHead()->release();
512 }
513}
514
515sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
516 int32_t x, int32_t y) {
517 // Traverse windows from front to back to find touched window.
Arthur Hungb92218b2018-08-14 12:00:21 +0800518 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
519 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800520 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800521 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 const InputWindowInfo* windowInfo = windowHandle->getInfo();
523 if (windowInfo->displayId == displayId) {
524 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525
526 if (windowInfo->visible) {
527 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
528 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
529 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
530 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
531 // Found window.
532 return windowHandle;
533 }
534 }
535 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800536 }
537 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700538 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539}
540
541void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
542 const char* reason;
543 switch (dropReason) {
544 case DROP_REASON_POLICY:
545#if DEBUG_INBOUND_EVENT_DETAILS
546 ALOGD("Dropped event because policy consumed it.");
547#endif
548 reason = "inbound event was dropped because the policy consumed it";
549 break;
550 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100551 if (mLastDropReason != DROP_REASON_DISABLED) {
552 ALOGI("Dropped event because input dispatch is disabled.");
553 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 reason = "inbound event was dropped because input dispatch is disabled";
555 break;
556 case DROP_REASON_APP_SWITCH:
557 ALOGI("Dropped event because of pending overdue app switch.");
558 reason = "inbound event was dropped because of pending overdue app switch";
559 break;
560 case DROP_REASON_BLOCKED:
561 ALOGI("Dropped event because the current application is not responding and the user "
562 "has started interacting with a different application.");
563 reason = "inbound event was dropped because the current application is not responding "
564 "and the user has started interacting with a different application";
565 break;
566 case DROP_REASON_STALE:
567 ALOGI("Dropped event because it is stale.");
568 reason = "inbound event was dropped because it is stale";
569 break;
570 default:
571 ALOG_ASSERT(false);
572 return;
573 }
574
575 switch (entry->type) {
576 case EventEntry::TYPE_KEY: {
577 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
578 synthesizeCancelationEventsForAllConnectionsLocked(options);
579 break;
580 }
581 case EventEntry::TYPE_MOTION: {
582 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
583 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
584 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
585 synthesizeCancelationEventsForAllConnectionsLocked(options);
586 } else {
587 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
588 synthesizeCancelationEventsForAllConnectionsLocked(options);
589 }
590 break;
591 }
592 }
593}
594
595bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
596 return keyCode == AKEYCODE_HOME
597 || keyCode == AKEYCODE_ENDCALL
598 || keyCode == AKEYCODE_APP_SWITCH;
599}
600
601bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
602 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
603 && isAppSwitchKeyCode(keyEntry->keyCode)
604 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
605 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
606}
607
608bool InputDispatcher::isAppSwitchPendingLocked() {
609 return mAppSwitchDueTime != LONG_LONG_MAX;
610}
611
612void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
613 mAppSwitchDueTime = LONG_LONG_MAX;
614
615#if DEBUG_APP_SWITCH
616 if (handled) {
617 ALOGD("App switch has arrived.");
618 } else {
619 ALOGD("App switch was abandoned.");
620 }
621#endif
622}
623
624bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
625 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
626}
627
628bool InputDispatcher::haveCommandsLocked() const {
629 return !mCommandQueue.isEmpty();
630}
631
632bool InputDispatcher::runCommandsLockedInterruptible() {
633 if (mCommandQueue.isEmpty()) {
634 return false;
635 }
636
637 do {
638 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
639
640 Command command = commandEntry->command;
641 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
642
643 commandEntry->connection.clear();
644 delete commandEntry;
645 } while (! mCommandQueue.isEmpty());
646 return true;
647}
648
649InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
650 CommandEntry* commandEntry = new CommandEntry(command);
651 mCommandQueue.enqueueAtTail(commandEntry);
652 return commandEntry;
653}
654
655void InputDispatcher::drainInboundQueueLocked() {
656 while (! mInboundQueue.isEmpty()) {
657 EventEntry* entry = mInboundQueue.dequeueAtHead();
658 releaseInboundEventLocked(entry);
659 }
660 traceInboundQueueLengthLocked();
661}
662
663void InputDispatcher::releasePendingEventLocked() {
664 if (mPendingEvent) {
665 resetANRTimeoutsLocked();
666 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700667 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 }
669}
670
671void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
672 InjectionState* injectionState = entry->injectionState;
673 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
674#if DEBUG_DISPATCH_CYCLE
675 ALOGD("Injected inbound event was dropped.");
676#endif
677 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
678 }
679 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700680 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 }
682 addRecentEventLocked(entry);
683 entry->release();
684}
685
686void InputDispatcher::resetKeyRepeatLocked() {
687 if (mKeyRepeatState.lastKeyEntry) {
688 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700689 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 }
691}
692
693InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
694 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
695
696 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700697 uint32_t policyFlags = entry->policyFlags &
698 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800699 if (entry->refCount == 1) {
700 entry->recycle();
701 entry->eventTime = currentTime;
702 entry->policyFlags = policyFlags;
703 entry->repeatCount += 1;
704 } else {
705 KeyEntry* newEntry = new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100706 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 entry->action, entry->flags, entry->keyCode, entry->scanCode,
708 entry->metaState, entry->repeatCount + 1, entry->downTime);
709
710 mKeyRepeatState.lastKeyEntry = newEntry;
711 entry->release();
712
713 entry = newEntry;
714 }
715 entry->syntheticRepeat = true;
716
717 // Increment reference count since we keep a reference to the event in
718 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
719 entry->refCount += 1;
720
721 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
722 return entry;
723}
724
725bool InputDispatcher::dispatchConfigurationChangedLocked(
726 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
727#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700728 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729#endif
730
731 // Reset key repeating in case a keyboard device was added or removed or something.
732 resetKeyRepeatLocked();
733
734 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
735 CommandEntry* commandEntry = postCommandLocked(
736 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
737 commandEntry->eventTime = entry->eventTime;
738 return true;
739}
740
741bool InputDispatcher::dispatchDeviceResetLocked(
742 nsecs_t currentTime, DeviceResetEntry* entry) {
743#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700744 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
745 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746#endif
747
748 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
749 "device was reset");
750 options.deviceId = entry->deviceId;
751 synthesizeCancelationEventsForAllConnectionsLocked(options);
752 return true;
753}
754
755bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
756 DropReason* dropReason, nsecs_t* nextWakeupTime) {
757 // Preprocessing.
758 if (! entry->dispatchInProgress) {
759 if (entry->repeatCount == 0
760 && entry->action == AKEY_EVENT_ACTION_DOWN
761 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
762 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
763 if (mKeyRepeatState.lastKeyEntry
764 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
765 // We have seen two identical key downs in a row which indicates that the device
766 // driver is automatically generating key repeats itself. We take note of the
767 // repeat here, but we disable our own next key repeat timer since it is clear that
768 // we will not need to synthesize key repeats ourselves.
769 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
770 resetKeyRepeatLocked();
771 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
772 } else {
773 // Not a repeat. Save key down state in case we do see a repeat later.
774 resetKeyRepeatLocked();
775 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
776 }
777 mKeyRepeatState.lastKeyEntry = entry;
778 entry->refCount += 1;
779 } else if (! entry->syntheticRepeat) {
780 resetKeyRepeatLocked();
781 }
782
783 if (entry->repeatCount == 1) {
784 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
785 } else {
786 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
787 }
788
789 entry->dispatchInProgress = true;
790
791 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
792 }
793
794 // Handle case where the policy asked us to try again later last time.
795 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
796 if (currentTime < entry->interceptKeyWakeupTime) {
797 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
798 *nextWakeupTime = entry->interceptKeyWakeupTime;
799 }
800 return false; // wait until next wakeup
801 }
802 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
803 entry->interceptKeyWakeupTime = 0;
804 }
805
806 // Give the policy a chance to intercept the key.
807 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
808 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
809 CommandEntry* commandEntry = postCommandLocked(
810 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Yi Kong9b14ac62018-07-17 13:48:38 -0700811 if (mFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812 commandEntry->inputWindowHandle = mFocusedWindowHandle;
813 }
814 commandEntry->keyEntry = entry;
815 entry->refCount += 1;
816 return false; // wait for the command to run
817 } else {
818 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
819 }
820 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
821 if (*dropReason == DROP_REASON_NOT_DROPPED) {
822 *dropReason = DROP_REASON_POLICY;
823 }
824 }
825
826 // Clean up if dropping the event.
827 if (*dropReason != DROP_REASON_NOT_DROPPED) {
828 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
829 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
830 return true;
831 }
832
833 // Identify targets.
834 Vector<InputTarget> inputTargets;
835 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
836 entry, inputTargets, nextWakeupTime);
837 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
838 return false;
839 }
840
841 setInjectionResultLocked(entry, injectionResult);
842 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
843 return true;
844 }
845
846 addMonitoringTargetsLocked(inputTargets);
847
848 // Dispatch the key.
849 dispatchEventLocked(currentTime, entry, inputTargets);
850 return true;
851}
852
853void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
854#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100855 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
856 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
857 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100859 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
861 entry->repeatCount, entry->downTime);
862#endif
863}
864
865bool InputDispatcher::dispatchMotionLocked(
866 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
867 // Preprocessing.
868 if (! entry->dispatchInProgress) {
869 entry->dispatchInProgress = true;
870
871 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
872 }
873
874 // Clean up if dropping the event.
875 if (*dropReason != DROP_REASON_NOT_DROPPED) {
876 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
877 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
878 return true;
879 }
880
881 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
882
883 // Identify targets.
884 Vector<InputTarget> inputTargets;
885
886 bool conflictingPointerActions = false;
887 int32_t injectionResult;
888 if (isPointerEvent) {
889 // Pointer event. (eg. touchscreen)
890 injectionResult = findTouchedWindowTargetsLocked(currentTime,
891 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
892 } else {
893 // Non touch event. (eg. trackball)
894 injectionResult = findFocusedWindowTargetsLocked(currentTime,
895 entry, inputTargets, nextWakeupTime);
896 }
897 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
898 return false;
899 }
900
901 setInjectionResultLocked(entry, injectionResult);
902 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100903 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
904 CancelationOptions::Mode mode(isPointerEvent ?
905 CancelationOptions::CANCEL_POINTER_EVENTS :
906 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
907 CancelationOptions options(mode, "input event injection failed");
908 synthesizeCancelationEventsForMonitorsLocked(options);
909 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800910 return true;
911 }
912
Tarandeep Singh48aeb512017-07-17 11:22:52 -0700913 addMonitoringTargetsLocked(inputTargets);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800914
915 // Dispatch the motion.
916 if (conflictingPointerActions) {
917 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
918 "conflicting pointer actions");
919 synthesizeCancelationEventsForAllConnectionsLocked(options);
920 }
921 dispatchEventLocked(currentTime, entry, inputTargets);
922 return true;
923}
924
925
926void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
927#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800928 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
929 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100930 "action=0x%x, actionButton=0x%x, flags=0x%x, "
931 "metaState=0x%x, buttonState=0x%x,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700932 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800934 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100935 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936 entry->metaState, entry->buttonState,
937 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
938 entry->downTime);
939
940 for (uint32_t i = 0; i < entry->pointerCount; i++) {
941 ALOGD(" Pointer %d: id=%d, toolType=%d, "
942 "x=%f, y=%f, pressure=%f, size=%f, "
943 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800944 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 i, entry->pointerProperties[i].id,
946 entry->pointerProperties[i].toolType,
947 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
948 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
949 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
950 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
951 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
952 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
953 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
954 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800955 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956 }
957#endif
958}
959
960void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
961 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
962#if DEBUG_DISPATCH_CYCLE
963 ALOGD("dispatchEventToCurrentInputTargets");
964#endif
965
966 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
967
968 pokeUserActivityLocked(eventEntry);
969
970 for (size_t i = 0; i < inputTargets.size(); i++) {
971 const InputTarget& inputTarget = inputTargets.itemAt(i);
972
973 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
974 if (connectionIndex >= 0) {
975 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
976 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
977 } else {
978#if DEBUG_FOCUS
979 ALOGD("Dropping event delivery to target with channel '%s' because it "
980 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800981 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982#endif
983 }
984 }
985}
986
987int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
988 const EventEntry* entry,
989 const sp<InputApplicationHandle>& applicationHandle,
990 const sp<InputWindowHandle>& windowHandle,
991 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700992 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
994#if DEBUG_FOCUS
995 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
996#endif
997 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
998 mInputTargetWaitStartTime = currentTime;
999 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1000 mInputTargetWaitTimeoutExpired = false;
1001 mInputTargetWaitApplicationHandle.clear();
1002 }
1003 } else {
1004 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1005#if DEBUG_FOCUS
1006 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001007 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001008 reason);
1009#endif
1010 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001011 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001013 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 timeout = applicationHandle->getDispatchingTimeout(
1015 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1016 } else {
1017 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1018 }
1019
1020 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1021 mInputTargetWaitStartTime = currentTime;
1022 mInputTargetWaitTimeoutTime = currentTime + timeout;
1023 mInputTargetWaitTimeoutExpired = false;
1024 mInputTargetWaitApplicationHandle.clear();
1025
Yi Kong9b14ac62018-07-17 13:48:38 -07001026 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
1028 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001029 if (mInputTargetWaitApplicationHandle == nullptr && applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 mInputTargetWaitApplicationHandle = applicationHandle;
1031 }
1032 }
1033 }
1034
1035 if (mInputTargetWaitTimeoutExpired) {
1036 return INPUT_EVENT_INJECTION_TIMED_OUT;
1037 }
1038
1039 if (currentTime >= mInputTargetWaitTimeoutTime) {
1040 onANRLocked(currentTime, applicationHandle, windowHandle,
1041 entry->eventTime, mInputTargetWaitStartTime, reason);
1042
1043 // Force poll loop to wake up immediately on next iteration once we get the
1044 // ANR response back from the policy.
1045 *nextWakeupTime = LONG_LONG_MIN;
1046 return INPUT_EVENT_INJECTION_PENDING;
1047 } else {
1048 // Force poll loop to wake up when timeout is due.
1049 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1050 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1051 }
1052 return INPUT_EVENT_INJECTION_PENDING;
1053 }
1054}
1055
1056void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1057 const sp<InputChannel>& inputChannel) {
1058 if (newTimeout > 0) {
1059 // Extend the timeout.
1060 mInputTargetWaitTimeoutTime = now() + newTimeout;
1061 } else {
1062 // Give up.
1063 mInputTargetWaitTimeoutExpired = true;
1064
1065 // Input state will not be realistic. Mark it out of sync.
1066 if (inputChannel.get()) {
1067 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1068 if (connectionIndex >= 0) {
1069 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1070 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1071
Yi Kong9b14ac62018-07-17 13:48:38 -07001072 if (windowHandle != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001073 const InputWindowInfo* info = windowHandle->getInfo();
1074 if (info) {
1075 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId);
1076 if (stateIndex >= 0) {
1077 mTouchStatesByDisplay.editValueAt(stateIndex).removeWindow(
1078 windowHandle);
1079 }
1080 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081 }
1082
1083 if (connection->status == Connection::STATUS_NORMAL) {
1084 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1085 "application not responding");
1086 synthesizeCancelationEventsForConnectionLocked(connection, options);
1087 }
1088 }
1089 }
1090 }
1091}
1092
1093nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1094 nsecs_t currentTime) {
1095 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1096 return currentTime - mInputTargetWaitStartTime;
1097 }
1098 return 0;
1099}
1100
1101void InputDispatcher::resetANRTimeoutsLocked() {
1102#if DEBUG_FOCUS
1103 ALOGD("Resetting ANR timeouts.");
1104#endif
1105
1106 // Reset input target wait timeout.
1107 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1108 mInputTargetWaitApplicationHandle.clear();
1109}
1110
1111int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1112 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1113 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001114 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115
1116 // If there is no currently focused window and no focused application
1117 // then drop the event.
Yi Kong9b14ac62018-07-17 13:48:38 -07001118 if (mFocusedWindowHandle == nullptr) {
1119 if (mFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001121 mFocusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 "Waiting because no window has focus but there is a "
1123 "focused application that may eventually add a window "
1124 "when it finishes starting up.");
1125 goto Unresponsive;
1126 }
1127
1128 ALOGI("Dropping event because there is no focused window or focused application.");
1129 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1130 goto Failed;
1131 }
1132
1133 // Check permissions.
1134 if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
1135 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1136 goto Failed;
1137 }
1138
Jeff Brownffb49772014-10-10 19:01:34 -07001139 // Check whether the window is ready for more input.
1140 reason = checkWindowReadyForMoreInputLocked(currentTime,
1141 mFocusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001142 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001144 mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145 goto Unresponsive;
1146 }
1147
1148 // Success! Output targets.
1149 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1150 addWindowTargetLocked(mFocusedWindowHandle,
1151 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1152 inputTargets);
1153
1154 // Done.
1155Failed:
1156Unresponsive:
1157 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1158 updateDispatchStatisticsLocked(currentTime, entry,
1159 injectionResult, timeSpentWaitingForApplication);
1160#if DEBUG_FOCUS
1161 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1162 "timeSpentWaitingForApplication=%0.1fms",
1163 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1164#endif
1165 return injectionResult;
1166}
1167
1168int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1169 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1170 bool* outConflictingPointerActions) {
1171 enum InjectionPermission {
1172 INJECTION_PERMISSION_UNKNOWN,
1173 INJECTION_PERMISSION_GRANTED,
1174 INJECTION_PERMISSION_DENIED
1175 };
1176
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 // For security reasons, we defer updating the touch state until we are sure that
1178 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 int32_t displayId = entry->displayId;
1180 int32_t action = entry->action;
1181 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1182
1183 // Update the touch state as needed based on the properties of the touch event.
1184 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1185 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1186 sp<InputWindowHandle> newHoverWindowHandle;
1187
Jeff Brownf086ddb2014-02-11 14:28:48 -08001188 // Copy current touch state into mTempTouchState.
1189 // This state is always reset at the end of this function, so if we don't find state
1190 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001191 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001192 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1193 if (oldStateIndex >= 0) {
1194 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1195 mTempTouchState.copyFrom(*oldState);
1196 }
1197
1198 bool isSplit = mTempTouchState.split;
1199 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1200 && (mTempTouchState.deviceId != entry->deviceId
1201 || mTempTouchState.source != entry->source
1202 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1204 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1205 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1206 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1207 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1208 || isHoverAction);
1209 bool wrongDevice = false;
1210 if (newGesture) {
1211 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001212 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213#if DEBUG_FOCUS
1214 ALOGD("Dropping event because a pointer for a different device is already down.");
1215#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001216 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1218 switchedDevice = false;
1219 wrongDevice = true;
1220 goto Failed;
1221 }
1222 mTempTouchState.reset();
1223 mTempTouchState.down = down;
1224 mTempTouchState.deviceId = entry->deviceId;
1225 mTempTouchState.source = entry->source;
1226 mTempTouchState.displayId = displayId;
1227 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001228 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1229#if DEBUG_FOCUS
1230 ALOGI("Dropping move event because a pointer for a different device is already active.");
1231#endif
1232 // TODO: test multiple simultaneous input streams.
1233 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1234 switchedDevice = false;
1235 wrongDevice = true;
1236 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 }
1238
1239 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1240 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1241
1242 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1243 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1244 getAxisValue(AMOTION_EVENT_AXIS_X));
1245 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1246 getAxisValue(AMOTION_EVENT_AXIS_Y));
1247 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 bool isTouchModal = false;
1249
1250 // Traverse windows from front to back to find touched window and outside targets.
Arthur Hungb92218b2018-08-14 12:00:21 +08001251 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1252 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001254 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1256 if (windowInfo->displayId != displayId) {
1257 continue; // wrong display
1258 }
1259
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 int32_t flags = windowInfo->layoutParamsFlags;
1261 if (windowInfo->visible) {
1262 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1263 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1264 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1265 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001266 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 break; // found touched window, exit window loop
1268 }
1269 }
1270
1271 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1272 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001273 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001274 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 }
1276 }
1277 }
1278
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001280 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1282 // New window supports splitting.
1283 isSplit = true;
1284 } else if (isSplit) {
1285 // New window does not support splitting but we have already split events.
1286 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001287 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 }
1289
1290 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001291 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 // Try to assign the pointer to the first foreground window we find, if there is one.
1293 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001294 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 ALOGI("Dropping event because there is no touchable window at (%d, %d).", x, y);
1296 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1297 goto Failed;
1298 }
1299 }
1300
1301 // Set target flags.
1302 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1303 if (isSplit) {
1304 targetFlags |= InputTarget::FLAG_SPLIT;
1305 }
1306 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1307 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001308 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1309 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001310 }
1311
1312 // Update hover state.
1313 if (isHoverAction) {
1314 newHoverWindowHandle = newTouchedWindowHandle;
1315 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1316 newHoverWindowHandle = mLastHoverWindowHandle;
1317 }
1318
1319 // Update the temporary touch state.
1320 BitSet32 pointerIds;
1321 if (isSplit) {
1322 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1323 pointerIds.markBit(pointerId);
1324 }
1325 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1326 } else {
1327 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1328
1329 // If the pointer is not currently down, then ignore the event.
1330 if (! mTempTouchState.down) {
1331#if DEBUG_FOCUS
1332 ALOGD("Dropping event because the pointer is not down or we previously "
1333 "dropped the pointer down event.");
1334#endif
1335 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1336 goto Failed;
1337 }
1338
1339 // Check whether touches should slip outside of the current foreground window.
1340 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1341 && entry->pointerCount == 1
1342 && mTempTouchState.isSlippery()) {
1343 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1344 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1345
1346 sp<InputWindowHandle> oldTouchedWindowHandle =
1347 mTempTouchState.getFirstForegroundWindowHandle();
1348 sp<InputWindowHandle> newTouchedWindowHandle =
1349 findTouchedWindowAtLocked(displayId, x, y);
1350 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001351 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001352#if DEBUG_FOCUS
1353 ALOGD("Touch is slipping out of window %s into window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001354 oldTouchedWindowHandle->getName().c_str(),
1355 newTouchedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356#endif
1357 // Make a slippery exit from the old window.
1358 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1359 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1360
1361 // Make a slippery entrance into the new window.
1362 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1363 isSplit = true;
1364 }
1365
1366 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1367 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1368 if (isSplit) {
1369 targetFlags |= InputTarget::FLAG_SPLIT;
1370 }
1371 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1372 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1373 }
1374
1375 BitSet32 pointerIds;
1376 if (isSplit) {
1377 pointerIds.markBit(entry->pointerProperties[0].id);
1378 }
1379 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1380 }
1381 }
1382 }
1383
1384 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1385 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001386 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001387#if DEBUG_HOVER
1388 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001389 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390#endif
1391 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1392 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1393 }
1394
1395 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001396 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397#if DEBUG_HOVER
1398 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001399 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400#endif
1401 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1402 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1403 }
1404 }
1405
1406 // Check permission to inject into all touched foreground windows and ensure there
1407 // is at least one touched foreground window.
1408 {
1409 bool haveForegroundWindow = false;
1410 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1411 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1412 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1413 haveForegroundWindow = true;
1414 if (! checkInjectionPermission(touchedWindow.windowHandle,
1415 entry->injectionState)) {
1416 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1417 injectionPermission = INJECTION_PERMISSION_DENIED;
1418 goto Failed;
1419 }
1420 }
1421 }
1422 if (! haveForegroundWindow) {
1423#if DEBUG_FOCUS
1424 ALOGD("Dropping event because there is no touched foreground window to receive it.");
1425#endif
1426 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1427 goto Failed;
1428 }
1429
1430 // Permission granted to injection into all touched foreground windows.
1431 injectionPermission = INJECTION_PERMISSION_GRANTED;
1432 }
1433
1434 // Check whether windows listening for outside touches are owned by the same UID. If it is
1435 // set the policy flag that we will not reveal coordinate information to this window.
1436 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1437 sp<InputWindowHandle> foregroundWindowHandle =
1438 mTempTouchState.getFirstForegroundWindowHandle();
1439 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1440 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1441 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1442 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1443 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1444 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1445 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1446 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1447 }
1448 }
1449 }
1450 }
1451
1452 // Ensure all touched foreground windows are ready for new input.
1453 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1454 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1455 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001456 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001457 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001458 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001459 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001461 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 goto Unresponsive;
1463 }
1464 }
1465 }
1466
1467 // If this is the first pointer going down and the touched window has a wallpaper
1468 // then also add the touched wallpaper windows so they are locked in for the duration
1469 // of the touch gesture.
1470 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1471 // engine only supports touch events. We would need to add a mechanism similar
1472 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1473 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1474 sp<InputWindowHandle> foregroundWindowHandle =
1475 mTempTouchState.getFirstForegroundWindowHandle();
1476 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001477 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1478 size_t numWindows = windowHandles.size();
1479 for (size_t i = 0; i < numWindows; i++) {
1480 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001481 const InputWindowInfo* info = windowHandle->getInfo();
1482 if (info->displayId == displayId
1483 && windowHandle->getInfo()->layoutParamsType
1484 == InputWindowInfo::TYPE_WALLPAPER) {
1485 mTempTouchState.addOrUpdateWindow(windowHandle,
1486 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001487 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 | InputTarget::FLAG_DISPATCH_AS_IS,
1489 BitSet32(0));
1490 }
1491 }
1492 }
1493 }
1494
1495 // Success! Output targets.
1496 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1497
1498 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1499 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1500 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1501 touchedWindow.pointerIds, inputTargets);
1502 }
1503
1504 // Drop the outside or hover touch windows since we will not care about them
1505 // in the next iteration.
1506 mTempTouchState.filterNonAsIsTouchWindows();
1507
1508Failed:
1509 // Check injection permission once and for all.
1510 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001511 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 injectionPermission = INJECTION_PERMISSION_GRANTED;
1513 } else {
1514 injectionPermission = INJECTION_PERMISSION_DENIED;
1515 }
1516 }
1517
1518 // Update final pieces of touch state if the injector had permission.
1519 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1520 if (!wrongDevice) {
1521 if (switchedDevice) {
1522#if DEBUG_FOCUS
1523 ALOGD("Conflicting pointer actions: Switched to a different device.");
1524#endif
1525 *outConflictingPointerActions = true;
1526 }
1527
1528 if (isHoverAction) {
1529 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001530 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531#if DEBUG_FOCUS
1532 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1533#endif
1534 *outConflictingPointerActions = true;
1535 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001536 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1538 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001539 mTempTouchState.deviceId = entry->deviceId;
1540 mTempTouchState.source = entry->source;
1541 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 }
1543 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1544 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1545 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001546 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1548 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001549 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550#if DEBUG_FOCUS
1551 ALOGD("Conflicting pointer actions: Down received while already down.");
1552#endif
1553 *outConflictingPointerActions = true;
1554 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1556 // One pointer went up.
1557 if (isSplit) {
1558 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1559 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1560
1561 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1562 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1563 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1564 touchedWindow.pointerIds.clearBit(pointerId);
1565 if (touchedWindow.pointerIds.isEmpty()) {
1566 mTempTouchState.windows.removeAt(i);
1567 continue;
1568 }
1569 }
1570 i += 1;
1571 }
1572 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001573 }
1574
1575 // Save changes unless the action was scroll in which case the temporary touch
1576 // state was only valid for this one action.
1577 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1578 if (mTempTouchState.displayId >= 0) {
1579 if (oldStateIndex >= 0) {
1580 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1581 } else {
1582 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1583 }
1584 } else if (oldStateIndex >= 0) {
1585 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 }
1588
1589 // Update hover state.
1590 mLastHoverWindowHandle = newHoverWindowHandle;
1591 }
1592 } else {
1593#if DEBUG_FOCUS
1594 ALOGD("Not updating touch focus because injection was denied.");
1595#endif
1596 }
1597
1598Unresponsive:
1599 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1600 mTempTouchState.reset();
1601
1602 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1603 updateDispatchStatisticsLocked(currentTime, entry,
1604 injectionResult, timeSpentWaitingForApplication);
1605#if DEBUG_FOCUS
1606 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1607 "timeSpentWaitingForApplication=%0.1fms",
1608 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1609#endif
1610 return injectionResult;
1611}
1612
1613void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1614 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1615 inputTargets.push();
1616
1617 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1618 InputTarget& target = inputTargets.editTop();
1619 target.inputChannel = windowInfo->inputChannel;
1620 target.flags = targetFlags;
1621 target.xOffset = - windowInfo->frameLeft;
1622 target.yOffset = - windowInfo->frameTop;
1623 target.scaleFactor = windowInfo->scaleFactor;
1624 target.pointerIds = pointerIds;
1625}
1626
1627void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
1628 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
1629 inputTargets.push();
1630
1631 InputTarget& target = inputTargets.editTop();
1632 target.inputChannel = mMonitoringChannels[i];
1633 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1634 target.xOffset = 0;
1635 target.yOffset = 0;
1636 target.pointerIds.clear();
1637 target.scaleFactor = 1.0f;
1638 }
1639}
1640
1641bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1642 const InjectionState* injectionState) {
1643 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001644 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001645 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1646 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001647 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001648 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1649 "owned by uid %d",
1650 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001651 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 windowHandle->getInfo()->ownerUid);
1653 } else {
1654 ALOGW("Permission denied: injecting event from pid %d uid %d",
1655 injectionState->injectorPid, injectionState->injectorUid);
1656 }
1657 return false;
1658 }
1659 return true;
1660}
1661
1662bool InputDispatcher::isWindowObscuredAtPointLocked(
1663 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1664 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001665 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1666 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001668 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001669 if (otherHandle == windowHandle) {
1670 break;
1671 }
1672
1673 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1674 if (otherInfo->displayId == displayId
1675 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1676 && otherInfo->frameContainsPoint(x, y)) {
1677 return true;
1678 }
1679 }
1680 return false;
1681}
1682
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001683
1684bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1685 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001686 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001687 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hungb92218b2018-08-14 12:00:21 +08001688 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001689 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001690 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001691 if (otherHandle == windowHandle) {
1692 break;
1693 }
1694
1695 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1696 if (otherInfo->displayId == displayId
1697 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1698 && otherInfo->overlaps(windowInfo)) {
1699 return true;
1700 }
1701 }
1702 return false;
1703}
1704
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001705std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001706 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1707 const char* targetType) {
1708 // If the window is paused then keep waiting.
1709 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001710 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001711 }
1712
1713 // If the window's connection is not registered then keep waiting.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brownffb49772014-10-10 19:01:34 -07001715 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001716 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001717 "registered with the input dispatcher. The window may be in the process "
1718 "of being removed.", targetType);
1719 }
1720
1721 // If the connection is dead then keep waiting.
1722 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1723 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001724 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001725 "The window may be in the process of being removed.", targetType,
1726 connection->getStatusLabel());
1727 }
1728
1729 // If the connection is backed up then keep waiting.
1730 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001731 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001732 "Outbound queue length: %d. Wait queue length: %d.",
1733 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1734 }
1735
1736 // Ensure that the dispatch queues aren't too far backed up for this event.
1737 if (eventEntry->type == EventEntry::TYPE_KEY) {
1738 // If the event is a key event, then we must wait for all previous events to
1739 // complete before delivering it because previous events may have the
1740 // side-effect of transferring focus to a different window and we want to
1741 // ensure that the following keys are sent to the new window.
1742 //
1743 // Suppose the user touches a button in a window then immediately presses "A".
1744 // If the button causes a pop-up window to appear then we want to ensure that
1745 // the "A" key is delivered to the new pop-up window. This is because users
1746 // often anticipate pending UI changes when typing on a keyboard.
1747 // To obtain this behavior, we must serialize key events with respect to all
1748 // prior input events.
1749 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001750 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001751 "finished processing all of the input events that were previously "
1752 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1753 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 }
Jeff Brownffb49772014-10-10 19:01:34 -07001755 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001756 // Touch events can always be sent to a window immediately because the user intended
1757 // to touch whatever was visible at the time. Even if focus changes or a new
1758 // window appears moments later, the touch event was meant to be delivered to
1759 // whatever window happened to be on screen at the time.
1760 //
1761 // Generic motion events, such as trackball or joystick events are a little trickier.
1762 // Like key events, generic motion events are delivered to the focused window.
1763 // Unlike key events, generic motion events don't tend to transfer focus to other
1764 // windows and it is not important for them to be serialized. So we prefer to deliver
1765 // generic motion events as soon as possible to improve efficiency and reduce lag
1766 // through batching.
1767 //
1768 // The one case where we pause input event delivery is when the wait queue is piling
1769 // up with lots of events because the application is not responding.
1770 // This condition ensures that ANRs are detected reliably.
1771 if (!connection->waitQueue.isEmpty()
1772 && currentTime >= connection->waitQueue.head->deliveryTime
1773 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001774 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001775 "finished processing certain input events that were delivered to it over "
1776 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1777 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1778 connection->waitQueue.count(),
1779 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 }
1781 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001782 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783}
1784
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001785std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001786 const sp<InputApplicationHandle>& applicationHandle,
1787 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001788 if (applicationHandle != nullptr) {
1789 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001790 std::string label(applicationHandle->getName());
1791 label += " - ";
1792 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 return label;
1794 } else {
1795 return applicationHandle->getName();
1796 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001797 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001798 return windowHandle->getName();
1799 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001800 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001801 }
1802}
1803
1804void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001805 if (mFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
1807 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1808#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001809 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810#endif
1811 return;
1812 }
1813 }
1814
1815 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1816 switch (eventEntry->type) {
1817 case EventEntry::TYPE_MOTION: {
1818 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1819 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1820 return;
1821 }
1822
1823 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1824 eventType = USER_ACTIVITY_EVENT_TOUCH;
1825 }
1826 break;
1827 }
1828 case EventEntry::TYPE_KEY: {
1829 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1830 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1831 return;
1832 }
1833 eventType = USER_ACTIVITY_EVENT_BUTTON;
1834 break;
1835 }
1836 }
1837
1838 CommandEntry* commandEntry = postCommandLocked(
1839 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1840 commandEntry->eventTime = eventEntry->eventTime;
1841 commandEntry->userActivityEventType = eventType;
1842}
1843
1844void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1845 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1846#if DEBUG_DISPATCH_CYCLE
1847 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1848 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1849 "pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001850 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 inputTarget->xOffset, inputTarget->yOffset,
1852 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1853#endif
1854
1855 // Skip this event if the connection status is not normal.
1856 // We don't want to enqueue additional outbound events if the connection is broken.
1857 if (connection->status != Connection::STATUS_NORMAL) {
1858#if DEBUG_DISPATCH_CYCLE
1859 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001860 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861#endif
1862 return;
1863 }
1864
1865 // Split a motion event if needed.
1866 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1867 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1868
1869 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1870 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1871 MotionEntry* splitMotionEntry = splitMotionEvent(
1872 originalMotionEntry, inputTarget->pointerIds);
1873 if (!splitMotionEntry) {
1874 return; // split event was dropped
1875 }
1876#if DEBUG_FOCUS
1877 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001878 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1880#endif
1881 enqueueDispatchEntriesLocked(currentTime, connection,
1882 splitMotionEntry, inputTarget);
1883 splitMotionEntry->release();
1884 return;
1885 }
1886 }
1887
1888 // Not splitting. Enqueue dispatch entries for the event as is.
1889 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1890}
1891
1892void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1893 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1894 bool wasEmpty = connection->outboundQueue.isEmpty();
1895
1896 // Enqueue dispatch entries for the requested modes.
1897 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1898 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1899 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1900 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1901 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1902 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1903 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1904 InputTarget::FLAG_DISPATCH_AS_IS);
1905 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1906 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1907 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1908 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1909
1910 // If the outbound queue was previously empty, start the dispatch cycle going.
1911 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1912 startDispatchCycleLocked(currentTime, connection);
1913 }
1914}
1915
1916void InputDispatcher::enqueueDispatchEntryLocked(
1917 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1918 int32_t dispatchMode) {
1919 int32_t inputTargetFlags = inputTarget->flags;
1920 if (!(inputTargetFlags & dispatchMode)) {
1921 return;
1922 }
1923 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1924
1925 // This is a new event.
1926 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1927 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1928 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1929 inputTarget->scaleFactor);
1930
1931 // Apply target flags and update the connection's input state.
1932 switch (eventEntry->type) {
1933 case EventEntry::TYPE_KEY: {
1934 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1935 dispatchEntry->resolvedAction = keyEntry->action;
1936 dispatchEntry->resolvedFlags = keyEntry->flags;
1937
1938 if (!connection->inputState.trackKey(keyEntry,
1939 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1940#if DEBUG_DISPATCH_CYCLE
1941 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001942 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943#endif
1944 delete dispatchEntry;
1945 return; // skip the inconsistent event
1946 }
1947 break;
1948 }
1949
1950 case EventEntry::TYPE_MOTION: {
1951 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
1952 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1953 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
1954 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
1955 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
1956 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
1957 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1958 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
1959 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
1960 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
1961 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
1962 } else {
1963 dispatchEntry->resolvedAction = motionEntry->action;
1964 }
1965 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1966 && !connection->inputState.isHovering(
1967 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
1968#if DEBUG_DISPATCH_CYCLE
1969 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001970 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971#endif
1972 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
1973 }
1974
1975 dispatchEntry->resolvedFlags = motionEntry->flags;
1976 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
1977 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
1978 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001979 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
1980 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1981 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982
1983 if (!connection->inputState.trackMotion(motionEntry,
1984 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
1985#if DEBUG_DISPATCH_CYCLE
1986 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001987 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988#endif
1989 delete dispatchEntry;
1990 return; // skip the inconsistent event
1991 }
1992 break;
1993 }
1994 }
1995
1996 // Remember that we are waiting for this dispatch to complete.
1997 if (dispatchEntry->hasForegroundTarget()) {
1998 incrementPendingForegroundDispatchesLocked(eventEntry);
1999 }
2000
2001 // Enqueue the dispatch entry.
2002 connection->outboundQueue.enqueueAtTail(dispatchEntry);
2003 traceOutboundQueueLengthLocked(connection);
2004}
2005
2006void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2007 const sp<Connection>& connection) {
2008#if DEBUG_DISPATCH_CYCLE
2009 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002010 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011#endif
2012
2013 while (connection->status == Connection::STATUS_NORMAL
2014 && !connection->outboundQueue.isEmpty()) {
2015 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2016 dispatchEntry->deliveryTime = currentTime;
2017
2018 // Publish the event.
2019 status_t status;
2020 EventEntry* eventEntry = dispatchEntry->eventEntry;
2021 switch (eventEntry->type) {
2022 case EventEntry::TYPE_KEY: {
2023 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2024
2025 // Publish the key event.
2026 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002027 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2029 keyEntry->keyCode, keyEntry->scanCode,
2030 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2031 keyEntry->eventTime);
2032 break;
2033 }
2034
2035 case EventEntry::TYPE_MOTION: {
2036 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2037
2038 PointerCoords scaledCoords[MAX_POINTERS];
2039 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2040
2041 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002042 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2044 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002045 float scaleFactor = dispatchEntry->scaleFactor;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002046 xOffset = dispatchEntry->xOffset * scaleFactor;
2047 yOffset = dispatchEntry->yOffset * scaleFactor;
2048 if (scaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002049 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002050 scaledCoords[i] = motionEntry->pointerCoords[i];
2051 scaledCoords[i].scale(scaleFactor);
2052 }
2053 usingCoords = scaledCoords;
2054 }
2055 } else {
2056 xOffset = 0.0f;
2057 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058
2059 // We don't want the dispatch target to know.
2060 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002061 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 scaledCoords[i].clear();
2063 }
2064 usingCoords = scaledCoords;
2065 }
2066 }
2067
2068 // Publish the motion event.
2069 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002070 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002071 dispatchEntry->resolvedAction, motionEntry->actionButton,
2072 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2073 motionEntry->metaState, motionEntry->buttonState,
2074 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 motionEntry->downTime, motionEntry->eventTime,
2076 motionEntry->pointerCount, motionEntry->pointerProperties,
2077 usingCoords);
2078 break;
2079 }
2080
2081 default:
2082 ALOG_ASSERT(false);
2083 return;
2084 }
2085
2086 // Check the result.
2087 if (status) {
2088 if (status == WOULD_BLOCK) {
2089 if (connection->waitQueue.isEmpty()) {
2090 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2091 "This is unexpected because the wait queue is empty, so the pipe "
2092 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002093 "event to it, status=%d", connection->getInputChannelName().c_str(),
2094 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2096 } else {
2097 // Pipe is full and we are waiting for the app to finish process some events
2098 // before sending more events to it.
2099#if DEBUG_DISPATCH_CYCLE
2100 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2101 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002102 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103#endif
2104 connection->inputPublisherBlocked = true;
2105 }
2106 } else {
2107 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002108 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2110 }
2111 return;
2112 }
2113
2114 // Re-enqueue the event on the wait queue.
2115 connection->outboundQueue.dequeue(dispatchEntry);
2116 traceOutboundQueueLengthLocked(connection);
2117 connection->waitQueue.enqueueAtTail(dispatchEntry);
2118 traceWaitQueueLengthLocked(connection);
2119 }
2120}
2121
2122void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2123 const sp<Connection>& connection, uint32_t seq, bool handled) {
2124#if DEBUG_DISPATCH_CYCLE
2125 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002126 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127#endif
2128
2129 connection->inputPublisherBlocked = false;
2130
2131 if (connection->status == Connection::STATUS_BROKEN
2132 || connection->status == Connection::STATUS_ZOMBIE) {
2133 return;
2134 }
2135
2136 // Notify other system components and prepare to start the next dispatch cycle.
2137 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2138}
2139
2140void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2141 const sp<Connection>& connection, bool notify) {
2142#if DEBUG_DISPATCH_CYCLE
2143 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002144 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145#endif
2146
2147 // Clear the dispatch queues.
2148 drainDispatchQueueLocked(&connection->outboundQueue);
2149 traceOutboundQueueLengthLocked(connection);
2150 drainDispatchQueueLocked(&connection->waitQueue);
2151 traceWaitQueueLengthLocked(connection);
2152
2153 // The connection appears to be unrecoverably broken.
2154 // Ignore already broken or zombie connections.
2155 if (connection->status == Connection::STATUS_NORMAL) {
2156 connection->status = Connection::STATUS_BROKEN;
2157
2158 if (notify) {
2159 // Notify other system components.
2160 onDispatchCycleBrokenLocked(currentTime, connection);
2161 }
2162 }
2163}
2164
2165void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2166 while (!queue->isEmpty()) {
2167 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2168 releaseDispatchEntryLocked(dispatchEntry);
2169 }
2170}
2171
2172void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2173 if (dispatchEntry->hasForegroundTarget()) {
2174 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2175 }
2176 delete dispatchEntry;
2177}
2178
2179int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2180 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2181
2182 { // acquire lock
2183 AutoMutex _l(d->mLock);
2184
2185 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2186 if (connectionIndex < 0) {
2187 ALOGE("Received spurious receive callback for unknown input channel. "
2188 "fd=%d, events=0x%x", fd, events);
2189 return 0; // remove the callback
2190 }
2191
2192 bool notify;
2193 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2194 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2195 if (!(events & ALOOPER_EVENT_INPUT)) {
2196 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002197 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 return 1;
2199 }
2200
2201 nsecs_t currentTime = now();
2202 bool gotOne = false;
2203 status_t status;
2204 for (;;) {
2205 uint32_t seq;
2206 bool handled;
2207 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2208 if (status) {
2209 break;
2210 }
2211 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2212 gotOne = true;
2213 }
2214 if (gotOne) {
2215 d->runCommandsLockedInterruptible();
2216 if (status == WOULD_BLOCK) {
2217 return 1;
2218 }
2219 }
2220
2221 notify = status != DEAD_OBJECT || !connection->monitor;
2222 if (notify) {
2223 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002224 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225 }
2226 } else {
2227 // Monitor channels are never explicitly unregistered.
2228 // We do it automatically when the remote endpoint is closed so don't warn
2229 // about them.
2230 notify = !connection->monitor;
2231 if (notify) {
2232 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002233 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 }
2235 }
2236
2237 // Unregister the channel.
2238 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2239 return 0; // remove the callback
2240 } // release lock
2241}
2242
2243void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2244 const CancelationOptions& options) {
2245 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2246 synthesizeCancelationEventsForConnectionLocked(
2247 mConnectionsByFd.valueAt(i), options);
2248 }
2249}
2250
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002251void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2252 const CancelationOptions& options) {
2253 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
2254 synthesizeCancelationEventsForInputChannelLocked(mMonitoringChannels[i], options);
2255 }
2256}
2257
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2259 const sp<InputChannel>& channel, const CancelationOptions& options) {
2260 ssize_t index = getConnectionIndexLocked(channel);
2261 if (index >= 0) {
2262 synthesizeCancelationEventsForConnectionLocked(
2263 mConnectionsByFd.valueAt(index), options);
2264 }
2265}
2266
2267void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2268 const sp<Connection>& connection, const CancelationOptions& options) {
2269 if (connection->status == Connection::STATUS_BROKEN) {
2270 return;
2271 }
2272
2273 nsecs_t currentTime = now();
2274
2275 Vector<EventEntry*> cancelationEvents;
2276 connection->inputState.synthesizeCancelationEvents(currentTime,
2277 cancelationEvents, options);
2278
2279 if (!cancelationEvents.isEmpty()) {
2280#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002281 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002283 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284 options.reason, options.mode);
2285#endif
2286 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2287 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2288 switch (cancelationEventEntry->type) {
2289 case EventEntry::TYPE_KEY:
2290 logOutboundKeyDetailsLocked("cancel - ",
2291 static_cast<KeyEntry*>(cancelationEventEntry));
2292 break;
2293 case EventEntry::TYPE_MOTION:
2294 logOutboundMotionDetailsLocked("cancel - ",
2295 static_cast<MotionEntry*>(cancelationEventEntry));
2296 break;
2297 }
2298
2299 InputTarget target;
2300 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07002301 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2303 target.xOffset = -windowInfo->frameLeft;
2304 target.yOffset = -windowInfo->frameTop;
2305 target.scaleFactor = windowInfo->scaleFactor;
2306 } else {
2307 target.xOffset = 0;
2308 target.yOffset = 0;
2309 target.scaleFactor = 1.0f;
2310 }
2311 target.inputChannel = connection->inputChannel;
2312 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2313
2314 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2315 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2316
2317 cancelationEventEntry->release();
2318 }
2319
2320 startDispatchCycleLocked(currentTime, connection);
2321 }
2322}
2323
2324InputDispatcher::MotionEntry*
2325InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2326 ALOG_ASSERT(pointerIds.value != 0);
2327
2328 uint32_t splitPointerIndexMap[MAX_POINTERS];
2329 PointerProperties splitPointerProperties[MAX_POINTERS];
2330 PointerCoords splitPointerCoords[MAX_POINTERS];
2331
2332 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2333 uint32_t splitPointerCount = 0;
2334
2335 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2336 originalPointerIndex++) {
2337 const PointerProperties& pointerProperties =
2338 originalMotionEntry->pointerProperties[originalPointerIndex];
2339 uint32_t pointerId = uint32_t(pointerProperties.id);
2340 if (pointerIds.hasBit(pointerId)) {
2341 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2342 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2343 splitPointerCoords[splitPointerCount].copyFrom(
2344 originalMotionEntry->pointerCoords[originalPointerIndex]);
2345 splitPointerCount += 1;
2346 }
2347 }
2348
2349 if (splitPointerCount != pointerIds.count()) {
2350 // This is bad. We are missing some of the pointers that we expected to deliver.
2351 // Most likely this indicates that we received an ACTION_MOVE events that has
2352 // different pointer ids than we expected based on the previous ACTION_DOWN
2353 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2354 // in this way.
2355 ALOGW("Dropping split motion event because the pointer count is %d but "
2356 "we expected there to be %d pointers. This probably means we received "
2357 "a broken sequence of pointer ids from the input device.",
2358 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002359 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360 }
2361
2362 int32_t action = originalMotionEntry->action;
2363 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2364 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2365 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2366 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2367 const PointerProperties& pointerProperties =
2368 originalMotionEntry->pointerProperties[originalPointerIndex];
2369 uint32_t pointerId = uint32_t(pointerProperties.id);
2370 if (pointerIds.hasBit(pointerId)) {
2371 if (pointerIds.count() == 1) {
2372 // The first/last pointer went down/up.
2373 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2374 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2375 } else {
2376 // A secondary pointer went down/up.
2377 uint32_t splitPointerIndex = 0;
2378 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2379 splitPointerIndex += 1;
2380 }
2381 action = maskedAction | (splitPointerIndex
2382 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2383 }
2384 } else {
2385 // An unrelated pointer changed.
2386 action = AMOTION_EVENT_ACTION_MOVE;
2387 }
2388 }
2389
2390 MotionEntry* splitMotionEntry = new MotionEntry(
2391 originalMotionEntry->eventTime,
2392 originalMotionEntry->deviceId,
2393 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002394 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 originalMotionEntry->policyFlags,
2396 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002397 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 originalMotionEntry->flags,
2399 originalMotionEntry->metaState,
2400 originalMotionEntry->buttonState,
2401 originalMotionEntry->edgeFlags,
2402 originalMotionEntry->xPrecision,
2403 originalMotionEntry->yPrecision,
2404 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002405 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406
2407 if (originalMotionEntry->injectionState) {
2408 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2409 splitMotionEntry->injectionState->refCount += 1;
2410 }
2411
2412 return splitMotionEntry;
2413}
2414
2415void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2416#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002417 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418#endif
2419
2420 bool needWake;
2421 { // acquire lock
2422 AutoMutex _l(mLock);
2423
2424 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2425 needWake = enqueueInboundEventLocked(newEntry);
2426 } // release lock
2427
2428 if (needWake) {
2429 mLooper->wake();
2430 }
2431}
2432
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002433/**
2434 * If one of the meta shortcuts is detected, process them here:
2435 * Meta + Backspace -> generate BACK
2436 * Meta + Enter -> generate HOME
2437 * This will potentially overwrite keyCode and metaState.
2438 */
2439void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2440 int32_t& keyCode, int32_t& metaState) {
2441 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2442 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2443 if (keyCode == AKEYCODE_DEL) {
2444 newKeyCode = AKEYCODE_BACK;
2445 } else if (keyCode == AKEYCODE_ENTER) {
2446 newKeyCode = AKEYCODE_HOME;
2447 }
2448 if (newKeyCode != AKEYCODE_UNKNOWN) {
2449 AutoMutex _l(mLock);
2450 struct KeyReplacement replacement = {keyCode, deviceId};
2451 mReplacedKeys.add(replacement, newKeyCode);
2452 keyCode = newKeyCode;
2453 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2454 }
2455 } else if (action == AKEY_EVENT_ACTION_UP) {
2456 // In order to maintain a consistent stream of up and down events, check to see if the key
2457 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2458 // even if the modifier was released between the down and the up events.
2459 AutoMutex _l(mLock);
2460 struct KeyReplacement replacement = {keyCode, deviceId};
2461 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2462 if (index >= 0) {
2463 keyCode = mReplacedKeys.valueAt(index);
2464 mReplacedKeys.removeItemsAt(index);
2465 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2466 }
2467 }
2468}
2469
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2471#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002472 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002473 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002474 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002475 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 args->action, args->flags, args->keyCode, args->scanCode,
2477 args->metaState, args->downTime);
2478#endif
2479 if (!validateKeyEvent(args->action)) {
2480 return;
2481 }
2482
2483 uint32_t policyFlags = args->policyFlags;
2484 int32_t flags = args->flags;
2485 int32_t metaState = args->metaState;
2486 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2487 policyFlags |= POLICY_FLAG_VIRTUAL;
2488 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 if (policyFlags & POLICY_FLAG_FUNCTION) {
2491 metaState |= AMETA_FUNCTION_ON;
2492 }
2493
2494 policyFlags |= POLICY_FLAG_TRUSTED;
2495
Michael Wright78f24442014-08-06 15:55:28 -07002496 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002497 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002498
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002500 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Michael Wright78f24442014-08-06 15:55:28 -07002501 flags, keyCode, args->scanCode, metaState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502 args->downTime, args->eventTime);
2503
Michael Wright2b3c3302018-03-02 17:19:13 +00002504 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002506 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2507 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2508 std::to_string(t.duration().count()).c_str());
2509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 bool needWake;
2512 { // acquire lock
2513 mLock.lock();
2514
2515 if (shouldSendKeyToInputFilterLocked(args)) {
2516 mLock.unlock();
2517
2518 policyFlags |= POLICY_FLAG_FILTERED;
2519 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2520 return; // event was consumed by the filter
2521 }
2522
2523 mLock.lock();
2524 }
2525
2526 int32_t repeatCount = 0;
2527 KeyEntry* newEntry = new KeyEntry(args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002528 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002529 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 metaState, repeatCount, args->downTime);
2531
2532 needWake = enqueueInboundEventLocked(newEntry);
2533 mLock.unlock();
2534 } // release lock
2535
2536 if (needWake) {
2537 mLooper->wake();
2538 }
2539}
2540
2541bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2542 return mInputFilterEnabled;
2543}
2544
2545void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2546#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002547 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2548 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002549 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002550 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002551 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002552 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
2554 for (uint32_t i = 0; i < args->pointerCount; i++) {
2555 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2556 "x=%f, y=%f, pressure=%f, size=%f, "
2557 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2558 "orientation=%f",
2559 i, args->pointerProperties[i].id,
2560 args->pointerProperties[i].toolType,
2561 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2562 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2563 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2564 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2565 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2566 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2567 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2568 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2569 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2570 }
2571#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002572 if (!validateMotionEvent(args->action, args->actionButton,
2573 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574 return;
2575 }
2576
2577 uint32_t policyFlags = args->policyFlags;
2578 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002579
2580 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002582 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2583 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2584 std::to_string(t.duration().count()).c_str());
2585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586
2587 bool needWake;
2588 { // acquire lock
2589 mLock.lock();
2590
2591 if (shouldSendMotionToInputFilterLocked(args)) {
2592 mLock.unlock();
2593
2594 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002595 event.initialize(args->deviceId, args->source, args->displayId,
2596 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002597 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2598 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 args->downTime, args->eventTime,
2600 args->pointerCount, args->pointerProperties, args->pointerCoords);
2601
2602 policyFlags |= POLICY_FLAG_FILTERED;
2603 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2604 return; // event was consumed by the filter
2605 }
2606
2607 mLock.lock();
2608 }
2609
2610 // Just enqueue a new motion event.
2611 MotionEntry* newEntry = new MotionEntry(args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002612 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002613 args->action, args->actionButton, args->flags,
2614 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002616 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002617
2618 needWake = enqueueInboundEventLocked(newEntry);
2619 mLock.unlock();
2620 } // release lock
2621
2622 if (needWake) {
2623 mLooper->wake();
2624 }
2625}
2626
2627bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2628 // TODO: support sending secondary display events to input filter
2629 return mInputFilterEnabled && isMainDisplay(args->displayId);
2630}
2631
2632void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2633#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002634 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2635 "switchMask=0x%08x",
2636 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637#endif
2638
2639 uint32_t policyFlags = args->policyFlags;
2640 policyFlags |= POLICY_FLAG_TRUSTED;
2641 mPolicy->notifySwitch(args->eventTime,
2642 args->switchValues, args->switchMask, policyFlags);
2643}
2644
2645void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2646#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002647 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648 args->eventTime, args->deviceId);
2649#endif
2650
2651 bool needWake;
2652 { // acquire lock
2653 AutoMutex _l(mLock);
2654
2655 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2656 needWake = enqueueInboundEventLocked(newEntry);
2657 } // release lock
2658
2659 if (needWake) {
2660 mLooper->wake();
2661 }
2662}
2663
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002664int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2666 uint32_t policyFlags) {
2667#if DEBUG_INBOUND_EVENT_DETAILS
2668 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002669 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2670 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671#endif
2672
2673 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2674
2675 policyFlags |= POLICY_FLAG_INJECTED;
2676 if (hasInjectionPermission(injectorPid, injectorUid)) {
2677 policyFlags |= POLICY_FLAG_TRUSTED;
2678 }
2679
2680 EventEntry* firstInjectedEntry;
2681 EventEntry* lastInjectedEntry;
2682 switch (event->getType()) {
2683 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002684 KeyEvent keyEvent;
2685 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2686 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 if (! validateKeyEvent(action)) {
2688 return INPUT_EVENT_INJECTION_FAILED;
2689 }
2690
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002691 int32_t flags = keyEvent.getFlags();
2692 int32_t keyCode = keyEvent.getKeyCode();
2693 int32_t metaState = keyEvent.getMetaState();
2694 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2695 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002696 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
2697 action, flags, keyCode, keyEvent.getScanCode(), metaState, 0,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002698 keyEvent.getDownTime(), keyEvent.getEventTime());
2699
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2701 policyFlags |= POLICY_FLAG_VIRTUAL;
2702 }
2703
2704 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002705 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002706 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002707 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2708 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2709 std::to_string(t.duration().count()).c_str());
2710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 }
2712
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 mLock.lock();
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002714 firstInjectedEntry = new KeyEntry(keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002715 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002717 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2718 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719 lastInjectedEntry = firstInjectedEntry;
2720 break;
2721 }
2722
2723 case AINPUT_EVENT_TYPE_MOTION: {
2724 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725 int32_t action = motionEvent->getAction();
2726 size_t pointerCount = motionEvent->getPointerCount();
2727 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002728 int32_t actionButton = motionEvent->getActionButton();
2729 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 return INPUT_EVENT_INJECTION_FAILED;
2731 }
2732
2733 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2734 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002735 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002737 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2738 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2739 std::to_string(t.duration().count()).c_str());
2740 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741 }
2742
2743 mLock.lock();
2744 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2745 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2746 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002747 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2748 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002749 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 motionEvent->getMetaState(), motionEvent->getButtonState(),
2751 motionEvent->getEdgeFlags(),
2752 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002753 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002754 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2755 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756 lastInjectedEntry = firstInjectedEntry;
2757 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2758 sampleEventTimes += 1;
2759 samplePointerCoords += pointerCount;
2760 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002761 motionEvent->getDeviceId(), motionEvent->getSource(),
2762 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002763 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764 motionEvent->getMetaState(), motionEvent->getButtonState(),
2765 motionEvent->getEdgeFlags(),
2766 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002767 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002768 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2769 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770 lastInjectedEntry->next = nextInjectedEntry;
2771 lastInjectedEntry = nextInjectedEntry;
2772 }
2773 break;
2774 }
2775
2776 default:
2777 ALOGW("Cannot inject event of type %d", event->getType());
2778 return INPUT_EVENT_INJECTION_FAILED;
2779 }
2780
2781 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2782 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2783 injectionState->injectionIsAsync = true;
2784 }
2785
2786 injectionState->refCount += 1;
2787 lastInjectedEntry->injectionState = injectionState;
2788
2789 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002790 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791 EventEntry* nextEntry = entry->next;
2792 needWake |= enqueueInboundEventLocked(entry);
2793 entry = nextEntry;
2794 }
2795
2796 mLock.unlock();
2797
2798 if (needWake) {
2799 mLooper->wake();
2800 }
2801
2802 int32_t injectionResult;
2803 { // acquire lock
2804 AutoMutex _l(mLock);
2805
2806 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2807 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2808 } else {
2809 for (;;) {
2810 injectionResult = injectionState->injectionResult;
2811 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2812 break;
2813 }
2814
2815 nsecs_t remainingTimeout = endTime - now();
2816 if (remainingTimeout <= 0) {
2817#if DEBUG_INJECTION
2818 ALOGD("injectInputEvent - Timed out waiting for injection result "
2819 "to become available.");
2820#endif
2821 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2822 break;
2823 }
2824
2825 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2826 }
2827
2828 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2829 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2830 while (injectionState->pendingForegroundDispatches != 0) {
2831#if DEBUG_INJECTION
2832 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2833 injectionState->pendingForegroundDispatches);
2834#endif
2835 nsecs_t remainingTimeout = endTime - now();
2836 if (remainingTimeout <= 0) {
2837#if DEBUG_INJECTION
2838 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2839 "dispatches to finish.");
2840#endif
2841 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2842 break;
2843 }
2844
2845 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2846 }
2847 }
2848 }
2849
2850 injectionState->release();
2851 } // release lock
2852
2853#if DEBUG_INJECTION
2854 ALOGD("injectInputEvent - Finished with result %d. "
2855 "injectorPid=%d, injectorUid=%d",
2856 injectionResult, injectorPid, injectorUid);
2857#endif
2858
2859 return injectionResult;
2860}
2861
2862bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2863 return injectorUid == 0
2864 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2865}
2866
2867void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2868 InjectionState* injectionState = entry->injectionState;
2869 if (injectionState) {
2870#if DEBUG_INJECTION
2871 ALOGD("Setting input event injection result to %d. "
2872 "injectorPid=%d, injectorUid=%d",
2873 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2874#endif
2875
2876 if (injectionState->injectionIsAsync
2877 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2878 // Log the outcome since the injector did not wait for the injection result.
2879 switch (injectionResult) {
2880 case INPUT_EVENT_INJECTION_SUCCEEDED:
2881 ALOGV("Asynchronous input event injection succeeded.");
2882 break;
2883 case INPUT_EVENT_INJECTION_FAILED:
2884 ALOGW("Asynchronous input event injection failed.");
2885 break;
2886 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2887 ALOGW("Asynchronous input event injection permission denied.");
2888 break;
2889 case INPUT_EVENT_INJECTION_TIMED_OUT:
2890 ALOGW("Asynchronous input event injection timed out.");
2891 break;
2892 }
2893 }
2894
2895 injectionState->injectionResult = injectionResult;
2896 mInjectionResultAvailableCondition.broadcast();
2897 }
2898}
2899
2900void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2901 InjectionState* injectionState = entry->injectionState;
2902 if (injectionState) {
2903 injectionState->pendingForegroundDispatches += 1;
2904 }
2905}
2906
2907void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2908 InjectionState* injectionState = entry->injectionState;
2909 if (injectionState) {
2910 injectionState->pendingForegroundDispatches -= 1;
2911
2912 if (injectionState->pendingForegroundDispatches == 0) {
2913 mInjectionSyncFinishedCondition.broadcast();
2914 }
2915 }
2916}
2917
Arthur Hungb92218b2018-08-14 12:00:21 +08002918Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
2919 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
2920 mWindowHandlesByDisplay.find(displayId);
2921 if(it != mWindowHandlesByDisplay.end()) {
2922 return it->second;
2923 }
2924
2925 // Return an empty one if nothing found.
2926 return Vector<sp<InputWindowHandle>>();
2927}
2928
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
2930 const sp<InputChannel>& inputChannel) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08002931 for (auto& it : mWindowHandlesByDisplay) {
2932 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
2933 size_t numWindows = windowHandles.size();
2934 for (size_t i = 0; i < numWindows; i++) {
2935 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
2936 if (windowHandle->getInputChannel() == inputChannel) {
2937 return windowHandle;
2938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939 }
2940 }
Yi Kong9b14ac62018-07-17 13:48:38 -07002941 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942}
2943
2944bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00002945 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08002946 for (auto& it : mWindowHandlesByDisplay) {
2947 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
2948 size_t numWindows = windowHandles.size();
2949 for (size_t i = 0; i < numWindows; i++) {
2950 if (windowHandles.itemAt(i) == windowHandle) {
2951 if (windowHandle->getInfo()->displayId != it.first) {
2952 ALOGE("Found window %s in display %d, but it should belong to display %d",
2953 windowHandle->getName().c_str(), it.first,
2954 windowHandle->getInfo()->displayId);
2955 }
2956 return true;
2957 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002958 }
2959 }
2960 return false;
2961}
2962
Arthur Hungb92218b2018-08-14 12:00:21 +08002963/**
2964 * Called from InputManagerService, update window handle list by displayId that can receive input.
2965 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
2966 * If set an empty list, remove all handles from the specific display.
2967 * For focused handle, check if need to change and send a cancel event to previous one.
2968 * For removed handle, check if need to send a cancel event if already in touch.
2969 */
2970void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
2971 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972#if DEBUG_FOCUS
2973 ALOGD("setInputWindows");
2974#endif
2975 { // acquire lock
2976 AutoMutex _l(mLock);
2977
Arthur Hungb92218b2018-08-14 12:00:21 +08002978 // Copy old handles for release if they are no longer present.
2979 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980
Arthur Hungb92218b2018-08-14 12:00:21 +08002981 // TODO(b/111361570): multi-display focus, one focus window per display.
2982 sp<InputWindowHandle> newFocusedWindowHandle = mFocusedWindowHandle;
2983 // Reset newFocusedWindowHandle to nullptr if current display own the focus window,
2984 // that will be updated below when going through all window handles in current display.
2985 // And if list of window handles becomes empty then it will be updated by other display.
2986 if (mFocusedWindowHandle != nullptr) {
2987 const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
2988 if (info == nullptr || info->displayId == displayId) {
2989 newFocusedWindowHandle = nullptr;
2990 }
2991 }
2992
Michael Wrightd02c5b62014-02-10 15:10:22 -08002993 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08002994
2995 if (inputWindowHandles.isEmpty()) {
2996 // Remove all handles on a display if there are no windows left.
2997 mWindowHandlesByDisplay.erase(displayId);
2998 } else {
2999 size_t numWindows = inputWindowHandles.size();
3000 for (size_t i = 0; i < numWindows; i++) {
3001 const sp<InputWindowHandle>& windowHandle = inputWindowHandles.itemAt(i);
3002 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == nullptr) {
3003 continue;
3004 }
3005
3006 if (windowHandle->getInfo()->displayId != displayId) {
3007 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3008 windowHandle->getName().c_str(), displayId,
3009 windowHandle->getInfo()->displayId);
3010 continue;
3011 }
3012
3013 if (windowHandle->getInfo()->hasFocus) {
3014 newFocusedWindowHandle = windowHandle;
3015 }
3016 if (windowHandle == mLastHoverWindowHandle) {
3017 foundHoveredWindow = true;
3018 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003019 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003020
3021 // Insert or replace
3022 mWindowHandlesByDisplay[displayId] = inputWindowHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 }
3024
3025 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003026 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027 }
3028
Arthur Hungb92218b2018-08-14 12:00:21 +08003029 // TODO(b/111361570): multi-display focus, one focus in all display in current.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030 if (mFocusedWindowHandle != newFocusedWindowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003031 if (mFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032#if DEBUG_FOCUS
3033 ALOGD("Focus left window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003034 mFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003035#endif
3036 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
Yi Kong9b14ac62018-07-17 13:48:38 -07003037 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3039 "focus left window");
3040 synthesizeCancelationEventsForInputChannelLocked(
3041 focusedInputChannel, options);
3042 }
3043 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003044 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045#if DEBUG_FOCUS
3046 ALOGD("Focus entered window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003047 newFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048#endif
3049 }
3050 mFocusedWindowHandle = newFocusedWindowHandle;
3051 }
3052
Arthur Hungb92218b2018-08-14 12:00:21 +08003053 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3054 if (stateIndex >= 0) {
3055 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003056 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003057 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003058 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003059#if DEBUG_FOCUS
Jeff Brownf086ddb2014-02-11 14:28:48 -08003060 ALOGD("Touched window was removed: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003061 touchedWindow.windowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003063 sp<InputChannel> touchedInputChannel =
3064 touchedWindow.windowHandle->getInputChannel();
Yi Kong9b14ac62018-07-17 13:48:38 -07003065 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003066 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3067 "touched window was removed");
3068 synthesizeCancelationEventsForInputChannelLocked(
3069 touchedInputChannel, options);
3070 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003071 state.windows.removeAt(i);
3072 } else {
3073 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075 }
3076 }
3077
3078 // Release information for windows that are no longer present.
3079 // This ensures that unused input channels are released promptly.
3080 // Otherwise, they might stick around until the window handle is destroyed
3081 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003082 size_t numWindows = oldWindowHandles.size();
3083 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003085 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003087 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088#endif
3089 oldWindowHandle->releaseInfo();
3090 }
3091 }
3092 } // release lock
3093
3094 // Wake up poll loop since it may need to make new input dispatching choices.
3095 mLooper->wake();
3096}
3097
3098void InputDispatcher::setFocusedApplication(
3099 const sp<InputApplicationHandle>& inputApplicationHandle) {
3100#if DEBUG_FOCUS
3101 ALOGD("setFocusedApplication");
3102#endif
3103 { // acquire lock
3104 AutoMutex _l(mLock);
3105
Yi Kong9b14ac62018-07-17 13:48:38 -07003106 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 if (mFocusedApplicationHandle != inputApplicationHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003108 if (mFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 resetANRTimeoutsLocked();
3110 mFocusedApplicationHandle->releaseInfo();
3111 }
3112 mFocusedApplicationHandle = inputApplicationHandle;
3113 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003114 } else if (mFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 resetANRTimeoutsLocked();
3116 mFocusedApplicationHandle->releaseInfo();
3117 mFocusedApplicationHandle.clear();
3118 }
3119
3120#if DEBUG_FOCUS
3121 //logDispatchStateLocked();
3122#endif
3123 } // release lock
3124
3125 // Wake up poll loop since it may need to make new input dispatching choices.
3126 mLooper->wake();
3127}
3128
3129void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3130#if DEBUG_FOCUS
3131 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3132#endif
3133
3134 bool changed;
3135 { // acquire lock
3136 AutoMutex _l(mLock);
3137
3138 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3139 if (mDispatchFrozen && !frozen) {
3140 resetANRTimeoutsLocked();
3141 }
3142
3143 if (mDispatchEnabled && !enabled) {
3144 resetAndDropEverythingLocked("dispatcher is being disabled");
3145 }
3146
3147 mDispatchEnabled = enabled;
3148 mDispatchFrozen = frozen;
3149 changed = true;
3150 } else {
3151 changed = false;
3152 }
3153
3154#if DEBUG_FOCUS
3155 //logDispatchStateLocked();
3156#endif
3157 } // release lock
3158
3159 if (changed) {
3160 // Wake up poll loop since it may need to make new input dispatching choices.
3161 mLooper->wake();
3162 }
3163}
3164
3165void InputDispatcher::setInputFilterEnabled(bool enabled) {
3166#if DEBUG_FOCUS
3167 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3168#endif
3169
3170 { // acquire lock
3171 AutoMutex _l(mLock);
3172
3173 if (mInputFilterEnabled == enabled) {
3174 return;
3175 }
3176
3177 mInputFilterEnabled = enabled;
3178 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3179 } // release lock
3180
3181 // Wake up poll loop since there might be work to do to drop everything.
3182 mLooper->wake();
3183}
3184
3185bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3186 const sp<InputChannel>& toChannel) {
3187#if DEBUG_FOCUS
3188 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003189 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190#endif
3191 { // acquire lock
3192 AutoMutex _l(mLock);
3193
3194 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3195 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07003196 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197#if DEBUG_FOCUS
3198 ALOGD("Cannot transfer focus because from or to window not found.");
3199#endif
3200 return false;
3201 }
3202 if (fromWindowHandle == toWindowHandle) {
3203#if DEBUG_FOCUS
3204 ALOGD("Trivial transfer to same window.");
3205#endif
3206 return true;
3207 }
3208 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3209#if DEBUG_FOCUS
3210 ALOGD("Cannot transfer focus because windows are on different displays.");
3211#endif
3212 return false;
3213 }
3214
3215 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003216 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3217 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3218 for (size_t i = 0; i < state.windows.size(); i++) {
3219 const TouchedWindow& touchedWindow = state.windows[i];
3220 if (touchedWindow.windowHandle == fromWindowHandle) {
3221 int32_t oldTargetFlags = touchedWindow.targetFlags;
3222 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223
Jeff Brownf086ddb2014-02-11 14:28:48 -08003224 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225
Jeff Brownf086ddb2014-02-11 14:28:48 -08003226 int32_t newTargetFlags = oldTargetFlags
3227 & (InputTarget::FLAG_FOREGROUND
3228 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3229 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230
Jeff Brownf086ddb2014-02-11 14:28:48 -08003231 found = true;
3232 goto Found;
3233 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234 }
3235 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003236Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237
3238 if (! found) {
3239#if DEBUG_FOCUS
3240 ALOGD("Focus transfer failed because from window did not have focus.");
3241#endif
3242 return false;
3243 }
3244
3245 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3246 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3247 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3248 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3249 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3250
3251 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3252 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3253 "transferring touch focus from this window to another window");
3254 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3255 }
3256
3257#if DEBUG_FOCUS
3258 logDispatchStateLocked();
3259#endif
3260 } // release lock
3261
3262 // Wake up poll loop since it may need to make new input dispatching choices.
3263 mLooper->wake();
3264 return true;
3265}
3266
3267void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3268#if DEBUG_FOCUS
3269 ALOGD("Resetting and dropping all events (%s).", reason);
3270#endif
3271
3272 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3273 synthesizeCancelationEventsForAllConnectionsLocked(options);
3274
3275 resetKeyRepeatLocked();
3276 releasePendingEventLocked();
3277 drainInboundQueueLocked();
3278 resetANRTimeoutsLocked();
3279
Jeff Brownf086ddb2014-02-11 14:28:48 -08003280 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003282 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283}
3284
3285void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003286 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003287 dumpDispatchStateLocked(dump);
3288
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003289 std::istringstream stream(dump);
3290 std::string line;
3291
3292 while (std::getline(stream, line, '\n')) {
3293 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294 }
3295}
3296
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003297void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3298 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3299 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300
Yi Kong9b14ac62018-07-17 13:48:38 -07003301 if (mFocusedApplicationHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003302 dump += StringPrintf(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
3303 mFocusedApplicationHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003304 mFocusedApplicationHandle->getDispatchingTimeout(
3305 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3306 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003307 dump += StringPrintf(INDENT "FocusedApplication: <null>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003309 dump += StringPrintf(INDENT "FocusedWindow: name='%s'\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07003310 mFocusedWindowHandle != nullptr ? mFocusedWindowHandle->getName().c_str() : "<null>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311
Jeff Brownf086ddb2014-02-11 14:28:48 -08003312 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003313 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003314 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3315 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003316 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003317 state.displayId, toString(state.down), toString(state.split),
3318 state.deviceId, state.source);
3319 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003320 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003321 for (size_t i = 0; i < state.windows.size(); i++) {
3322 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003323 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3324 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003325 touchedWindow.pointerIds.value,
3326 touchedWindow.targetFlags);
3327 }
3328 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003329 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003330 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331 }
3332 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003333 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334 }
3335
Arthur Hungb92218b2018-08-14 12:00:21 +08003336 if (!mWindowHandlesByDisplay.empty()) {
3337 for (auto& it : mWindowHandlesByDisplay) {
3338 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3339 dump += StringPrintf(INDENT "Display: %d\n", it.first);
3340 if (!windowHandles.isEmpty()) {
3341 dump += INDENT2 "Windows:\n";
3342 for (size_t i = 0; i < windowHandles.size(); i++) {
3343 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3344 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345
Arthur Hungb92218b2018-08-14 12:00:21 +08003346 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3347 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3348 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3349 "frame=[%d,%d][%d,%d], scale=%f, "
3350 "touchableRegion=",
3351 i, windowInfo->name.c_str(), windowInfo->displayId,
3352 toString(windowInfo->paused),
3353 toString(windowInfo->hasFocus),
3354 toString(windowInfo->hasWallpaper),
3355 toString(windowInfo->visible),
3356 toString(windowInfo->canReceiveKeys),
3357 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3358 windowInfo->layer,
3359 windowInfo->frameLeft, windowInfo->frameTop,
3360 windowInfo->frameRight, windowInfo->frameBottom,
3361 windowInfo->scaleFactor);
3362 dumpRegion(dump, windowInfo->touchableRegion);
3363 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3364 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3365 windowInfo->ownerPid, windowInfo->ownerUid,
3366 windowInfo->dispatchingTimeout / 1000000.0);
3367 }
3368 } else {
3369 dump += INDENT2 "Windows: <none>\n";
3370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 }
3372 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003373 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 }
3375
3376 if (!mMonitoringChannels.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003377 dump += INDENT "MonitoringChannels:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3379 const sp<InputChannel>& channel = mMonitoringChannels[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003380 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 }
3382 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003383 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 }
3385
3386 nsecs_t currentTime = now();
3387
3388 // Dump recently dispatched or dropped events from oldest to newest.
3389 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003390 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003392 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003394 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 (currentTime - entry->eventTime) * 0.000001f);
3396 }
3397 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003398 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 }
3400
3401 // Dump event currently being dispatched.
3402 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003403 dump += INDENT "PendingEvent:\n";
3404 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003406 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3408 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003409 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 }
3411
3412 // Dump inbound events from oldest to newest.
3413 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003414 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003416 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003418 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 (currentTime - entry->eventTime) * 0.000001f);
3420 }
3421 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003422 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 }
3424
Michael Wright78f24442014-08-06 15:55:28 -07003425 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003426 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003427 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3428 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3429 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003430 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003431 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3432 }
3433 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003434 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003435 }
3436
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003438 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3440 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003441 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003443 i, connection->getInputChannelName().c_str(),
3444 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445 connection->getStatusLabel(), toString(connection->monitor),
3446 toString(connection->inputPublisherBlocked));
3447
3448 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003449 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 connection->outboundQueue.count());
3451 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3452 entry = entry->next) {
3453 dump.append(INDENT4);
3454 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003455 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456 entry->targetFlags, entry->resolvedAction,
3457 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3458 }
3459 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003460 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461 }
3462
3463 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003464 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465 connection->waitQueue.count());
3466 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3467 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003468 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003470 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 "age=%0.1fms, wait=%0.1fms\n",
3472 entry->targetFlags, entry->resolvedAction,
3473 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3474 (currentTime - entry->deliveryTime) * 0.000001f);
3475 }
3476 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003477 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478 }
3479 }
3480 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003481 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482 }
3483
3484 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003485 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 (mAppSwitchDueTime - now()) / 1000000.0);
3487 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003488 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489 }
3490
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003491 dump += INDENT "Configuration:\n";
3492 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003494 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495 mConfig.keyRepeatTimeout * 0.000001f);
3496}
3497
3498status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3499 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
3500#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003501 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 toString(monitor));
3503#endif
3504
3505 { // acquire lock
3506 AutoMutex _l(mLock);
3507
3508 if (getConnectionIndexLocked(inputChannel) >= 0) {
3509 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003510 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 return BAD_VALUE;
3512 }
3513
3514 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3515
3516 int fd = inputChannel->getFd();
3517 mConnectionsByFd.add(fd, connection);
3518
3519 if (monitor) {
3520 mMonitoringChannels.push(inputChannel);
3521 }
3522
3523 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3524 } // release lock
3525
3526 // Wake the looper because some connections have changed.
3527 mLooper->wake();
3528 return OK;
3529}
3530
3531status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3532#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003533 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534#endif
3535
3536 { // acquire lock
3537 AutoMutex _l(mLock);
3538
3539 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3540 if (status) {
3541 return status;
3542 }
3543 } // release lock
3544
3545 // Wake the poll loop because removing the connection may have changed the current
3546 // synchronization state.
3547 mLooper->wake();
3548 return OK;
3549}
3550
3551status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3552 bool notify) {
3553 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3554 if (connectionIndex < 0) {
3555 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003556 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 return BAD_VALUE;
3558 }
3559
3560 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3561 mConnectionsByFd.removeItemsAt(connectionIndex);
3562
3563 if (connection->monitor) {
3564 removeMonitorChannelLocked(inputChannel);
3565 }
3566
3567 mLooper->removeFd(inputChannel->getFd());
3568
3569 nsecs_t currentTime = now();
3570 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3571
3572 connection->status = Connection::STATUS_ZOMBIE;
3573 return OK;
3574}
3575
3576void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3577 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3578 if (mMonitoringChannels[i] == inputChannel) {
3579 mMonitoringChannels.removeAt(i);
3580 break;
3581 }
3582 }
3583}
3584
3585ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
3586 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3587 if (connectionIndex >= 0) {
3588 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3589 if (connection->inputChannel.get() == inputChannel.get()) {
3590 return connectionIndex;
3591 }
3592 }
3593
3594 return -1;
3595}
3596
3597void InputDispatcher::onDispatchCycleFinishedLocked(
3598 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3599 CommandEntry* commandEntry = postCommandLocked(
3600 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3601 commandEntry->connection = connection;
3602 commandEntry->eventTime = currentTime;
3603 commandEntry->seq = seq;
3604 commandEntry->handled = handled;
3605}
3606
3607void InputDispatcher::onDispatchCycleBrokenLocked(
3608 nsecs_t currentTime, const sp<Connection>& connection) {
3609 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003610 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611
3612 CommandEntry* commandEntry = postCommandLocked(
3613 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3614 commandEntry->connection = connection;
3615}
3616
3617void InputDispatcher::onANRLocked(
3618 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3619 const sp<InputWindowHandle>& windowHandle,
3620 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3621 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3622 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3623 ALOGI("Application is not responding: %s. "
3624 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003625 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 dispatchLatency, waitDuration, reason);
3627
3628 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003629 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 struct tm tm;
3631 localtime_r(&t, &tm);
3632 char timestr[64];
3633 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3634 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003635 mLastANRState += INDENT "ANR:\n";
3636 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3637 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3638 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3639 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3640 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3641 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 dumpDispatchStateLocked(mLastANRState);
3643
3644 CommandEntry* commandEntry = postCommandLocked(
3645 & InputDispatcher::doNotifyANRLockedInterruptible);
3646 commandEntry->inputApplicationHandle = applicationHandle;
3647 commandEntry->inputWindowHandle = windowHandle;
3648 commandEntry->reason = reason;
3649}
3650
3651void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3652 CommandEntry* commandEntry) {
3653 mLock.unlock();
3654
3655 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3656
3657 mLock.lock();
3658}
3659
3660void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3661 CommandEntry* commandEntry) {
3662 sp<Connection> connection = commandEntry->connection;
3663
3664 if (connection->status != Connection::STATUS_ZOMBIE) {
3665 mLock.unlock();
3666
3667 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3668
3669 mLock.lock();
3670 }
3671}
3672
3673void InputDispatcher::doNotifyANRLockedInterruptible(
3674 CommandEntry* commandEntry) {
3675 mLock.unlock();
3676
3677 nsecs_t newTimeout = mPolicy->notifyANR(
3678 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3679 commandEntry->reason);
3680
3681 mLock.lock();
3682
3683 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Yi Kong9b14ac62018-07-17 13:48:38 -07003684 commandEntry->inputWindowHandle != nullptr
3685 ? commandEntry->inputWindowHandle->getInputChannel() : nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686}
3687
3688void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3689 CommandEntry* commandEntry) {
3690 KeyEntry* entry = commandEntry->keyEntry;
3691
3692 KeyEvent event;
3693 initializeKeyEvent(&event, entry);
3694
3695 mLock.unlock();
3696
Michael Wright2b3c3302018-03-02 17:19:13 +00003697 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3699 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003700 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3701 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3702 std::to_string(t.duration().count()).c_str());
3703 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704
3705 mLock.lock();
3706
3707 if (delay < 0) {
3708 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3709 } else if (!delay) {
3710 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3711 } else {
3712 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3713 entry->interceptKeyWakeupTime = now() + delay;
3714 }
3715 entry->release();
3716}
3717
3718void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3719 CommandEntry* commandEntry) {
3720 sp<Connection> connection = commandEntry->connection;
3721 nsecs_t finishTime = commandEntry->eventTime;
3722 uint32_t seq = commandEntry->seq;
3723 bool handled = commandEntry->handled;
3724
3725 // Handle post-event policy actions.
3726 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3727 if (dispatchEntry) {
3728 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3729 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003730 std::string msg =
3731 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003732 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003734 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735 }
3736
3737 bool restartEvent;
3738 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3739 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3740 restartEvent = afterKeyEventLockedInterruptible(connection,
3741 dispatchEntry, keyEntry, handled);
3742 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3743 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3744 restartEvent = afterMotionEventLockedInterruptible(connection,
3745 dispatchEntry, motionEntry, handled);
3746 } else {
3747 restartEvent = false;
3748 }
3749
3750 // Dequeue the event and start the next cycle.
3751 // Note that because the lock might have been released, it is possible that the
3752 // contents of the wait queue to have been drained, so we need to double-check
3753 // a few things.
3754 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3755 connection->waitQueue.dequeue(dispatchEntry);
3756 traceWaitQueueLengthLocked(connection);
3757 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3758 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3759 traceOutboundQueueLengthLocked(connection);
3760 } else {
3761 releaseDispatchEntryLocked(dispatchEntry);
3762 }
3763 }
3764
3765 // Start the next dispatch cycle for this connection.
3766 startDispatchCycleLocked(now(), connection);
3767 }
3768}
3769
3770bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3771 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3772 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3773 // Get the fallback key state.
3774 // Clear it out after dispatching the UP.
3775 int32_t originalKeyCode = keyEntry->keyCode;
3776 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3777 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3778 connection->inputState.removeFallbackKey(originalKeyCode);
3779 }
3780
3781 if (handled || !dispatchEntry->hasForegroundTarget()) {
3782 // If the application handles the original key for which we previously
3783 // generated a fallback or if the window is not a foreground window,
3784 // then cancel the associated fallback key, if any.
3785 if (fallbackKeyCode != -1) {
3786 // Dispatch the unhandled key to the policy with the cancel flag.
3787#if DEBUG_OUTBOUND_EVENT_DETAILS
3788 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3789 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3790 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3791 keyEntry->policyFlags);
3792#endif
3793 KeyEvent event;
3794 initializeKeyEvent(&event, keyEntry);
3795 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3796
3797 mLock.unlock();
3798
3799 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3800 &event, keyEntry->policyFlags, &event);
3801
3802 mLock.lock();
3803
3804 // Cancel the fallback key.
3805 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3806 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3807 "application handled the original non-fallback key "
3808 "or is no longer a foreground target, "
3809 "canceling previously dispatched fallback key");
3810 options.keyCode = fallbackKeyCode;
3811 synthesizeCancelationEventsForConnectionLocked(connection, options);
3812 }
3813 connection->inputState.removeFallbackKey(originalKeyCode);
3814 }
3815 } else {
3816 // If the application did not handle a non-fallback key, first check
3817 // that we are in a good state to perform unhandled key event processing
3818 // Then ask the policy what to do with it.
3819 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3820 && keyEntry->repeatCount == 0;
3821 if (fallbackKeyCode == -1 && !initialDown) {
3822#if DEBUG_OUTBOUND_EVENT_DETAILS
3823 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3824 "since this is not an initial down. "
3825 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3826 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3827 keyEntry->policyFlags);
3828#endif
3829 return false;
3830 }
3831
3832 // Dispatch the unhandled key to the policy.
3833#if DEBUG_OUTBOUND_EVENT_DETAILS
3834 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
3835 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3836 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3837 keyEntry->policyFlags);
3838#endif
3839 KeyEvent event;
3840 initializeKeyEvent(&event, keyEntry);
3841
3842 mLock.unlock();
3843
3844 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3845 &event, keyEntry->policyFlags, &event);
3846
3847 mLock.lock();
3848
3849 if (connection->status != Connection::STATUS_NORMAL) {
3850 connection->inputState.removeFallbackKey(originalKeyCode);
3851 return false;
3852 }
3853
3854 // Latch the fallback keycode for this key on an initial down.
3855 // The fallback keycode cannot change at any other point in the lifecycle.
3856 if (initialDown) {
3857 if (fallback) {
3858 fallbackKeyCode = event.getKeyCode();
3859 } else {
3860 fallbackKeyCode = AKEYCODE_UNKNOWN;
3861 }
3862 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3863 }
3864
3865 ALOG_ASSERT(fallbackKeyCode != -1);
3866
3867 // Cancel the fallback key if the policy decides not to send it anymore.
3868 // We will continue to dispatch the key to the policy but we will no
3869 // longer dispatch a fallback key to the application.
3870 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3871 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3872#if DEBUG_OUTBOUND_EVENT_DETAILS
3873 if (fallback) {
3874 ALOGD("Unhandled key event: Policy requested to send key %d"
3875 "as a fallback for %d, but on the DOWN it had requested "
3876 "to send %d instead. Fallback canceled.",
3877 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3878 } else {
3879 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
3880 "but on the DOWN it had requested to send %d. "
3881 "Fallback canceled.",
3882 originalKeyCode, fallbackKeyCode);
3883 }
3884#endif
3885
3886 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3887 "canceling fallback, policy no longer desires it");
3888 options.keyCode = fallbackKeyCode;
3889 synthesizeCancelationEventsForConnectionLocked(connection, options);
3890
3891 fallback = false;
3892 fallbackKeyCode = AKEYCODE_UNKNOWN;
3893 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3894 connection->inputState.setFallbackKey(originalKeyCode,
3895 fallbackKeyCode);
3896 }
3897 }
3898
3899#if DEBUG_OUTBOUND_EVENT_DETAILS
3900 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003901 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3903 connection->inputState.getFallbackKeys();
3904 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003905 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906 fallbackKeys.valueAt(i));
3907 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003908 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003909 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 }
3911#endif
3912
3913 if (fallback) {
3914 // Restart the dispatch cycle using the fallback key.
3915 keyEntry->eventTime = event.getEventTime();
3916 keyEntry->deviceId = event.getDeviceId();
3917 keyEntry->source = event.getSource();
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01003918 keyEntry->displayId = event.getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3920 keyEntry->keyCode = fallbackKeyCode;
3921 keyEntry->scanCode = event.getScanCode();
3922 keyEntry->metaState = event.getMetaState();
3923 keyEntry->repeatCount = event.getRepeatCount();
3924 keyEntry->downTime = event.getDownTime();
3925 keyEntry->syntheticRepeat = false;
3926
3927#if DEBUG_OUTBOUND_EVENT_DETAILS
3928 ALOGD("Unhandled key event: Dispatching fallback key. "
3929 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3930 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3931#endif
3932 return true; // restart the event
3933 } else {
3934#if DEBUG_OUTBOUND_EVENT_DETAILS
3935 ALOGD("Unhandled key event: No fallback key.");
3936#endif
3937 }
3938 }
3939 }
3940 return false;
3941}
3942
3943bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3944 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3945 return false;
3946}
3947
3948void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3949 mLock.unlock();
3950
3951 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
3952
3953 mLock.lock();
3954}
3955
3956void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01003957 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3959 entry->downTime, entry->eventTime);
3960}
3961
3962void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3963 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3964 // TODO Write some statistics about how long we spend waiting.
3965}
3966
3967void InputDispatcher::traceInboundQueueLengthLocked() {
3968 if (ATRACE_ENABLED()) {
3969 ATRACE_INT("iq", mInboundQueue.count());
3970 }
3971}
3972
3973void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3974 if (ATRACE_ENABLED()) {
3975 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003976 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 ATRACE_INT(counterName, connection->outboundQueue.count());
3978 }
3979}
3980
3981void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3982 if (ATRACE_ENABLED()) {
3983 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003984 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985 ATRACE_INT(counterName, connection->waitQueue.count());
3986 }
3987}
3988
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003989void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 AutoMutex _l(mLock);
3991
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003992 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 dumpDispatchStateLocked(dump);
3994
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003995 if (!mLastANRState.empty()) {
3996 dump += "\nInput Dispatcher State at time of last ANR:\n";
3997 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998 }
3999}
4000
4001void InputDispatcher::monitor() {
4002 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4003 mLock.lock();
4004 mLooper->wake();
4005 mDispatcherIsAliveCondition.wait(mLock);
4006 mLock.unlock();
4007}
4008
4009
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010// --- InputDispatcher::InjectionState ---
4011
4012InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4013 refCount(1),
4014 injectorPid(injectorPid), injectorUid(injectorUid),
4015 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4016 pendingForegroundDispatches(0) {
4017}
4018
4019InputDispatcher::InjectionState::~InjectionState() {
4020}
4021
4022void InputDispatcher::InjectionState::release() {
4023 refCount -= 1;
4024 if (refCount == 0) {
4025 delete this;
4026 } else {
4027 ALOG_ASSERT(refCount > 0);
4028 }
4029}
4030
4031
4032// --- InputDispatcher::EventEntry ---
4033
4034InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4035 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
Yi Kong9b14ac62018-07-17 13:48:38 -07004036 injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037}
4038
4039InputDispatcher::EventEntry::~EventEntry() {
4040 releaseInjectionState();
4041}
4042
4043void InputDispatcher::EventEntry::release() {
4044 refCount -= 1;
4045 if (refCount == 0) {
4046 delete this;
4047 } else {
4048 ALOG_ASSERT(refCount > 0);
4049 }
4050}
4051
4052void InputDispatcher::EventEntry::releaseInjectionState() {
4053 if (injectionState) {
4054 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004055 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 }
4057}
4058
4059
4060// --- InputDispatcher::ConfigurationChangedEntry ---
4061
4062InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4063 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4064}
4065
4066InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4067}
4068
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004069void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4070 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071}
4072
4073
4074// --- InputDispatcher::DeviceResetEntry ---
4075
4076InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4077 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4078 deviceId(deviceId) {
4079}
4080
4081InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4082}
4083
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004084void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4085 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086 deviceId, policyFlags);
4087}
4088
4089
4090// --- InputDispatcher::KeyEntry ---
4091
4092InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004093 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4095 int32_t repeatCount, nsecs_t downTime) :
4096 EventEntry(TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004097 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4099 repeatCount(repeatCount), downTime(downTime),
4100 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4101 interceptKeyWakeupTime(0) {
4102}
4103
4104InputDispatcher::KeyEntry::~KeyEntry() {
4105}
4106
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004107void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004108 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4110 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004111 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004112 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113}
4114
4115void InputDispatcher::KeyEntry::recycle() {
4116 releaseInjectionState();
4117
4118 dispatchInProgress = false;
4119 syntheticRepeat = false;
4120 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4121 interceptKeyWakeupTime = 0;
4122}
4123
4124
4125// --- InputDispatcher::MotionEntry ---
4126
Michael Wright7b159c92015-05-14 14:48:03 +01004127InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004128 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4129 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004130 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4131 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004132 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004133 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4134 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4136 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004137 deviceId(deviceId), source(source), displayId(displayId), action(action),
4138 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004139 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004140 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 for (uint32_t i = 0; i < pointerCount; i++) {
4142 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4143 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004144 if (xOffset || yOffset) {
4145 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4146 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 }
4148}
4149
4150InputDispatcher::MotionEntry::~MotionEntry() {
4151}
4152
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004153void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004154 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004155 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004156 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004157 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4158 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4159
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 for (uint32_t i = 0; i < pointerCount; i++) {
4161 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004162 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004164 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 pointerCoords[i].getX(), pointerCoords[i].getY());
4166 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004167 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168}
4169
4170
4171// --- InputDispatcher::DispatchEntry ---
4172
4173volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4174
4175InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4176 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4177 seq(nextSeq()),
4178 eventEntry(eventEntry), targetFlags(targetFlags),
4179 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4180 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4181 eventEntry->refCount += 1;
4182}
4183
4184InputDispatcher::DispatchEntry::~DispatchEntry() {
4185 eventEntry->release();
4186}
4187
4188uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4189 // Sequence number 0 is reserved and will never be returned.
4190 uint32_t seq;
4191 do {
4192 seq = android_atomic_inc(&sNextSeqAtomic);
4193 } while (!seq);
4194 return seq;
4195}
4196
4197
4198// --- InputDispatcher::InputState ---
4199
4200InputDispatcher::InputState::InputState() {
4201}
4202
4203InputDispatcher::InputState::~InputState() {
4204}
4205
4206bool InputDispatcher::InputState::isNeutral() const {
4207 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4208}
4209
4210bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4211 int32_t displayId) const {
4212 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4213 const MotionMemento& memento = mMotionMementos.itemAt(i);
4214 if (memento.deviceId == deviceId
4215 && memento.source == source
4216 && memento.displayId == displayId
4217 && memento.hovering) {
4218 return true;
4219 }
4220 }
4221 return false;
4222}
4223
4224bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4225 int32_t action, int32_t flags) {
4226 switch (action) {
4227 case AKEY_EVENT_ACTION_UP: {
4228 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4229 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4230 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4231 mFallbackKeys.removeItemsAt(i);
4232 } else {
4233 i += 1;
4234 }
4235 }
4236 }
4237 ssize_t index = findKeyMemento(entry);
4238 if (index >= 0) {
4239 mKeyMementos.removeAt(index);
4240 return true;
4241 }
4242 /* FIXME: We can't just drop the key up event because that prevents creating
4243 * popup windows that are automatically shown when a key is held and then
4244 * dismissed when the key is released. The problem is that the popup will
4245 * not have received the original key down, so the key up will be considered
4246 * to be inconsistent with its observed state. We could perhaps handle this
4247 * by synthesizing a key down but that will cause other problems.
4248 *
4249 * So for now, allow inconsistent key up events to be dispatched.
4250 *
4251#if DEBUG_OUTBOUND_EVENT_DETAILS
4252 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4253 "keyCode=%d, scanCode=%d",
4254 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4255#endif
4256 return false;
4257 */
4258 return true;
4259 }
4260
4261 case AKEY_EVENT_ACTION_DOWN: {
4262 ssize_t index = findKeyMemento(entry);
4263 if (index >= 0) {
4264 mKeyMementos.removeAt(index);
4265 }
4266 addKeyMemento(entry, flags);
4267 return true;
4268 }
4269
4270 default:
4271 return true;
4272 }
4273}
4274
4275bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4276 int32_t action, int32_t flags) {
4277 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4278 switch (actionMasked) {
4279 case AMOTION_EVENT_ACTION_UP:
4280 case AMOTION_EVENT_ACTION_CANCEL: {
4281 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4282 if (index >= 0) {
4283 mMotionMementos.removeAt(index);
4284 return true;
4285 }
4286#if DEBUG_OUTBOUND_EVENT_DETAILS
4287 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004288 "displayId=%" PRId32 ", actionMasked=%d",
4289 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290#endif
4291 return false;
4292 }
4293
4294 case AMOTION_EVENT_ACTION_DOWN: {
4295 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4296 if (index >= 0) {
4297 mMotionMementos.removeAt(index);
4298 }
4299 addMotionMemento(entry, flags, false /*hovering*/);
4300 return true;
4301 }
4302
4303 case AMOTION_EVENT_ACTION_POINTER_UP:
4304 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4305 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004306 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4307 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4308 // generate cancellation events for these since they're based in relative rather than
4309 // absolute units.
4310 return true;
4311 }
4312
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004314
4315 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4316 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4317 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4318 // other value and we need to track the motion so we can send cancellation events for
4319 // anything generating fallback events (e.g. DPad keys for joystick movements).
4320 if (index >= 0) {
4321 if (entry->pointerCoords[0].isEmpty()) {
4322 mMotionMementos.removeAt(index);
4323 } else {
4324 MotionMemento& memento = mMotionMementos.editItemAt(index);
4325 memento.setPointers(entry);
4326 }
4327 } else if (!entry->pointerCoords[0].isEmpty()) {
4328 addMotionMemento(entry, flags, false /*hovering*/);
4329 }
4330
4331 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4332 return true;
4333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 if (index >= 0) {
4335 MotionMemento& memento = mMotionMementos.editItemAt(index);
4336 memento.setPointers(entry);
4337 return true;
4338 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339#if DEBUG_OUTBOUND_EVENT_DETAILS
4340 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004341 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4342 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343#endif
4344 return false;
4345 }
4346
4347 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4348 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4349 if (index >= 0) {
4350 mMotionMementos.removeAt(index);
4351 return true;
4352 }
4353#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004354 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4355 "displayId=%" PRId32,
4356 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357#endif
4358 return false;
4359 }
4360
4361 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4362 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4363 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4364 if (index >= 0) {
4365 mMotionMementos.removeAt(index);
4366 }
4367 addMotionMemento(entry, flags, true /*hovering*/);
4368 return true;
4369 }
4370
4371 default:
4372 return true;
4373 }
4374}
4375
4376ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4377 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4378 const KeyMemento& memento = mKeyMementos.itemAt(i);
4379 if (memento.deviceId == entry->deviceId
4380 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004381 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 && memento.keyCode == entry->keyCode
4383 && memento.scanCode == entry->scanCode) {
4384 return i;
4385 }
4386 }
4387 return -1;
4388}
4389
4390ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4391 bool hovering) const {
4392 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4393 const MotionMemento& memento = mMotionMementos.itemAt(i);
4394 if (memento.deviceId == entry->deviceId
4395 && memento.source == entry->source
4396 && memento.displayId == entry->displayId
4397 && memento.hovering == hovering) {
4398 return i;
4399 }
4400 }
4401 return -1;
4402}
4403
4404void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4405 mKeyMementos.push();
4406 KeyMemento& memento = mKeyMementos.editTop();
4407 memento.deviceId = entry->deviceId;
4408 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004409 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410 memento.keyCode = entry->keyCode;
4411 memento.scanCode = entry->scanCode;
4412 memento.metaState = entry->metaState;
4413 memento.flags = flags;
4414 memento.downTime = entry->downTime;
4415 memento.policyFlags = entry->policyFlags;
4416}
4417
4418void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4419 int32_t flags, bool hovering) {
4420 mMotionMementos.push();
4421 MotionMemento& memento = mMotionMementos.editTop();
4422 memento.deviceId = entry->deviceId;
4423 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004424 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 memento.flags = flags;
4426 memento.xPrecision = entry->xPrecision;
4427 memento.yPrecision = entry->yPrecision;
4428 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 memento.setPointers(entry);
4430 memento.hovering = hovering;
4431 memento.policyFlags = entry->policyFlags;
4432}
4433
4434void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4435 pointerCount = entry->pointerCount;
4436 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4437 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4438 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4439 }
4440}
4441
4442void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4443 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4444 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4445 const KeyMemento& memento = mKeyMementos.itemAt(i);
4446 if (shouldCancelKey(memento, options)) {
4447 outEvents.push(new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004448 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4450 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4451 }
4452 }
4453
4454 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4455 const MotionMemento& memento = mMotionMementos.itemAt(i);
4456 if (shouldCancelMotion(memento, options)) {
4457 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004458 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 memento.hovering
4460 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4461 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004462 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004464 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4465 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466 }
4467 }
4468}
4469
4470void InputDispatcher::InputState::clear() {
4471 mKeyMementos.clear();
4472 mMotionMementos.clear();
4473 mFallbackKeys.clear();
4474}
4475
4476void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4477 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4478 const MotionMemento& memento = mMotionMementos.itemAt(i);
4479 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4480 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4481 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4482 if (memento.deviceId == otherMemento.deviceId
4483 && memento.source == otherMemento.source
4484 && memento.displayId == otherMemento.displayId) {
4485 other.mMotionMementos.removeAt(j);
4486 } else {
4487 j += 1;
4488 }
4489 }
4490 other.mMotionMementos.push(memento);
4491 }
4492 }
4493}
4494
4495int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4496 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4497 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4498}
4499
4500void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4501 int32_t fallbackKeyCode) {
4502 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4503 if (index >= 0) {
4504 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4505 } else {
4506 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4507 }
4508}
4509
4510void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4511 mFallbackKeys.removeItem(originalKeyCode);
4512}
4513
4514bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4515 const CancelationOptions& options) {
4516 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4517 return false;
4518 }
4519
4520 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4521 return false;
4522 }
4523
4524 switch (options.mode) {
4525 case CancelationOptions::CANCEL_ALL_EVENTS:
4526 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4527 return true;
4528 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4529 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4530 default:
4531 return false;
4532 }
4533}
4534
4535bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4536 const CancelationOptions& options) {
4537 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4538 return false;
4539 }
4540
4541 switch (options.mode) {
4542 case CancelationOptions::CANCEL_ALL_EVENTS:
4543 return true;
4544 case CancelationOptions::CANCEL_POINTER_EVENTS:
4545 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4546 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4547 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4548 default:
4549 return false;
4550 }
4551}
4552
4553
4554// --- InputDispatcher::Connection ---
4555
4556InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4557 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4558 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4559 monitor(monitor),
4560 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4561}
4562
4563InputDispatcher::Connection::~Connection() {
4564}
4565
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004566const std::string InputDispatcher::Connection::getWindowName() const {
Yi Kong9b14ac62018-07-17 13:48:38 -07004567 if (inputWindowHandle != nullptr) {
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004568 return inputWindowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 }
4570 if (monitor) {
4571 return "monitor";
4572 }
4573 return "?";
4574}
4575
4576const char* InputDispatcher::Connection::getStatusLabel() const {
4577 switch (status) {
4578 case STATUS_NORMAL:
4579 return "NORMAL";
4580
4581 case STATUS_BROKEN:
4582 return "BROKEN";
4583
4584 case STATUS_ZOMBIE:
4585 return "ZOMBIE";
4586
4587 default:
4588 return "UNKNOWN";
4589 }
4590}
4591
4592InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004593 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594 if (entry->seq == seq) {
4595 return entry;
4596 }
4597 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004598 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004599}
4600
4601
4602// --- InputDispatcher::CommandEntry ---
4603
4604InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004605 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606 seq(0), handled(false) {
4607}
4608
4609InputDispatcher::CommandEntry::~CommandEntry() {
4610}
4611
4612
4613// --- InputDispatcher::TouchState ---
4614
4615InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004616 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617}
4618
4619InputDispatcher::TouchState::~TouchState() {
4620}
4621
4622void InputDispatcher::TouchState::reset() {
4623 down = false;
4624 split = false;
4625 deviceId = -1;
4626 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004627 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 windows.clear();
4629}
4630
4631void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4632 down = other.down;
4633 split = other.split;
4634 deviceId = other.deviceId;
4635 source = other.source;
4636 displayId = other.displayId;
4637 windows = other.windows;
4638}
4639
4640void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4641 int32_t targetFlags, BitSet32 pointerIds) {
4642 if (targetFlags & InputTarget::FLAG_SPLIT) {
4643 split = true;
4644 }
4645
4646 for (size_t i = 0; i < windows.size(); i++) {
4647 TouchedWindow& touchedWindow = windows.editItemAt(i);
4648 if (touchedWindow.windowHandle == windowHandle) {
4649 touchedWindow.targetFlags |= targetFlags;
4650 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4651 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4652 }
4653 touchedWindow.pointerIds.value |= pointerIds.value;
4654 return;
4655 }
4656 }
4657
4658 windows.push();
4659
4660 TouchedWindow& touchedWindow = windows.editTop();
4661 touchedWindow.windowHandle = windowHandle;
4662 touchedWindow.targetFlags = targetFlags;
4663 touchedWindow.pointerIds = pointerIds;
4664}
4665
4666void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4667 for (size_t i = 0; i < windows.size(); i++) {
4668 if (windows.itemAt(i).windowHandle == windowHandle) {
4669 windows.removeAt(i);
4670 return;
4671 }
4672 }
4673}
4674
4675void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4676 for (size_t i = 0 ; i < windows.size(); ) {
4677 TouchedWindow& window = windows.editItemAt(i);
4678 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4679 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4680 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4681 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4682 i += 1;
4683 } else {
4684 windows.removeAt(i);
4685 }
4686 }
4687}
4688
4689sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4690 for (size_t i = 0; i < windows.size(); i++) {
4691 const TouchedWindow& window = windows.itemAt(i);
4692 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4693 return window.windowHandle;
4694 }
4695 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004696 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697}
4698
4699bool InputDispatcher::TouchState::isSlippery() const {
4700 // Must have exactly one foreground window.
4701 bool haveSlipperyForegroundWindow = false;
4702 for (size_t i = 0; i < windows.size(); i++) {
4703 const TouchedWindow& window = windows.itemAt(i);
4704 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4705 if (haveSlipperyForegroundWindow
4706 || !(window.windowHandle->getInfo()->layoutParamsFlags
4707 & InputWindowInfo::FLAG_SLIPPERY)) {
4708 return false;
4709 }
4710 haveSlipperyForegroundWindow = true;
4711 }
4712 }
4713 return haveSlipperyForegroundWindow;
4714}
4715
4716
4717// --- InputDispatcherThread ---
4718
4719InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4720 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4721}
4722
4723InputDispatcherThread::~InputDispatcherThread() {
4724}
4725
4726bool InputDispatcherThread::threadLoop() {
4727 mDispatcher->dispatchOnce();
4728 return true;
4729}
4730
4731} // namespace android