blob: 863e4263378af38732761ea632f45299853568fb [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 Hung09cb30e2018-07-30 15:04:39 +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 Hung09cb30e2018-07-30 15:04:39 +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 Hung09cb30e2018-07-30 15:04:39 +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 Hung09cb30e2018-07-30 15:04:39 +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 Hung09cb30e2018-07-30 15:04:39 +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 Hung09cb30e2018-07-30 15:04:39 +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 Hung09cb30e2018-07-30 15:04:39 +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 Hung09cb30e2018-07-30 15:04:39 +08001686 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001687 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung09cb30e2018-07-30 15:04:39 +08001688 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001689 for (size_t i = 0; i < numWindows; i++) {
Arthur Hung09cb30e2018-07-30 15:04:39 +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 Hung09cb30e2018-07-30 15:04:39 +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 Hung09cb30e2018-07-30 15:04:39 +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(
Arthur Hung09cb30e2018-07-30 15:04:39 +08002945 const sp<InputWindowHandle>& windowHandle, int32_t displayId) const {
2946
2947 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
2948 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 for (size_t i = 0; i < numWindows; i++) {
Arthur Hung09cb30e2018-07-30 15:04:39 +08002950 if (windowHandles.itemAt(i) == windowHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002951 return true;
2952 }
2953 }
2954 return false;
2955}
2956
Arthur Hung09cb30e2018-07-30 15:04:39 +08002957void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
2958 int displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002959#if DEBUG_FOCUS
2960 ALOGD("setInputWindows");
2961#endif
2962 { // acquire lock
2963 AutoMutex _l(mLock);
2964
Arthur Hung09cb30e2018-07-30 15:04:39 +08002965 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
2966 Vector<sp<InputWindowHandle>> windowHandles = inputWindowHandles;
2967 // Insert or replace
2968 mWindowHandlesByDisplay[displayId] = windowHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002969
Arthur Hung09cb30e2018-07-30 15:04:39 +08002970 // TODO(b/111361570): multi-display focus, one focus in all display in current.
2971 sp<InputWindowHandle> newFocusedWindowHandle = mFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 bool foundHoveredWindow = false;
Arthur Hung09cb30e2018-07-30 15:04:39 +08002973
2974 if (windowHandles.isEmpty()) {
2975 // Remove all handles on a display if there are no windows left.
2976 mWindowHandlesByDisplay.erase(displayId);
2977 } else {
2978 for (size_t i = 0; i < windowHandles.size(); i++) {
2979 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
2980 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == nullptr) {
2981 continue;
2982 }
2983 if (windowHandle->getInfo()->hasFocus) {
2984 newFocusedWindowHandle = windowHandle;
2985 }
2986 if (windowHandle == mLastHoverWindowHandle) {
2987 foundHoveredWindow = true;
2988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002989 }
2990 }
2991
2992 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002993 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002994 }
2995
Arthur Hung09cb30e2018-07-30 15:04:39 +08002996 // TODO(b/111361570): multi-display focus, one focus in all display in current.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002997 if (mFocusedWindowHandle != newFocusedWindowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07002998 if (mFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002999#if DEBUG_FOCUS
3000 ALOGD("Focus left window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003001 mFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002#endif
3003 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
Yi Kong9b14ac62018-07-17 13:48:38 -07003004 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003005 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3006 "focus left window");
3007 synthesizeCancelationEventsForInputChannelLocked(
3008 focusedInputChannel, options);
3009 }
3010 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003011 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012#if DEBUG_FOCUS
3013 ALOGD("Focus entered window: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003014 newFocusedWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015#endif
3016 }
3017 mFocusedWindowHandle = newFocusedWindowHandle;
3018 }
3019
Arthur Hung09cb30e2018-07-30 15:04:39 +08003020 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3021 if (stateIndex >= 0) {
3022 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003023 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003024 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Arthur Hung09cb30e2018-07-30 15:04:39 +08003025 if (!hasWindowHandleLocked(touchedWindow.windowHandle, displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026#if DEBUG_FOCUS
Jeff Brownf086ddb2014-02-11 14:28:48 -08003027 ALOGD("Touched window was removed: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003028 touchedWindow.windowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003030 sp<InputChannel> touchedInputChannel =
3031 touchedWindow.windowHandle->getInputChannel();
Yi Kong9b14ac62018-07-17 13:48:38 -07003032 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003033 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3034 "touched window was removed");
3035 synthesizeCancelationEventsForInputChannelLocked(
3036 touchedInputChannel, options);
3037 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003038 state.windows.removeAt(i);
3039 } else {
3040 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 }
3043 }
3044
3045 // Release information for windows that are no longer present.
3046 // This ensures that unused input channels are released promptly.
3047 // Otherwise, they might stick around until the window handle is destroyed
3048 // which might not happen until the next GC.
3049 for (size_t i = 0; i < oldWindowHandles.size(); i++) {
3050 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Arthur Hung09cb30e2018-07-30 15:04:39 +08003051 if (!hasWindowHandleLocked(oldWindowHandle, displayId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003053 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054#endif
3055 oldWindowHandle->releaseInfo();
3056 }
3057 }
3058 } // release lock
3059
3060 // Wake up poll loop since it may need to make new input dispatching choices.
3061 mLooper->wake();
3062}
3063
3064void InputDispatcher::setFocusedApplication(
3065 const sp<InputApplicationHandle>& inputApplicationHandle) {
3066#if DEBUG_FOCUS
3067 ALOGD("setFocusedApplication");
3068#endif
3069 { // acquire lock
3070 AutoMutex _l(mLock);
3071
Yi Kong9b14ac62018-07-17 13:48:38 -07003072 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073 if (mFocusedApplicationHandle != inputApplicationHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003074 if (mFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003075 resetANRTimeoutsLocked();
3076 mFocusedApplicationHandle->releaseInfo();
3077 }
3078 mFocusedApplicationHandle = inputApplicationHandle;
3079 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003080 } else if (mFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081 resetANRTimeoutsLocked();
3082 mFocusedApplicationHandle->releaseInfo();
3083 mFocusedApplicationHandle.clear();
3084 }
3085
3086#if DEBUG_FOCUS
3087 //logDispatchStateLocked();
3088#endif
3089 } // release lock
3090
3091 // Wake up poll loop since it may need to make new input dispatching choices.
3092 mLooper->wake();
3093}
3094
3095void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3096#if DEBUG_FOCUS
3097 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3098#endif
3099
3100 bool changed;
3101 { // acquire lock
3102 AutoMutex _l(mLock);
3103
3104 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3105 if (mDispatchFrozen && !frozen) {
3106 resetANRTimeoutsLocked();
3107 }
3108
3109 if (mDispatchEnabled && !enabled) {
3110 resetAndDropEverythingLocked("dispatcher is being disabled");
3111 }
3112
3113 mDispatchEnabled = enabled;
3114 mDispatchFrozen = frozen;
3115 changed = true;
3116 } else {
3117 changed = false;
3118 }
3119
3120#if DEBUG_FOCUS
3121 //logDispatchStateLocked();
3122#endif
3123 } // release lock
3124
3125 if (changed) {
3126 // Wake up poll loop since it may need to make new input dispatching choices.
3127 mLooper->wake();
3128 }
3129}
3130
3131void InputDispatcher::setInputFilterEnabled(bool enabled) {
3132#if DEBUG_FOCUS
3133 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3134#endif
3135
3136 { // acquire lock
3137 AutoMutex _l(mLock);
3138
3139 if (mInputFilterEnabled == enabled) {
3140 return;
3141 }
3142
3143 mInputFilterEnabled = enabled;
3144 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3145 } // release lock
3146
3147 // Wake up poll loop since there might be work to do to drop everything.
3148 mLooper->wake();
3149}
3150
3151bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3152 const sp<InputChannel>& toChannel) {
3153#if DEBUG_FOCUS
3154 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003155 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156#endif
3157 { // acquire lock
3158 AutoMutex _l(mLock);
3159
3160 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3161 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07003162 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163#if DEBUG_FOCUS
3164 ALOGD("Cannot transfer focus because from or to window not found.");
3165#endif
3166 return false;
3167 }
3168 if (fromWindowHandle == toWindowHandle) {
3169#if DEBUG_FOCUS
3170 ALOGD("Trivial transfer to same window.");
3171#endif
3172 return true;
3173 }
3174 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3175#if DEBUG_FOCUS
3176 ALOGD("Cannot transfer focus because windows are on different displays.");
3177#endif
3178 return false;
3179 }
3180
3181 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003182 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3183 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3184 for (size_t i = 0; i < state.windows.size(); i++) {
3185 const TouchedWindow& touchedWindow = state.windows[i];
3186 if (touchedWindow.windowHandle == fromWindowHandle) {
3187 int32_t oldTargetFlags = touchedWindow.targetFlags;
3188 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189
Jeff Brownf086ddb2014-02-11 14:28:48 -08003190 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191
Jeff Brownf086ddb2014-02-11 14:28:48 -08003192 int32_t newTargetFlags = oldTargetFlags
3193 & (InputTarget::FLAG_FOREGROUND
3194 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3195 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196
Jeff Brownf086ddb2014-02-11 14:28:48 -08003197 found = true;
3198 goto Found;
3199 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 }
3201 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003202Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203
3204 if (! found) {
3205#if DEBUG_FOCUS
3206 ALOGD("Focus transfer failed because from window did not have focus.");
3207#endif
3208 return false;
3209 }
3210
3211 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3212 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3213 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3214 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3215 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3216
3217 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3218 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3219 "transferring touch focus from this window to another window");
3220 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3221 }
3222
3223#if DEBUG_FOCUS
3224 logDispatchStateLocked();
3225#endif
3226 } // release lock
3227
3228 // Wake up poll loop since it may need to make new input dispatching choices.
3229 mLooper->wake();
3230 return true;
3231}
3232
3233void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3234#if DEBUG_FOCUS
3235 ALOGD("Resetting and dropping all events (%s).", reason);
3236#endif
3237
3238 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3239 synthesizeCancelationEventsForAllConnectionsLocked(options);
3240
3241 resetKeyRepeatLocked();
3242 releasePendingEventLocked();
3243 drainInboundQueueLocked();
3244 resetANRTimeoutsLocked();
3245
Jeff Brownf086ddb2014-02-11 14:28:48 -08003246 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003248 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249}
3250
3251void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003252 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 dumpDispatchStateLocked(dump);
3254
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003255 std::istringstream stream(dump);
3256 std::string line;
3257
3258 while (std::getline(stream, line, '\n')) {
3259 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003260 }
3261}
3262
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003263void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3264 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3265 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266
Yi Kong9b14ac62018-07-17 13:48:38 -07003267 if (mFocusedApplicationHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003268 dump += StringPrintf(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
3269 mFocusedApplicationHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270 mFocusedApplicationHandle->getDispatchingTimeout(
3271 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3272 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003273 dump += StringPrintf(INDENT "FocusedApplication: <null>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003275 dump += StringPrintf(INDENT "FocusedWindow: name='%s'\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07003276 mFocusedWindowHandle != nullptr ? mFocusedWindowHandle->getName().c_str() : "<null>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277
Jeff Brownf086ddb2014-02-11 14:28:48 -08003278 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003279 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003280 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3281 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003282 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003283 state.displayId, toString(state.down), toString(state.split),
3284 state.deviceId, state.source);
3285 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003286 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003287 for (size_t i = 0; i < state.windows.size(); i++) {
3288 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003289 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3290 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003291 touchedWindow.pointerIds.value,
3292 touchedWindow.targetFlags);
3293 }
3294 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003295 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003296 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 }
3298 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003299 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003300 }
3301
Arthur Hung09cb30e2018-07-30 15:04:39 +08003302 if (!mWindowHandlesByDisplay.empty()) {
3303 for (auto& it : mWindowHandlesByDisplay) {
3304 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3305 dump += StringPrintf(INDENT "Display: %d\n", it.first);
3306 if (!windowHandles.isEmpty()) {
3307 dump += INDENT "Windows:\n";
3308 for (size_t i = 0; i < windowHandles.size(); i++) {
3309 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3310 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311
Arthur Hung09cb30e2018-07-30 15:04:39 +08003312 dump += StringPrintf(INDENT2 "%zu: name='%s', displayId=%d, "
3313 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3314 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3315 "frame=[%d,%d][%d,%d], scale=%f, "
3316 "touchableRegion=",
3317 i, windowInfo->name.c_str(), windowInfo->displayId,
3318 toString(windowInfo->paused),
3319 toString(windowInfo->hasFocus),
3320 toString(windowInfo->hasWallpaper),
3321 toString(windowInfo->visible),
3322 toString(windowInfo->canReceiveKeys),
3323 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3324 windowInfo->layer,
3325 windowInfo->frameLeft, windowInfo->frameTop,
3326 windowInfo->frameRight, windowInfo->frameBottom,
3327 windowInfo->scaleFactor);
3328 dumpRegion(dump, windowInfo->touchableRegion);
3329 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3330 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3331 windowInfo->ownerPid, windowInfo->ownerUid,
3332 windowInfo->dispatchingTimeout / 1000000.0);
3333 }
3334 } else {
3335 dump += INDENT "Windows: <none>\n";
3336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 }
3338 } else {
Arthur Hung09cb30e2018-07-30 15:04:39 +08003339 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 }
3341
3342 if (!mMonitoringChannels.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003343 dump += INDENT "MonitoringChannels:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3345 const sp<InputChannel>& channel = mMonitoringChannels[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003346 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347 }
3348 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003349 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 }
3351
3352 nsecs_t currentTime = now();
3353
3354 // Dump recently dispatched or dropped events from oldest to newest.
3355 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003356 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003358 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003360 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361 (currentTime - entry->eventTime) * 0.000001f);
3362 }
3363 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003364 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365 }
3366
3367 // Dump event currently being dispatched.
3368 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003369 dump += INDENT "PendingEvent:\n";
3370 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003372 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3374 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003375 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 }
3377
3378 // Dump inbound events from oldest to newest.
3379 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003380 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003382 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003384 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 (currentTime - entry->eventTime) * 0.000001f);
3386 }
3387 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003388 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 }
3390
Michael Wright78f24442014-08-06 15:55:28 -07003391 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003392 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003393 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3394 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3395 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003396 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003397 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3398 }
3399 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003400 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003401 }
3402
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003404 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3406 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003407 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003409 i, connection->getInputChannelName().c_str(),
3410 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 connection->getStatusLabel(), toString(connection->monitor),
3412 toString(connection->inputPublisherBlocked));
3413
3414 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003415 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 connection->outboundQueue.count());
3417 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3418 entry = entry->next) {
3419 dump.append(INDENT4);
3420 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003421 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 entry->targetFlags, entry->resolvedAction,
3423 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3424 }
3425 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003426 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 }
3428
3429 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003430 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431 connection->waitQueue.count());
3432 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3433 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003434 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003436 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437 "age=%0.1fms, wait=%0.1fms\n",
3438 entry->targetFlags, entry->resolvedAction,
3439 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3440 (currentTime - entry->deliveryTime) * 0.000001f);
3441 }
3442 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003443 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003444 }
3445 }
3446 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003447 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 }
3449
3450 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003451 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 (mAppSwitchDueTime - now()) / 1000000.0);
3453 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003454 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003455 }
3456
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003457 dump += INDENT "Configuration:\n";
3458 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003460 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461 mConfig.keyRepeatTimeout * 0.000001f);
3462}
3463
3464status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3465 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
3466#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003467 ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 toString(monitor));
3469#endif
3470
3471 { // acquire lock
3472 AutoMutex _l(mLock);
3473
3474 if (getConnectionIndexLocked(inputChannel) >= 0) {
3475 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003476 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 return BAD_VALUE;
3478 }
3479
3480 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3481
3482 int fd = inputChannel->getFd();
3483 mConnectionsByFd.add(fd, connection);
3484
3485 if (monitor) {
3486 mMonitoringChannels.push(inputChannel);
3487 }
3488
3489 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3490 } // release lock
3491
3492 // Wake the looper because some connections have changed.
3493 mLooper->wake();
3494 return OK;
3495}
3496
3497status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3498#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003499 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500#endif
3501
3502 { // acquire lock
3503 AutoMutex _l(mLock);
3504
3505 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3506 if (status) {
3507 return status;
3508 }
3509 } // release lock
3510
3511 // Wake the poll loop because removing the connection may have changed the current
3512 // synchronization state.
3513 mLooper->wake();
3514 return OK;
3515}
3516
3517status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3518 bool notify) {
3519 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3520 if (connectionIndex < 0) {
3521 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003522 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523 return BAD_VALUE;
3524 }
3525
3526 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3527 mConnectionsByFd.removeItemsAt(connectionIndex);
3528
3529 if (connection->monitor) {
3530 removeMonitorChannelLocked(inputChannel);
3531 }
3532
3533 mLooper->removeFd(inputChannel->getFd());
3534
3535 nsecs_t currentTime = now();
3536 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3537
3538 connection->status = Connection::STATUS_ZOMBIE;
3539 return OK;
3540}
3541
3542void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
3543 for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
3544 if (mMonitoringChannels[i] == inputChannel) {
3545 mMonitoringChannels.removeAt(i);
3546 break;
3547 }
3548 }
3549}
3550
3551ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
3552 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3553 if (connectionIndex >= 0) {
3554 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3555 if (connection->inputChannel.get() == inputChannel.get()) {
3556 return connectionIndex;
3557 }
3558 }
3559
3560 return -1;
3561}
3562
3563void InputDispatcher::onDispatchCycleFinishedLocked(
3564 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3565 CommandEntry* commandEntry = postCommandLocked(
3566 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3567 commandEntry->connection = connection;
3568 commandEntry->eventTime = currentTime;
3569 commandEntry->seq = seq;
3570 commandEntry->handled = handled;
3571}
3572
3573void InputDispatcher::onDispatchCycleBrokenLocked(
3574 nsecs_t currentTime, const sp<Connection>& connection) {
3575 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003576 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577
3578 CommandEntry* commandEntry = postCommandLocked(
3579 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3580 commandEntry->connection = connection;
3581}
3582
3583void InputDispatcher::onANRLocked(
3584 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3585 const sp<InputWindowHandle>& windowHandle,
3586 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3587 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3588 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3589 ALOGI("Application is not responding: %s. "
3590 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003591 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 dispatchLatency, waitDuration, reason);
3593
3594 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003595 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 struct tm tm;
3597 localtime_r(&t, &tm);
3598 char timestr[64];
3599 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3600 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003601 mLastANRState += INDENT "ANR:\n";
3602 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3603 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3604 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3605 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3606 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3607 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 dumpDispatchStateLocked(mLastANRState);
3609
3610 CommandEntry* commandEntry = postCommandLocked(
3611 & InputDispatcher::doNotifyANRLockedInterruptible);
3612 commandEntry->inputApplicationHandle = applicationHandle;
3613 commandEntry->inputWindowHandle = windowHandle;
3614 commandEntry->reason = reason;
3615}
3616
3617void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3618 CommandEntry* commandEntry) {
3619 mLock.unlock();
3620
3621 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3622
3623 mLock.lock();
3624}
3625
3626void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3627 CommandEntry* commandEntry) {
3628 sp<Connection> connection = commandEntry->connection;
3629
3630 if (connection->status != Connection::STATUS_ZOMBIE) {
3631 mLock.unlock();
3632
3633 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3634
3635 mLock.lock();
3636 }
3637}
3638
3639void InputDispatcher::doNotifyANRLockedInterruptible(
3640 CommandEntry* commandEntry) {
3641 mLock.unlock();
3642
3643 nsecs_t newTimeout = mPolicy->notifyANR(
3644 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3645 commandEntry->reason);
3646
3647 mLock.lock();
3648
3649 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Yi Kong9b14ac62018-07-17 13:48:38 -07003650 commandEntry->inputWindowHandle != nullptr
3651 ? commandEntry->inputWindowHandle->getInputChannel() : nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652}
3653
3654void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3655 CommandEntry* commandEntry) {
3656 KeyEntry* entry = commandEntry->keyEntry;
3657
3658 KeyEvent event;
3659 initializeKeyEvent(&event, entry);
3660
3661 mLock.unlock();
3662
Michael Wright2b3c3302018-03-02 17:19:13 +00003663 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3665 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003666 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3667 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3668 std::to_string(t.duration().count()).c_str());
3669 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670
3671 mLock.lock();
3672
3673 if (delay < 0) {
3674 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3675 } else if (!delay) {
3676 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3677 } else {
3678 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3679 entry->interceptKeyWakeupTime = now() + delay;
3680 }
3681 entry->release();
3682}
3683
3684void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3685 CommandEntry* commandEntry) {
3686 sp<Connection> connection = commandEntry->connection;
3687 nsecs_t finishTime = commandEntry->eventTime;
3688 uint32_t seq = commandEntry->seq;
3689 bool handled = commandEntry->handled;
3690
3691 // Handle post-event policy actions.
3692 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3693 if (dispatchEntry) {
3694 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3695 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003696 std::string msg =
3697 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003698 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003700 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 }
3702
3703 bool restartEvent;
3704 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3705 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3706 restartEvent = afterKeyEventLockedInterruptible(connection,
3707 dispatchEntry, keyEntry, handled);
3708 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3709 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3710 restartEvent = afterMotionEventLockedInterruptible(connection,
3711 dispatchEntry, motionEntry, handled);
3712 } else {
3713 restartEvent = false;
3714 }
3715
3716 // Dequeue the event and start the next cycle.
3717 // Note that because the lock might have been released, it is possible that the
3718 // contents of the wait queue to have been drained, so we need to double-check
3719 // a few things.
3720 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3721 connection->waitQueue.dequeue(dispatchEntry);
3722 traceWaitQueueLengthLocked(connection);
3723 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3724 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3725 traceOutboundQueueLengthLocked(connection);
3726 } else {
3727 releaseDispatchEntryLocked(dispatchEntry);
3728 }
3729 }
3730
3731 // Start the next dispatch cycle for this connection.
3732 startDispatchCycleLocked(now(), connection);
3733 }
3734}
3735
3736bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3737 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3738 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3739 // Get the fallback key state.
3740 // Clear it out after dispatching the UP.
3741 int32_t originalKeyCode = keyEntry->keyCode;
3742 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3743 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3744 connection->inputState.removeFallbackKey(originalKeyCode);
3745 }
3746
3747 if (handled || !dispatchEntry->hasForegroundTarget()) {
3748 // If the application handles the original key for which we previously
3749 // generated a fallback or if the window is not a foreground window,
3750 // then cancel the associated fallback key, if any.
3751 if (fallbackKeyCode != -1) {
3752 // Dispatch the unhandled key to the policy with the cancel flag.
3753#if DEBUG_OUTBOUND_EVENT_DETAILS
3754 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3755 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3756 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3757 keyEntry->policyFlags);
3758#endif
3759 KeyEvent event;
3760 initializeKeyEvent(&event, keyEntry);
3761 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3762
3763 mLock.unlock();
3764
3765 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3766 &event, keyEntry->policyFlags, &event);
3767
3768 mLock.lock();
3769
3770 // Cancel the fallback key.
3771 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3772 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3773 "application handled the original non-fallback key "
3774 "or is no longer a foreground target, "
3775 "canceling previously dispatched fallback key");
3776 options.keyCode = fallbackKeyCode;
3777 synthesizeCancelationEventsForConnectionLocked(connection, options);
3778 }
3779 connection->inputState.removeFallbackKey(originalKeyCode);
3780 }
3781 } else {
3782 // If the application did not handle a non-fallback key, first check
3783 // that we are in a good state to perform unhandled key event processing
3784 // Then ask the policy what to do with it.
3785 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3786 && keyEntry->repeatCount == 0;
3787 if (fallbackKeyCode == -1 && !initialDown) {
3788#if DEBUG_OUTBOUND_EVENT_DETAILS
3789 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3790 "since this is not an initial down. "
3791 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3792 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3793 keyEntry->policyFlags);
3794#endif
3795 return false;
3796 }
3797
3798 // Dispatch the unhandled key to the policy.
3799#if DEBUG_OUTBOUND_EVENT_DETAILS
3800 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
3801 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3802 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3803 keyEntry->policyFlags);
3804#endif
3805 KeyEvent event;
3806 initializeKeyEvent(&event, keyEntry);
3807
3808 mLock.unlock();
3809
3810 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3811 &event, keyEntry->policyFlags, &event);
3812
3813 mLock.lock();
3814
3815 if (connection->status != Connection::STATUS_NORMAL) {
3816 connection->inputState.removeFallbackKey(originalKeyCode);
3817 return false;
3818 }
3819
3820 // Latch the fallback keycode for this key on an initial down.
3821 // The fallback keycode cannot change at any other point in the lifecycle.
3822 if (initialDown) {
3823 if (fallback) {
3824 fallbackKeyCode = event.getKeyCode();
3825 } else {
3826 fallbackKeyCode = AKEYCODE_UNKNOWN;
3827 }
3828 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
3829 }
3830
3831 ALOG_ASSERT(fallbackKeyCode != -1);
3832
3833 // Cancel the fallback key if the policy decides not to send it anymore.
3834 // We will continue to dispatch the key to the policy but we will no
3835 // longer dispatch a fallback key to the application.
3836 if (fallbackKeyCode != AKEYCODE_UNKNOWN
3837 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
3838#if DEBUG_OUTBOUND_EVENT_DETAILS
3839 if (fallback) {
3840 ALOGD("Unhandled key event: Policy requested to send key %d"
3841 "as a fallback for %d, but on the DOWN it had requested "
3842 "to send %d instead. Fallback canceled.",
3843 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
3844 } else {
3845 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
3846 "but on the DOWN it had requested to send %d. "
3847 "Fallback canceled.",
3848 originalKeyCode, fallbackKeyCode);
3849 }
3850#endif
3851
3852 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3853 "canceling fallback, policy no longer desires it");
3854 options.keyCode = fallbackKeyCode;
3855 synthesizeCancelationEventsForConnectionLocked(connection, options);
3856
3857 fallback = false;
3858 fallbackKeyCode = AKEYCODE_UNKNOWN;
3859 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
3860 connection->inputState.setFallbackKey(originalKeyCode,
3861 fallbackKeyCode);
3862 }
3863 }
3864
3865#if DEBUG_OUTBOUND_EVENT_DETAILS
3866 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003867 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868 const KeyedVector<int32_t, int32_t>& fallbackKeys =
3869 connection->inputState.getFallbackKeys();
3870 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003871 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872 fallbackKeys.valueAt(i));
3873 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07003874 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003875 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 }
3877#endif
3878
3879 if (fallback) {
3880 // Restart the dispatch cycle using the fallback key.
3881 keyEntry->eventTime = event.getEventTime();
3882 keyEntry->deviceId = event.getDeviceId();
3883 keyEntry->source = event.getSource();
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01003884 keyEntry->displayId = event.getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003885 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
3886 keyEntry->keyCode = fallbackKeyCode;
3887 keyEntry->scanCode = event.getScanCode();
3888 keyEntry->metaState = event.getMetaState();
3889 keyEntry->repeatCount = event.getRepeatCount();
3890 keyEntry->downTime = event.getDownTime();
3891 keyEntry->syntheticRepeat = false;
3892
3893#if DEBUG_OUTBOUND_EVENT_DETAILS
3894 ALOGD("Unhandled key event: Dispatching fallback key. "
3895 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
3896 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
3897#endif
3898 return true; // restart the event
3899 } else {
3900#if DEBUG_OUTBOUND_EVENT_DETAILS
3901 ALOGD("Unhandled key event: No fallback key.");
3902#endif
3903 }
3904 }
3905 }
3906 return false;
3907}
3908
3909bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
3910 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
3911 return false;
3912}
3913
3914void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
3915 mLock.unlock();
3916
3917 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
3918
3919 mLock.lock();
3920}
3921
3922void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01003923 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
3925 entry->downTime, entry->eventTime);
3926}
3927
3928void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
3929 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
3930 // TODO Write some statistics about how long we spend waiting.
3931}
3932
3933void InputDispatcher::traceInboundQueueLengthLocked() {
3934 if (ATRACE_ENABLED()) {
3935 ATRACE_INT("iq", mInboundQueue.count());
3936 }
3937}
3938
3939void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
3940 if (ATRACE_ENABLED()) {
3941 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003942 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 ATRACE_INT(counterName, connection->outboundQueue.count());
3944 }
3945}
3946
3947void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
3948 if (ATRACE_ENABLED()) {
3949 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003950 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 ATRACE_INT(counterName, connection->waitQueue.count());
3952 }
3953}
3954
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003955void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956 AutoMutex _l(mLock);
3957
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003958 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959 dumpDispatchStateLocked(dump);
3960
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003961 if (!mLastANRState.empty()) {
3962 dump += "\nInput Dispatcher State at time of last ANR:\n";
3963 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 }
3965}
3966
3967void InputDispatcher::monitor() {
3968 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
3969 mLock.lock();
3970 mLooper->wake();
3971 mDispatcherIsAliveCondition.wait(mLock);
3972 mLock.unlock();
3973}
3974
3975
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976// --- InputDispatcher::InjectionState ---
3977
3978InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
3979 refCount(1),
3980 injectorPid(injectorPid), injectorUid(injectorUid),
3981 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
3982 pendingForegroundDispatches(0) {
3983}
3984
3985InputDispatcher::InjectionState::~InjectionState() {
3986}
3987
3988void InputDispatcher::InjectionState::release() {
3989 refCount -= 1;
3990 if (refCount == 0) {
3991 delete this;
3992 } else {
3993 ALOG_ASSERT(refCount > 0);
3994 }
3995}
3996
3997
3998// --- InputDispatcher::EventEntry ---
3999
4000InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4001 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
Yi Kong9b14ac62018-07-17 13:48:38 -07004002 injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003}
4004
4005InputDispatcher::EventEntry::~EventEntry() {
4006 releaseInjectionState();
4007}
4008
4009void InputDispatcher::EventEntry::release() {
4010 refCount -= 1;
4011 if (refCount == 0) {
4012 delete this;
4013 } else {
4014 ALOG_ASSERT(refCount > 0);
4015 }
4016}
4017
4018void InputDispatcher::EventEntry::releaseInjectionState() {
4019 if (injectionState) {
4020 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004021 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022 }
4023}
4024
4025
4026// --- InputDispatcher::ConfigurationChangedEntry ---
4027
4028InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4029 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4030}
4031
4032InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4033}
4034
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004035void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4036 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037}
4038
4039
4040// --- InputDispatcher::DeviceResetEntry ---
4041
4042InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4043 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4044 deviceId(deviceId) {
4045}
4046
4047InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4048}
4049
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004050void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4051 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052 deviceId, policyFlags);
4053}
4054
4055
4056// --- InputDispatcher::KeyEntry ---
4057
4058InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004059 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004060 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4061 int32_t repeatCount, nsecs_t downTime) :
4062 EventEntry(TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004063 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4065 repeatCount(repeatCount), downTime(downTime),
4066 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4067 interceptKeyWakeupTime(0) {
4068}
4069
4070InputDispatcher::KeyEntry::~KeyEntry() {
4071}
4072
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004073void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004074 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4076 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004077 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004078 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004079}
4080
4081void InputDispatcher::KeyEntry::recycle() {
4082 releaseInjectionState();
4083
4084 dispatchInProgress = false;
4085 syntheticRepeat = false;
4086 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4087 interceptKeyWakeupTime = 0;
4088}
4089
4090
4091// --- InputDispatcher::MotionEntry ---
4092
Michael Wright7b159c92015-05-14 14:48:03 +01004093InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004094 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4095 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004096 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4097 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004098 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004099 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4100 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4102 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004103 deviceId(deviceId), source(source), displayId(displayId), action(action),
4104 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004105 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004106 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 for (uint32_t i = 0; i < pointerCount; i++) {
4108 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4109 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004110 if (xOffset || yOffset) {
4111 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4112 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 }
4114}
4115
4116InputDispatcher::MotionEntry::~MotionEntry() {
4117}
4118
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004119void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004120 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004121 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004122 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004123 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4124 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4125
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126 for (uint32_t i = 0; i < pointerCount; i++) {
4127 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004128 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004130 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 pointerCoords[i].getX(), pointerCoords[i].getY());
4132 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004133 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134}
4135
4136
4137// --- InputDispatcher::DispatchEntry ---
4138
4139volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4140
4141InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4142 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4143 seq(nextSeq()),
4144 eventEntry(eventEntry), targetFlags(targetFlags),
4145 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4146 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4147 eventEntry->refCount += 1;
4148}
4149
4150InputDispatcher::DispatchEntry::~DispatchEntry() {
4151 eventEntry->release();
4152}
4153
4154uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4155 // Sequence number 0 is reserved and will never be returned.
4156 uint32_t seq;
4157 do {
4158 seq = android_atomic_inc(&sNextSeqAtomic);
4159 } while (!seq);
4160 return seq;
4161}
4162
4163
4164// --- InputDispatcher::InputState ---
4165
4166InputDispatcher::InputState::InputState() {
4167}
4168
4169InputDispatcher::InputState::~InputState() {
4170}
4171
4172bool InputDispatcher::InputState::isNeutral() const {
4173 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4174}
4175
4176bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4177 int32_t displayId) const {
4178 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4179 const MotionMemento& memento = mMotionMementos.itemAt(i);
4180 if (memento.deviceId == deviceId
4181 && memento.source == source
4182 && memento.displayId == displayId
4183 && memento.hovering) {
4184 return true;
4185 }
4186 }
4187 return false;
4188}
4189
4190bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4191 int32_t action, int32_t flags) {
4192 switch (action) {
4193 case AKEY_EVENT_ACTION_UP: {
4194 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4195 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4196 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4197 mFallbackKeys.removeItemsAt(i);
4198 } else {
4199 i += 1;
4200 }
4201 }
4202 }
4203 ssize_t index = findKeyMemento(entry);
4204 if (index >= 0) {
4205 mKeyMementos.removeAt(index);
4206 return true;
4207 }
4208 /* FIXME: We can't just drop the key up event because that prevents creating
4209 * popup windows that are automatically shown when a key is held and then
4210 * dismissed when the key is released. The problem is that the popup will
4211 * not have received the original key down, so the key up will be considered
4212 * to be inconsistent with its observed state. We could perhaps handle this
4213 * by synthesizing a key down but that will cause other problems.
4214 *
4215 * So for now, allow inconsistent key up events to be dispatched.
4216 *
4217#if DEBUG_OUTBOUND_EVENT_DETAILS
4218 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4219 "keyCode=%d, scanCode=%d",
4220 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4221#endif
4222 return false;
4223 */
4224 return true;
4225 }
4226
4227 case AKEY_EVENT_ACTION_DOWN: {
4228 ssize_t index = findKeyMemento(entry);
4229 if (index >= 0) {
4230 mKeyMementos.removeAt(index);
4231 }
4232 addKeyMemento(entry, flags);
4233 return true;
4234 }
4235
4236 default:
4237 return true;
4238 }
4239}
4240
4241bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4242 int32_t action, int32_t flags) {
4243 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4244 switch (actionMasked) {
4245 case AMOTION_EVENT_ACTION_UP:
4246 case AMOTION_EVENT_ACTION_CANCEL: {
4247 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4248 if (index >= 0) {
4249 mMotionMementos.removeAt(index);
4250 return true;
4251 }
4252#if DEBUG_OUTBOUND_EVENT_DETAILS
4253 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004254 "displayId=%" PRId32 ", actionMasked=%d",
4255 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256#endif
4257 return false;
4258 }
4259
4260 case AMOTION_EVENT_ACTION_DOWN: {
4261 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4262 if (index >= 0) {
4263 mMotionMementos.removeAt(index);
4264 }
4265 addMotionMemento(entry, flags, false /*hovering*/);
4266 return true;
4267 }
4268
4269 case AMOTION_EVENT_ACTION_POINTER_UP:
4270 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4271 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004272 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4273 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4274 // generate cancellation events for these since they're based in relative rather than
4275 // absolute units.
4276 return true;
4277 }
4278
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004280
4281 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4282 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4283 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4284 // other value and we need to track the motion so we can send cancellation events for
4285 // anything generating fallback events (e.g. DPad keys for joystick movements).
4286 if (index >= 0) {
4287 if (entry->pointerCoords[0].isEmpty()) {
4288 mMotionMementos.removeAt(index);
4289 } else {
4290 MotionMemento& memento = mMotionMementos.editItemAt(index);
4291 memento.setPointers(entry);
4292 }
4293 } else if (!entry->pointerCoords[0].isEmpty()) {
4294 addMotionMemento(entry, flags, false /*hovering*/);
4295 }
4296
4297 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4298 return true;
4299 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 if (index >= 0) {
4301 MotionMemento& memento = mMotionMementos.editItemAt(index);
4302 memento.setPointers(entry);
4303 return true;
4304 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305#if DEBUG_OUTBOUND_EVENT_DETAILS
4306 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004307 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4308 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309#endif
4310 return false;
4311 }
4312
4313 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4314 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4315 if (index >= 0) {
4316 mMotionMementos.removeAt(index);
4317 return true;
4318 }
4319#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004320 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4321 "displayId=%" PRId32,
4322 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323#endif
4324 return false;
4325 }
4326
4327 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4328 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4329 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4330 if (index >= 0) {
4331 mMotionMementos.removeAt(index);
4332 }
4333 addMotionMemento(entry, flags, true /*hovering*/);
4334 return true;
4335 }
4336
4337 default:
4338 return true;
4339 }
4340}
4341
4342ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4343 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4344 const KeyMemento& memento = mKeyMementos.itemAt(i);
4345 if (memento.deviceId == entry->deviceId
4346 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004347 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 && memento.keyCode == entry->keyCode
4349 && memento.scanCode == entry->scanCode) {
4350 return i;
4351 }
4352 }
4353 return -1;
4354}
4355
4356ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4357 bool hovering) const {
4358 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4359 const MotionMemento& memento = mMotionMementos.itemAt(i);
4360 if (memento.deviceId == entry->deviceId
4361 && memento.source == entry->source
4362 && memento.displayId == entry->displayId
4363 && memento.hovering == hovering) {
4364 return i;
4365 }
4366 }
4367 return -1;
4368}
4369
4370void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4371 mKeyMementos.push();
4372 KeyMemento& memento = mKeyMementos.editTop();
4373 memento.deviceId = entry->deviceId;
4374 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004375 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 memento.keyCode = entry->keyCode;
4377 memento.scanCode = entry->scanCode;
4378 memento.metaState = entry->metaState;
4379 memento.flags = flags;
4380 memento.downTime = entry->downTime;
4381 memento.policyFlags = entry->policyFlags;
4382}
4383
4384void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4385 int32_t flags, bool hovering) {
4386 mMotionMementos.push();
4387 MotionMemento& memento = mMotionMementos.editTop();
4388 memento.deviceId = entry->deviceId;
4389 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004390 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 memento.flags = flags;
4392 memento.xPrecision = entry->xPrecision;
4393 memento.yPrecision = entry->yPrecision;
4394 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 memento.setPointers(entry);
4396 memento.hovering = hovering;
4397 memento.policyFlags = entry->policyFlags;
4398}
4399
4400void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4401 pointerCount = entry->pointerCount;
4402 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4403 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4404 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4405 }
4406}
4407
4408void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4409 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4410 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4411 const KeyMemento& memento = mKeyMementos.itemAt(i);
4412 if (shouldCancelKey(memento, options)) {
4413 outEvents.push(new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004414 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4416 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4417 }
4418 }
4419
4420 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4421 const MotionMemento& memento = mMotionMementos.itemAt(i);
4422 if (shouldCancelMotion(memento, options)) {
4423 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004424 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 memento.hovering
4426 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4427 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004428 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004429 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004430 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4431 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004432 }
4433 }
4434}
4435
4436void InputDispatcher::InputState::clear() {
4437 mKeyMementos.clear();
4438 mMotionMementos.clear();
4439 mFallbackKeys.clear();
4440}
4441
4442void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4443 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4444 const MotionMemento& memento = mMotionMementos.itemAt(i);
4445 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4446 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4447 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4448 if (memento.deviceId == otherMemento.deviceId
4449 && memento.source == otherMemento.source
4450 && memento.displayId == otherMemento.displayId) {
4451 other.mMotionMementos.removeAt(j);
4452 } else {
4453 j += 1;
4454 }
4455 }
4456 other.mMotionMementos.push(memento);
4457 }
4458 }
4459}
4460
4461int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4462 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4463 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4464}
4465
4466void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4467 int32_t fallbackKeyCode) {
4468 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4469 if (index >= 0) {
4470 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4471 } else {
4472 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4473 }
4474}
4475
4476void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4477 mFallbackKeys.removeItem(originalKeyCode);
4478}
4479
4480bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4481 const CancelationOptions& options) {
4482 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4483 return false;
4484 }
4485
4486 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4487 return false;
4488 }
4489
4490 switch (options.mode) {
4491 case CancelationOptions::CANCEL_ALL_EVENTS:
4492 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4493 return true;
4494 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4495 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4496 default:
4497 return false;
4498 }
4499}
4500
4501bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4502 const CancelationOptions& options) {
4503 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4504 return false;
4505 }
4506
4507 switch (options.mode) {
4508 case CancelationOptions::CANCEL_ALL_EVENTS:
4509 return true;
4510 case CancelationOptions::CANCEL_POINTER_EVENTS:
4511 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4512 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4513 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
4514 default:
4515 return false;
4516 }
4517}
4518
4519
4520// --- InputDispatcher::Connection ---
4521
4522InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4523 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4524 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4525 monitor(monitor),
4526 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4527}
4528
4529InputDispatcher::Connection::~Connection() {
4530}
4531
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004532const std::string InputDispatcher::Connection::getWindowName() const {
Yi Kong9b14ac62018-07-17 13:48:38 -07004533 if (inputWindowHandle != nullptr) {
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004534 return inputWindowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004535 }
4536 if (monitor) {
4537 return "monitor";
4538 }
4539 return "?";
4540}
4541
4542const char* InputDispatcher::Connection::getStatusLabel() const {
4543 switch (status) {
4544 case STATUS_NORMAL:
4545 return "NORMAL";
4546
4547 case STATUS_BROKEN:
4548 return "BROKEN";
4549
4550 case STATUS_ZOMBIE:
4551 return "ZOMBIE";
4552
4553 default:
4554 return "UNKNOWN";
4555 }
4556}
4557
4558InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004559 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004560 if (entry->seq == seq) {
4561 return entry;
4562 }
4563 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004564 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565}
4566
4567
4568// --- InputDispatcher::CommandEntry ---
4569
4570InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004571 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572 seq(0), handled(false) {
4573}
4574
4575InputDispatcher::CommandEntry::~CommandEntry() {
4576}
4577
4578
4579// --- InputDispatcher::TouchState ---
4580
4581InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004582 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583}
4584
4585InputDispatcher::TouchState::~TouchState() {
4586}
4587
4588void InputDispatcher::TouchState::reset() {
4589 down = false;
4590 split = false;
4591 deviceId = -1;
4592 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004593 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594 windows.clear();
4595}
4596
4597void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4598 down = other.down;
4599 split = other.split;
4600 deviceId = other.deviceId;
4601 source = other.source;
4602 displayId = other.displayId;
4603 windows = other.windows;
4604}
4605
4606void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4607 int32_t targetFlags, BitSet32 pointerIds) {
4608 if (targetFlags & InputTarget::FLAG_SPLIT) {
4609 split = true;
4610 }
4611
4612 for (size_t i = 0; i < windows.size(); i++) {
4613 TouchedWindow& touchedWindow = windows.editItemAt(i);
4614 if (touchedWindow.windowHandle == windowHandle) {
4615 touchedWindow.targetFlags |= targetFlags;
4616 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4617 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4618 }
4619 touchedWindow.pointerIds.value |= pointerIds.value;
4620 return;
4621 }
4622 }
4623
4624 windows.push();
4625
4626 TouchedWindow& touchedWindow = windows.editTop();
4627 touchedWindow.windowHandle = windowHandle;
4628 touchedWindow.targetFlags = targetFlags;
4629 touchedWindow.pointerIds = pointerIds;
4630}
4631
4632void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4633 for (size_t i = 0; i < windows.size(); i++) {
4634 if (windows.itemAt(i).windowHandle == windowHandle) {
4635 windows.removeAt(i);
4636 return;
4637 }
4638 }
4639}
4640
4641void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4642 for (size_t i = 0 ; i < windows.size(); ) {
4643 TouchedWindow& window = windows.editItemAt(i);
4644 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4645 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4646 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4647 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4648 i += 1;
4649 } else {
4650 windows.removeAt(i);
4651 }
4652 }
4653}
4654
4655sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4656 for (size_t i = 0; i < windows.size(); i++) {
4657 const TouchedWindow& window = windows.itemAt(i);
4658 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4659 return window.windowHandle;
4660 }
4661 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004662 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663}
4664
4665bool InputDispatcher::TouchState::isSlippery() const {
4666 // Must have exactly one foreground window.
4667 bool haveSlipperyForegroundWindow = false;
4668 for (size_t i = 0; i < windows.size(); i++) {
4669 const TouchedWindow& window = windows.itemAt(i);
4670 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4671 if (haveSlipperyForegroundWindow
4672 || !(window.windowHandle->getInfo()->layoutParamsFlags
4673 & InputWindowInfo::FLAG_SLIPPERY)) {
4674 return false;
4675 }
4676 haveSlipperyForegroundWindow = true;
4677 }
4678 }
4679 return haveSlipperyForegroundWindow;
4680}
4681
4682
4683// --- InputDispatcherThread ---
4684
4685InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4686 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4687}
4688
4689InputDispatcherThread::~InputDispatcherThread() {
4690}
4691
4692bool InputDispatcherThread::threadLoop() {
4693 mDispatcher->dispatchOnce();
4694 return true;
4695}
4696
4697} // namespace android