blob: a498fa154c4726636c4489a3655feb82641e3cb3 [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>
Robert Carr4e670e52018-08-15 13:26:12 -070061#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080062
63#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66#define INDENT4 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
72// Default input dispatching timeout if there is no focused application or paused window
73// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000074constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
76// Amount of time to allow for all pending events to be processed when an app switch
77// key is on the way. This is used to preempt input dispatch and drop input events
78// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000079constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080080
81// Amount of time to allow for an event to be dispatched (measured since its eventTime)
82// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000083constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow touch events to be streamed out to a connection before requiring
86// that the first event be finished. This value extends the ANR timeout by the specified
87// amount. For example, if streaming is allowed to get ahead by one second relative to the
88// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000089constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
91// 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 +000092constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
93
94// Log a warning when an interception call takes longer than this to process.
95constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
97// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
99
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100
101static inline nsecs_t now() {
102 return systemTime(SYSTEM_TIME_MONOTONIC);
103}
104
105static inline const char* toString(bool value) {
106 return value ? "true" : "false";
107}
108
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800109static std::string motionActionToString(int32_t action) {
110 // Convert MotionEvent action to string
111 switch(action & AMOTION_EVENT_ACTION_MASK) {
112 case AMOTION_EVENT_ACTION_DOWN:
113 return "DOWN";
114 case AMOTION_EVENT_ACTION_MOVE:
115 return "MOVE";
116 case AMOTION_EVENT_ACTION_UP:
117 return "UP";
118 case AMOTION_EVENT_ACTION_POINTER_DOWN:
119 return "POINTER_DOWN";
120 case AMOTION_EVENT_ACTION_POINTER_UP:
121 return "POINTER_UP";
122 }
123 return StringPrintf("%" PRId32, action);
124}
125
126static std::string keyActionToString(int32_t action) {
127 // Convert KeyEvent action to string
128 switch(action) {
129 case AKEY_EVENT_ACTION_DOWN:
130 return "DOWN";
131 case AKEY_EVENT_ACTION_UP:
132 return "UP";
133 case AKEY_EVENT_ACTION_MULTIPLE:
134 return "MULTIPLE";
135 }
136 return StringPrintf("%" PRId32, action);
137}
138
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
140 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
141 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
142}
143
144static bool isValidKeyAction(int32_t action) {
145 switch (action) {
146 case AKEY_EVENT_ACTION_DOWN:
147 case AKEY_EVENT_ACTION_UP:
148 return true;
149 default:
150 return false;
151 }
152}
153
154static bool validateKeyEvent(int32_t action) {
155 if (! isValidKeyAction(action)) {
156 ALOGE("Key event has invalid action code 0x%x", action);
157 return false;
158 }
159 return true;
160}
161
Michael Wright7b159c92015-05-14 14:48:03 +0100162static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800163 switch (action & AMOTION_EVENT_ACTION_MASK) {
164 case AMOTION_EVENT_ACTION_DOWN:
165 case AMOTION_EVENT_ACTION_UP:
166 case AMOTION_EVENT_ACTION_CANCEL:
167 case AMOTION_EVENT_ACTION_MOVE:
168 case AMOTION_EVENT_ACTION_OUTSIDE:
169 case AMOTION_EVENT_ACTION_HOVER_ENTER:
170 case AMOTION_EVENT_ACTION_HOVER_MOVE:
171 case AMOTION_EVENT_ACTION_HOVER_EXIT:
172 case AMOTION_EVENT_ACTION_SCROLL:
173 return true;
174 case AMOTION_EVENT_ACTION_POINTER_DOWN:
175 case AMOTION_EVENT_ACTION_POINTER_UP: {
176 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800177 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800178 }
Michael Wright7b159c92015-05-14 14:48:03 +0100179 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
180 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
181 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800182 default:
183 return false;
184 }
185}
186
Michael Wright7b159c92015-05-14 14:48:03 +0100187static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800188 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100189 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190 ALOGE("Motion event has invalid action code 0x%x", action);
191 return false;
192 }
193 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000194 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 pointerCount, MAX_POINTERS);
196 return false;
197 }
198 BitSet32 pointerIdBits;
199 for (size_t i = 0; i < pointerCount; i++) {
200 int32_t id = pointerProperties[i].id;
201 if (id < 0 || id > MAX_POINTER_ID) {
202 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
203 id, MAX_POINTER_ID);
204 return false;
205 }
206 if (pointerIdBits.hasBit(id)) {
207 ALOGE("Motion event has duplicate pointer id %d", id);
208 return false;
209 }
210 pointerIdBits.markBit(id);
211 }
212 return true;
213}
214
215static bool isMainDisplay(int32_t displayId) {
216 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
217}
218
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800219static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800221 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 return;
223 }
224
225 bool first = true;
226 Region::const_iterator cur = region.begin();
227 Region::const_iterator const tail = region.end();
228 while (cur != tail) {
229 if (first) {
230 first = false;
231 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800232 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800234 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800235 cur++;
236 }
237}
238
Tiger Huang721e26f2018-07-24 22:26:19 +0800239template<typename T, typename U>
240static T getValueByKey(std::unordered_map<U, T>& map, U key) {
241 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
242 return it != map.end() ? it->second : T{};
243}
244
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245
246// --- InputDispatcher ---
247
248InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
249 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700250 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100251 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700252 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800254 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
256 mLooper = new Looper(false);
257
Yi Kong9b14ac62018-07-17 13:48:38 -0700258 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259
260 policy->getDispatcherConfiguration(&mConfig);
261}
262
263InputDispatcher::~InputDispatcher() {
264 { // acquire lock
265 AutoMutex _l(mLock);
266
267 resetKeyRepeatLocked();
268 releasePendingEventLocked();
269 drainInboundQueueLocked();
270 }
271
272 while (mConnectionsByFd.size() != 0) {
273 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
274 }
275}
276
277void InputDispatcher::dispatchOnce() {
278 nsecs_t nextWakeupTime = LONG_LONG_MAX;
279 { // acquire lock
280 AutoMutex _l(mLock);
281 mDispatcherIsAliveCondition.broadcast();
282
283 // Run a dispatch loop if there are no pending commands.
284 // The dispatch loop might enqueue commands to run afterwards.
285 if (!haveCommandsLocked()) {
286 dispatchOnceInnerLocked(&nextWakeupTime);
287 }
288
289 // Run all pending commands if there are any.
290 // If any commands were run then force the next poll to wake up immediately.
291 if (runCommandsLockedInterruptible()) {
292 nextWakeupTime = LONG_LONG_MIN;
293 }
294 } // release lock
295
296 // Wait for callback or timeout or wake. (make sure we round up, not down)
297 nsecs_t currentTime = now();
298 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
299 mLooper->pollOnce(timeoutMillis);
300}
301
302void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
303 nsecs_t currentTime = now();
304
Jeff Browndc5992e2014-04-11 01:27:26 -0700305 // Reset the key repeat timer whenever normal dispatch is suspended while the
306 // device is in a non-interactive state. This is to ensure that we abort a key
307 // repeat if the device is just coming out of sleep.
308 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800309 resetKeyRepeatLocked();
310 }
311
312 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
313 if (mDispatchFrozen) {
314#if DEBUG_FOCUS
315 ALOGD("Dispatch frozen. Waiting some more.");
316#endif
317 return;
318 }
319
320 // Optimize latency of app switches.
321 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
322 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
323 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
324 if (mAppSwitchDueTime < *nextWakeupTime) {
325 *nextWakeupTime = mAppSwitchDueTime;
326 }
327
328 // Ready to start a new event.
329 // If we don't already have a pending event, go grab one.
330 if (! mPendingEvent) {
331 if (mInboundQueue.isEmpty()) {
332 if (isAppSwitchDue) {
333 // The inbound queue is empty so the app switch key we were waiting
334 // for will never arrive. Stop waiting for it.
335 resetPendingAppSwitchLocked(false);
336 isAppSwitchDue = false;
337 }
338
339 // Synthesize a key repeat if appropriate.
340 if (mKeyRepeatState.lastKeyEntry) {
341 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
342 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
343 } else {
344 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
345 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
346 }
347 }
348 }
349
350 // Nothing to do if there is no pending event.
351 if (!mPendingEvent) {
352 return;
353 }
354 } else {
355 // Inbound queue has at least one entry.
356 mPendingEvent = mInboundQueue.dequeueAtHead();
357 traceInboundQueueLengthLocked();
358 }
359
360 // Poke user activity for this event.
361 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
362 pokeUserActivityLocked(mPendingEvent);
363 }
364
365 // Get ready to dispatch the event.
366 resetANRTimeoutsLocked();
367 }
368
369 // Now we have an event to dispatch.
370 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700371 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372 bool done = false;
373 DropReason dropReason = DROP_REASON_NOT_DROPPED;
374 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
375 dropReason = DROP_REASON_POLICY;
376 } else if (!mDispatchEnabled) {
377 dropReason = DROP_REASON_DISABLED;
378 }
379
380 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700381 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800382 }
383
384 switch (mPendingEvent->type) {
385 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
386 ConfigurationChangedEntry* typedEntry =
387 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
388 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
389 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
390 break;
391 }
392
393 case EventEntry::TYPE_DEVICE_RESET: {
394 DeviceResetEntry* typedEntry =
395 static_cast<DeviceResetEntry*>(mPendingEvent);
396 done = dispatchDeviceResetLocked(currentTime, typedEntry);
397 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
398 break;
399 }
400
401 case EventEntry::TYPE_KEY: {
402 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
403 if (isAppSwitchDue) {
404 if (isAppSwitchKeyEventLocked(typedEntry)) {
405 resetPendingAppSwitchLocked(true);
406 isAppSwitchDue = false;
407 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
408 dropReason = DROP_REASON_APP_SWITCH;
409 }
410 }
411 if (dropReason == DROP_REASON_NOT_DROPPED
412 && isStaleEventLocked(currentTime, typedEntry)) {
413 dropReason = DROP_REASON_STALE;
414 }
415 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
416 dropReason = DROP_REASON_BLOCKED;
417 }
418 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
419 break;
420 }
421
422 case EventEntry::TYPE_MOTION: {
423 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
424 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
425 dropReason = DROP_REASON_APP_SWITCH;
426 }
427 if (dropReason == DROP_REASON_NOT_DROPPED
428 && isStaleEventLocked(currentTime, typedEntry)) {
429 dropReason = DROP_REASON_STALE;
430 }
431 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
432 dropReason = DROP_REASON_BLOCKED;
433 }
434 done = dispatchMotionLocked(currentTime, typedEntry,
435 &dropReason, nextWakeupTime);
436 break;
437 }
438
439 default:
440 ALOG_ASSERT(false);
441 break;
442 }
443
444 if (done) {
445 if (dropReason != DROP_REASON_NOT_DROPPED) {
446 dropInboundEventLocked(mPendingEvent, dropReason);
447 }
Michael Wright3a981722015-06-10 15:26:13 +0100448 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449
450 releasePendingEventLocked();
451 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
452 }
453}
454
455bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
456 bool needWake = mInboundQueue.isEmpty();
457 mInboundQueue.enqueueAtTail(entry);
458 traceInboundQueueLengthLocked();
459
460 switch (entry->type) {
461 case EventEntry::TYPE_KEY: {
462 // Optimize app switch latency.
463 // If the application takes too long to catch up then we drop all events preceding
464 // the app switch key.
465 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
466 if (isAppSwitchKeyEventLocked(keyEntry)) {
467 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
468 mAppSwitchSawKeyDown = true;
469 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
470 if (mAppSwitchSawKeyDown) {
471#if DEBUG_APP_SWITCH
472 ALOGD("App switch is pending!");
473#endif
474 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
475 mAppSwitchSawKeyDown = false;
476 needWake = true;
477 }
478 }
479 }
480 break;
481 }
482
483 case EventEntry::TYPE_MOTION: {
484 // Optimize case where the current application is unresponsive and the user
485 // decides to touch a window in a different application.
486 // If the application takes too long to catch up then we drop all events preceding
487 // the touch into the other window.
488 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
489 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
490 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
491 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Robert Carr740167f2018-10-11 19:03:41 -0700492 && mInputTargetWaitApplicationToken != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 int32_t displayId = motionEntry->displayId;
494 int32_t x = int32_t(motionEntry->pointerCoords[0].
495 getAxisValue(AMOTION_EVENT_AXIS_X));
496 int32_t y = int32_t(motionEntry->pointerCoords[0].
497 getAxisValue(AMOTION_EVENT_AXIS_Y));
498 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700499 if (touchedWindowHandle != nullptr
Robert Carr740167f2018-10-11 19:03:41 -0700500 && touchedWindowHandle->getApplicationToken()
501 != mInputTargetWaitApplicationToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 // User touched a different application than the one we are waiting on.
503 // Flag the event, and start pruning the input queue.
504 mNextUnblockedEvent = motionEntry;
505 needWake = true;
506 }
507 }
508 break;
509 }
510 }
511
512 return needWake;
513}
514
515void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
516 entry->refCount += 1;
517 mRecentQueue.enqueueAtTail(entry);
518 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
519 mRecentQueue.dequeueAtHead()->release();
520 }
521}
522
523sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
524 int32_t x, int32_t y) {
525 // Traverse windows from front to back to find touched window.
Arthur Hungb92218b2018-08-14 12:00:21 +0800526 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
527 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800529 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 const InputWindowInfo* windowInfo = windowHandle->getInfo();
531 if (windowInfo->displayId == displayId) {
532 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533
534 if (windowInfo->visible) {
535 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
536 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
537 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
538 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
539 // Found window.
540 return windowHandle;
541 }
542 }
543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 }
545 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700546 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547}
548
549void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
550 const char* reason;
551 switch (dropReason) {
552 case DROP_REASON_POLICY:
553#if DEBUG_INBOUND_EVENT_DETAILS
554 ALOGD("Dropped event because policy consumed it.");
555#endif
556 reason = "inbound event was dropped because the policy consumed it";
557 break;
558 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100559 if (mLastDropReason != DROP_REASON_DISABLED) {
560 ALOGI("Dropped event because input dispatch is disabled.");
561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 reason = "inbound event was dropped because input dispatch is disabled";
563 break;
564 case DROP_REASON_APP_SWITCH:
565 ALOGI("Dropped event because of pending overdue app switch.");
566 reason = "inbound event was dropped because of pending overdue app switch";
567 break;
568 case DROP_REASON_BLOCKED:
569 ALOGI("Dropped event because the current application is not responding and the user "
570 "has started interacting with a different application.");
571 reason = "inbound event was dropped because the current application is not responding "
572 "and the user has started interacting with a different application";
573 break;
574 case DROP_REASON_STALE:
575 ALOGI("Dropped event because it is stale.");
576 reason = "inbound event was dropped because it is stale";
577 break;
578 default:
579 ALOG_ASSERT(false);
580 return;
581 }
582
583 switch (entry->type) {
584 case EventEntry::TYPE_KEY: {
585 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
586 synthesizeCancelationEventsForAllConnectionsLocked(options);
587 break;
588 }
589 case EventEntry::TYPE_MOTION: {
590 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
591 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
592 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
593 synthesizeCancelationEventsForAllConnectionsLocked(options);
594 } else {
595 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
596 synthesizeCancelationEventsForAllConnectionsLocked(options);
597 }
598 break;
599 }
600 }
601}
602
603bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
604 return keyCode == AKEYCODE_HOME
605 || keyCode == AKEYCODE_ENDCALL
606 || keyCode == AKEYCODE_APP_SWITCH;
607}
608
609bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
610 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
611 && isAppSwitchKeyCode(keyEntry->keyCode)
612 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
613 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
614}
615
616bool InputDispatcher::isAppSwitchPendingLocked() {
617 return mAppSwitchDueTime != LONG_LONG_MAX;
618}
619
620void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
621 mAppSwitchDueTime = LONG_LONG_MAX;
622
623#if DEBUG_APP_SWITCH
624 if (handled) {
625 ALOGD("App switch has arrived.");
626 } else {
627 ALOGD("App switch was abandoned.");
628 }
629#endif
630}
631
632bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
633 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
634}
635
636bool InputDispatcher::haveCommandsLocked() const {
637 return !mCommandQueue.isEmpty();
638}
639
640bool InputDispatcher::runCommandsLockedInterruptible() {
641 if (mCommandQueue.isEmpty()) {
642 return false;
643 }
644
645 do {
646 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
647
648 Command command = commandEntry->command;
649 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
650
651 commandEntry->connection.clear();
652 delete commandEntry;
653 } while (! mCommandQueue.isEmpty());
654 return true;
655}
656
657InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
658 CommandEntry* commandEntry = new CommandEntry(command);
659 mCommandQueue.enqueueAtTail(commandEntry);
660 return commandEntry;
661}
662
663void InputDispatcher::drainInboundQueueLocked() {
664 while (! mInboundQueue.isEmpty()) {
665 EventEntry* entry = mInboundQueue.dequeueAtHead();
666 releaseInboundEventLocked(entry);
667 }
668 traceInboundQueueLengthLocked();
669}
670
671void InputDispatcher::releasePendingEventLocked() {
672 if (mPendingEvent) {
673 resetANRTimeoutsLocked();
674 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700675 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 }
677}
678
679void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
680 InjectionState* injectionState = entry->injectionState;
681 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
682#if DEBUG_DISPATCH_CYCLE
683 ALOGD("Injected inbound event was dropped.");
684#endif
685 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
686 }
687 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700688 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 }
690 addRecentEventLocked(entry);
691 entry->release();
692}
693
694void InputDispatcher::resetKeyRepeatLocked() {
695 if (mKeyRepeatState.lastKeyEntry) {
696 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700697 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
699}
700
701InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
702 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
703
704 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700705 uint32_t policyFlags = entry->policyFlags &
706 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 if (entry->refCount == 1) {
708 entry->recycle();
709 entry->eventTime = currentTime;
710 entry->policyFlags = policyFlags;
711 entry->repeatCount += 1;
712 } else {
713 KeyEntry* newEntry = new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100714 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 entry->action, entry->flags, entry->keyCode, entry->scanCode,
716 entry->metaState, entry->repeatCount + 1, entry->downTime);
717
718 mKeyRepeatState.lastKeyEntry = newEntry;
719 entry->release();
720
721 entry = newEntry;
722 }
723 entry->syntheticRepeat = true;
724
725 // Increment reference count since we keep a reference to the event in
726 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
727 entry->refCount += 1;
728
729 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
730 return entry;
731}
732
733bool InputDispatcher::dispatchConfigurationChangedLocked(
734 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
735#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700736 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737#endif
738
739 // Reset key repeating in case a keyboard device was added or removed or something.
740 resetKeyRepeatLocked();
741
742 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
743 CommandEntry* commandEntry = postCommandLocked(
744 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
745 commandEntry->eventTime = entry->eventTime;
746 return true;
747}
748
749bool InputDispatcher::dispatchDeviceResetLocked(
750 nsecs_t currentTime, DeviceResetEntry* entry) {
751#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700752 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
753 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754#endif
755
756 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
757 "device was reset");
758 options.deviceId = entry->deviceId;
759 synthesizeCancelationEventsForAllConnectionsLocked(options);
760 return true;
761}
762
763bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
764 DropReason* dropReason, nsecs_t* nextWakeupTime) {
765 // Preprocessing.
766 if (! entry->dispatchInProgress) {
767 if (entry->repeatCount == 0
768 && entry->action == AKEY_EVENT_ACTION_DOWN
769 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
770 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
771 if (mKeyRepeatState.lastKeyEntry
772 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
773 // We have seen two identical key downs in a row which indicates that the device
774 // driver is automatically generating key repeats itself. We take note of the
775 // repeat here, but we disable our own next key repeat timer since it is clear that
776 // we will not need to synthesize key repeats ourselves.
777 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
778 resetKeyRepeatLocked();
779 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
780 } else {
781 // Not a repeat. Save key down state in case we do see a repeat later.
782 resetKeyRepeatLocked();
783 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
784 }
785 mKeyRepeatState.lastKeyEntry = entry;
786 entry->refCount += 1;
787 } else if (! entry->syntheticRepeat) {
788 resetKeyRepeatLocked();
789 }
790
791 if (entry->repeatCount == 1) {
792 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
793 } else {
794 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
795 }
796
797 entry->dispatchInProgress = true;
798
799 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
800 }
801
802 // Handle case where the policy asked us to try again later last time.
803 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
804 if (currentTime < entry->interceptKeyWakeupTime) {
805 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
806 *nextWakeupTime = entry->interceptKeyWakeupTime;
807 }
808 return false; // wait until next wakeup
809 }
810 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
811 entry->interceptKeyWakeupTime = 0;
812 }
813
814 // Give the policy a chance to intercept the key.
815 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
816 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
817 CommandEntry* commandEntry = postCommandLocked(
818 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800819 sp<InputWindowHandle> focusedWindowHandle =
820 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
821 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700822 commandEntry->inputChannel =
823 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 }
825 commandEntry->keyEntry = entry;
826 entry->refCount += 1;
827 return false; // wait for the command to run
828 } else {
829 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
830 }
831 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
832 if (*dropReason == DROP_REASON_NOT_DROPPED) {
833 *dropReason = DROP_REASON_POLICY;
834 }
835 }
836
837 // Clean up if dropping the event.
838 if (*dropReason != DROP_REASON_NOT_DROPPED) {
839 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
840 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
841 return true;
842 }
843
844 // Identify targets.
845 Vector<InputTarget> inputTargets;
846 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
847 entry, inputTargets, nextWakeupTime);
848 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
849 return false;
850 }
851
852 setInjectionResultLocked(entry, injectionResult);
853 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
854 return true;
855 }
856
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800857 // Add monitor channels from event's or focused display.
858 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859
860 // Dispatch the key.
861 dispatchEventLocked(currentTime, entry, inputTargets);
862 return true;
863}
864
865void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
866#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100867 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
868 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800869 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100871 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800873 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874#endif
875}
876
877bool InputDispatcher::dispatchMotionLocked(
878 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
879 // Preprocessing.
880 if (! entry->dispatchInProgress) {
881 entry->dispatchInProgress = true;
882
883 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
884 }
885
886 // Clean up if dropping the event.
887 if (*dropReason != DROP_REASON_NOT_DROPPED) {
888 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
889 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
890 return true;
891 }
892
893 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
894
895 // Identify targets.
896 Vector<InputTarget> inputTargets;
897
898 bool conflictingPointerActions = false;
899 int32_t injectionResult;
900 if (isPointerEvent) {
901 // Pointer event. (eg. touchscreen)
902 injectionResult = findTouchedWindowTargetsLocked(currentTime,
903 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
904 } else {
905 // Non touch event. (eg. trackball)
906 injectionResult = findFocusedWindowTargetsLocked(currentTime,
907 entry, inputTargets, nextWakeupTime);
908 }
909 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
910 return false;
911 }
912
913 setInjectionResultLocked(entry, injectionResult);
914 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100915 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
916 CancelationOptions::Mode mode(isPointerEvent ?
917 CancelationOptions::CANCEL_POINTER_EVENTS :
918 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
919 CancelationOptions options(mode, "input event injection failed");
920 synthesizeCancelationEventsForMonitorsLocked(options);
921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 return true;
923 }
924
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800925 // Add monitor channels from event's or focused display.
926 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927
928 // Dispatch the motion.
929 if (conflictingPointerActions) {
930 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
931 "conflicting pointer actions");
932 synthesizeCancelationEventsForAllConnectionsLocked(options);
933 }
934 dispatchEventLocked(currentTime, entry, inputTargets);
935 return true;
936}
937
938
939void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
940#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800941 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
942 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100943 "action=0x%x, actionButton=0x%x, flags=0x%x, "
944 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800945 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800947 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100948 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 entry->metaState, entry->buttonState,
950 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800951 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952
953 for (uint32_t i = 0; i < entry->pointerCount; i++) {
954 ALOGD(" Pointer %d: id=%d, toolType=%d, "
955 "x=%f, y=%f, pressure=%f, size=%f, "
956 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800957 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958 i, entry->pointerProperties[i].id,
959 entry->pointerProperties[i].toolType,
960 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
961 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
962 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
963 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
964 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
965 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
966 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
967 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800968 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 }
970#endif
971}
972
973void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
974 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
975#if DEBUG_DISPATCH_CYCLE
976 ALOGD("dispatchEventToCurrentInputTargets");
977#endif
978
979 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
980
981 pokeUserActivityLocked(eventEntry);
982
983 for (size_t i = 0; i < inputTargets.size(); i++) {
984 const InputTarget& inputTarget = inputTargets.itemAt(i);
985
986 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
987 if (connectionIndex >= 0) {
988 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
989 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
990 } else {
991#if DEBUG_FOCUS
992 ALOGD("Dropping event delivery to target with channel '%s' because it "
993 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800994 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995#endif
996 }
997 }
998}
999
1000int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1001 const EventEntry* entry,
1002 const sp<InputApplicationHandle>& applicationHandle,
1003 const sp<InputWindowHandle>& windowHandle,
1004 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001005 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1007#if DEBUG_FOCUS
1008 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1009#endif
1010 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1011 mInputTargetWaitStartTime = currentTime;
1012 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1013 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001014 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 }
1016 } else {
1017 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1018#if DEBUG_FOCUS
1019 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001020 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 reason);
1022#endif
1023 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001024 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001026 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 timeout = applicationHandle->getDispatchingTimeout(
1028 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1029 } else {
1030 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1031 }
1032
1033 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1034 mInputTargetWaitStartTime = currentTime;
1035 mInputTargetWaitTimeoutTime = currentTime + timeout;
1036 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001037 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038
Yi Kong9b14ac62018-07-17 13:48:38 -07001039 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001040 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 }
Robert Carr740167f2018-10-11 19:03:41 -07001042 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1043 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 }
1045 }
1046 }
1047
1048 if (mInputTargetWaitTimeoutExpired) {
1049 return INPUT_EVENT_INJECTION_TIMED_OUT;
1050 }
1051
1052 if (currentTime >= mInputTargetWaitTimeoutTime) {
1053 onANRLocked(currentTime, applicationHandle, windowHandle,
1054 entry->eventTime, mInputTargetWaitStartTime, reason);
1055
1056 // Force poll loop to wake up immediately on next iteration once we get the
1057 // ANR response back from the policy.
1058 *nextWakeupTime = LONG_LONG_MIN;
1059 return INPUT_EVENT_INJECTION_PENDING;
1060 } else {
1061 // Force poll loop to wake up when timeout is due.
1062 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1063 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1064 }
1065 return INPUT_EVENT_INJECTION_PENDING;
1066 }
1067}
1068
Robert Carr803535b2018-08-02 16:38:15 -07001069void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1070 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1071 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1072 state.removeWindowByToken(token);
1073 }
1074}
1075
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1077 const sp<InputChannel>& inputChannel) {
1078 if (newTimeout > 0) {
1079 // Extend the timeout.
1080 mInputTargetWaitTimeoutTime = now() + newTimeout;
1081 } else {
1082 // Give up.
1083 mInputTargetWaitTimeoutExpired = true;
1084
1085 // Input state will not be realistic. Mark it out of sync.
1086 if (inputChannel.get()) {
1087 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1088 if (connectionIndex >= 0) {
1089 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001090 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091
Robert Carr803535b2018-08-02 16:38:15 -07001092 if (token != nullptr) {
1093 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 }
1095
1096 if (connection->status == Connection::STATUS_NORMAL) {
1097 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1098 "application not responding");
1099 synthesizeCancelationEventsForConnectionLocked(connection, options);
1100 }
1101 }
1102 }
1103 }
1104}
1105
1106nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1107 nsecs_t currentTime) {
1108 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1109 return currentTime - mInputTargetWaitStartTime;
1110 }
1111 return 0;
1112}
1113
1114void InputDispatcher::resetANRTimeoutsLocked() {
1115#if DEBUG_FOCUS
1116 ALOGD("Resetting ANR timeouts.");
1117#endif
1118
1119 // Reset input target wait timeout.
1120 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001121 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122}
1123
Tiger Huang721e26f2018-07-24 22:26:19 +08001124/**
1125 * Get the display id that the given event should go to. If this event specifies a valid display id,
1126 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1127 * Focused display is the display that the user most recently interacted with.
1128 */
1129int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1130 int32_t displayId;
1131 switch (entry->type) {
1132 case EventEntry::TYPE_KEY: {
1133 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1134 displayId = typedEntry->displayId;
1135 break;
1136 }
1137 case EventEntry::TYPE_MOTION: {
1138 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1139 displayId = typedEntry->displayId;
1140 break;
1141 }
1142 default: {
1143 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1144 return ADISPLAY_ID_NONE;
1145 }
1146 }
1147 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1148}
1149
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1151 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1152 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001153 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154
Tiger Huang721e26f2018-07-24 22:26:19 +08001155 int32_t displayId = getTargetDisplayId(entry);
1156 sp<InputWindowHandle> focusedWindowHandle =
1157 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1158 sp<InputApplicationHandle> focusedApplicationHandle =
1159 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1160
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 // If there is no currently focused window and no focused application
1162 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001163 if (focusedWindowHandle == nullptr) {
1164 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001166 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 "Waiting because no window has focus but there is a "
1168 "focused application that may eventually add a window "
1169 "when it finishes starting up.");
1170 goto Unresponsive;
1171 }
1172
Arthur Hung3b413f22018-10-26 18:05:34 +08001173 ALOGI("Dropping event because there is no focused window or focused application in display "
1174 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1176 goto Failed;
1177 }
1178
1179 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001180 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1182 goto Failed;
1183 }
1184
Jeff Brownffb49772014-10-10 19:01:34 -07001185 // Check whether the window is ready for more input.
1186 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001187 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001188 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001190 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 goto Unresponsive;
1192 }
1193
1194 // Success! Output targets.
1195 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001196 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1198 inputTargets);
1199
1200 // Done.
1201Failed:
1202Unresponsive:
1203 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1204 updateDispatchStatisticsLocked(currentTime, entry,
1205 injectionResult, timeSpentWaitingForApplication);
1206#if DEBUG_FOCUS
1207 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1208 "timeSpentWaitingForApplication=%0.1fms",
1209 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1210#endif
1211 return injectionResult;
1212}
1213
1214int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1215 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1216 bool* outConflictingPointerActions) {
1217 enum InjectionPermission {
1218 INJECTION_PERMISSION_UNKNOWN,
1219 INJECTION_PERMISSION_GRANTED,
1220 INJECTION_PERMISSION_DENIED
1221 };
1222
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 // For security reasons, we defer updating the touch state until we are sure that
1224 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 int32_t displayId = entry->displayId;
1226 int32_t action = entry->action;
1227 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1228
1229 // Update the touch state as needed based on the properties of the touch event.
1230 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1231 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1232 sp<InputWindowHandle> newHoverWindowHandle;
1233
Jeff Brownf086ddb2014-02-11 14:28:48 -08001234 // Copy current touch state into mTempTouchState.
1235 // This state is always reset at the end of this function, so if we don't find state
1236 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001237 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001238 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1239 if (oldStateIndex >= 0) {
1240 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1241 mTempTouchState.copyFrom(*oldState);
1242 }
1243
1244 bool isSplit = mTempTouchState.split;
1245 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1246 && (mTempTouchState.deviceId != entry->deviceId
1247 || mTempTouchState.source != entry->source
1248 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1250 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1251 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1252 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1253 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1254 || isHoverAction);
1255 bool wrongDevice = false;
1256 if (newGesture) {
1257 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001258 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001260 ALOGD("Dropping event because a pointer for a different device is already down "
1261 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001263 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1265 switchedDevice = false;
1266 wrongDevice = true;
1267 goto Failed;
1268 }
1269 mTempTouchState.reset();
1270 mTempTouchState.down = down;
1271 mTempTouchState.deviceId = entry->deviceId;
1272 mTempTouchState.source = entry->source;
1273 mTempTouchState.displayId = displayId;
1274 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001275 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1276#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001277 ALOGI("Dropping move event because a pointer for a different device is already active "
1278 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001279#endif
1280 // TODO: test multiple simultaneous input streams.
1281 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1282 switchedDevice = false;
1283 wrongDevice = true;
1284 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285 }
1286
1287 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1288 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1289
1290 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1291 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1292 getAxisValue(AMOTION_EVENT_AXIS_X));
1293 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1294 getAxisValue(AMOTION_EVENT_AXIS_Y));
1295 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 bool isTouchModal = false;
1297
1298 // Traverse windows from front to back to find touched window and outside targets.
Arthur Hungb92218b2018-08-14 12:00:21 +08001299 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1300 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001302 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1304 if (windowInfo->displayId != displayId) {
1305 continue; // wrong display
1306 }
1307
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 int32_t flags = windowInfo->layoutParamsFlags;
1309 if (windowInfo->visible) {
1310 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1311 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1312 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1313 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001314 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 break; // found touched window, exit window loop
1316 }
1317 }
1318
1319 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1320 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001322 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 }
1324 }
1325 }
1326
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001328 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1330 // New window supports splitting.
1331 isSplit = true;
1332 } else if (isSplit) {
1333 // New window does not support splitting but we have already split events.
1334 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001335 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001336 }
1337
1338 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001339 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 // Try to assign the pointer to the first foreground window we find, if there is one.
1341 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001342 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001343 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1344 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1346 goto Failed;
1347 }
1348 }
1349
1350 // Set target flags.
1351 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1352 if (isSplit) {
1353 targetFlags |= InputTarget::FLAG_SPLIT;
1354 }
1355 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1356 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001357 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1358 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 }
1360
1361 // Update hover state.
1362 if (isHoverAction) {
1363 newHoverWindowHandle = newTouchedWindowHandle;
1364 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1365 newHoverWindowHandle = mLastHoverWindowHandle;
1366 }
1367
1368 // Update the temporary touch state.
1369 BitSet32 pointerIds;
1370 if (isSplit) {
1371 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1372 pointerIds.markBit(pointerId);
1373 }
1374 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1375 } else {
1376 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1377
1378 // If the pointer is not currently down, then ignore the event.
1379 if (! mTempTouchState.down) {
1380#if DEBUG_FOCUS
1381 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001382 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383#endif
1384 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1385 goto Failed;
1386 }
1387
1388 // Check whether touches should slip outside of the current foreground window.
1389 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1390 && entry->pointerCount == 1
1391 && mTempTouchState.isSlippery()) {
1392 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1393 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1394
1395 sp<InputWindowHandle> oldTouchedWindowHandle =
1396 mTempTouchState.getFirstForegroundWindowHandle();
1397 sp<InputWindowHandle> newTouchedWindowHandle =
1398 findTouchedWindowAtLocked(displayId, x, y);
1399 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001400 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001402 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001403 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001404 newTouchedWindowHandle->getName().c_str(),
1405 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406#endif
1407 // Make a slippery exit from the old window.
1408 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1409 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1410
1411 // Make a slippery entrance into the new window.
1412 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1413 isSplit = true;
1414 }
1415
1416 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1417 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1418 if (isSplit) {
1419 targetFlags |= InputTarget::FLAG_SPLIT;
1420 }
1421 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1422 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1423 }
1424
1425 BitSet32 pointerIds;
1426 if (isSplit) {
1427 pointerIds.markBit(entry->pointerProperties[0].id);
1428 }
1429 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1430 }
1431 }
1432 }
1433
1434 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1435 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001436 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437#if DEBUG_HOVER
1438 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001439 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440#endif
1441 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1442 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1443 }
1444
1445 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001446 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447#if DEBUG_HOVER
1448 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001449 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450#endif
1451 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1452 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1453 }
1454 }
1455
1456 // Check permission to inject into all touched foreground windows and ensure there
1457 // is at least one touched foreground window.
1458 {
1459 bool haveForegroundWindow = false;
1460 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1461 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1462 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1463 haveForegroundWindow = true;
1464 if (! checkInjectionPermission(touchedWindow.windowHandle,
1465 entry->injectionState)) {
1466 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1467 injectionPermission = INJECTION_PERMISSION_DENIED;
1468 goto Failed;
1469 }
1470 }
1471 }
1472 if (! haveForegroundWindow) {
1473#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001474 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1475 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476#endif
1477 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1478 goto Failed;
1479 }
1480
1481 // Permission granted to injection into all touched foreground windows.
1482 injectionPermission = INJECTION_PERMISSION_GRANTED;
1483 }
1484
1485 // Check whether windows listening for outside touches are owned by the same UID. If it is
1486 // set the policy flag that we will not reveal coordinate information to this window.
1487 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1488 sp<InputWindowHandle> foregroundWindowHandle =
1489 mTempTouchState.getFirstForegroundWindowHandle();
1490 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1491 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1492 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1493 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1494 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1495 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1496 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1497 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1498 }
1499 }
1500 }
1501 }
1502
1503 // Ensure all touched foreground windows are ready for new input.
1504 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1505 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1506 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001507 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001508 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001509 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001510 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001512 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 goto Unresponsive;
1514 }
1515 }
1516 }
1517
1518 // If this is the first pointer going down and the touched window has a wallpaper
1519 // then also add the touched wallpaper windows so they are locked in for the duration
1520 // of the touch gesture.
1521 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1522 // engine only supports touch events. We would need to add a mechanism similar
1523 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1524 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1525 sp<InputWindowHandle> foregroundWindowHandle =
1526 mTempTouchState.getFirstForegroundWindowHandle();
1527 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001528 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1529 size_t numWindows = windowHandles.size();
1530 for (size_t i = 0; i < numWindows; i++) {
1531 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 const InputWindowInfo* info = windowHandle->getInfo();
1533 if (info->displayId == displayId
1534 && windowHandle->getInfo()->layoutParamsType
1535 == InputWindowInfo::TYPE_WALLPAPER) {
1536 mTempTouchState.addOrUpdateWindow(windowHandle,
1537 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001538 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 | InputTarget::FLAG_DISPATCH_AS_IS,
1540 BitSet32(0));
1541 }
1542 }
1543 }
1544 }
1545
1546 // Success! Output targets.
1547 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1548
1549 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1550 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1551 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1552 touchedWindow.pointerIds, inputTargets);
1553 }
1554
1555 // Drop the outside or hover touch windows since we will not care about them
1556 // in the next iteration.
1557 mTempTouchState.filterNonAsIsTouchWindows();
1558
1559Failed:
1560 // Check injection permission once and for all.
1561 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001562 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 injectionPermission = INJECTION_PERMISSION_GRANTED;
1564 } else {
1565 injectionPermission = INJECTION_PERMISSION_DENIED;
1566 }
1567 }
1568
1569 // Update final pieces of touch state if the injector had permission.
1570 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1571 if (!wrongDevice) {
1572 if (switchedDevice) {
1573#if DEBUG_FOCUS
1574 ALOGD("Conflicting pointer actions: Switched to a different device.");
1575#endif
1576 *outConflictingPointerActions = true;
1577 }
1578
1579 if (isHoverAction) {
1580 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001581 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582#if DEBUG_FOCUS
1583 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1584#endif
1585 *outConflictingPointerActions = true;
1586 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001587 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1589 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001590 mTempTouchState.deviceId = entry->deviceId;
1591 mTempTouchState.source = entry->source;
1592 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 }
1594 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1595 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1596 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001597 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1599 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001600 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601#if DEBUG_FOCUS
1602 ALOGD("Conflicting pointer actions: Down received while already down.");
1603#endif
1604 *outConflictingPointerActions = true;
1605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1607 // One pointer went up.
1608 if (isSplit) {
1609 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1610 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1611
1612 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1613 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1614 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1615 touchedWindow.pointerIds.clearBit(pointerId);
1616 if (touchedWindow.pointerIds.isEmpty()) {
1617 mTempTouchState.windows.removeAt(i);
1618 continue;
1619 }
1620 }
1621 i += 1;
1622 }
1623 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001624 }
1625
1626 // Save changes unless the action was scroll in which case the temporary touch
1627 // state was only valid for this one action.
1628 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1629 if (mTempTouchState.displayId >= 0) {
1630 if (oldStateIndex >= 0) {
1631 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1632 } else {
1633 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1634 }
1635 } else if (oldStateIndex >= 0) {
1636 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 }
1639
1640 // Update hover state.
1641 mLastHoverWindowHandle = newHoverWindowHandle;
1642 }
1643 } else {
1644#if DEBUG_FOCUS
1645 ALOGD("Not updating touch focus because injection was denied.");
1646#endif
1647 }
1648
1649Unresponsive:
1650 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1651 mTempTouchState.reset();
1652
1653 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1654 updateDispatchStatisticsLocked(currentTime, entry,
1655 injectionResult, timeSpentWaitingForApplication);
1656#if DEBUG_FOCUS
1657 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1658 "timeSpentWaitingForApplication=%0.1fms",
1659 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1660#endif
1661 return injectionResult;
1662}
1663
1664void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1665 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1666 inputTargets.push();
1667
1668 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1669 InputTarget& target = inputTargets.editTop();
Robert Carr5c8a0262018-10-03 16:30:44 -07001670 target.inputChannel = getInputChannelLocked(windowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 target.flags = targetFlags;
1672 target.xOffset = - windowInfo->frameLeft;
1673 target.yOffset = - windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001674 target.globalScaleFactor = windowInfo->globalScaleFactor;
1675 target.windowXScale = windowInfo->windowXScale;
1676 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677 target.pointerIds = pointerIds;
1678}
1679
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001680void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets,
1681 int32_t displayId) {
1682 std::unordered_map<int32_t, Vector<sp<InputChannel>>>::const_iterator it =
1683 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001685 if (it != mMonitoringChannelsByDisplay.end()) {
1686 const Vector<sp<InputChannel>>& monitoringChannels = it->second;
1687 const size_t numChannels = monitoringChannels.size();
1688 for (size_t i = 0; i < numChannels; i++) {
1689 inputTargets.push();
1690
1691 InputTarget& target = inputTargets.editTop();
1692 target.inputChannel = monitoringChannels[i];
1693 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1694 target.xOffset = 0;
1695 target.yOffset = 0;
1696 target.pointerIds.clear();
Robert Carre07e1032018-11-26 12:55:53 -08001697 target.globalScaleFactor = 1.0f;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001698 }
1699 } else {
1700 // If there is no monitor channel registered or all monitor channel unregistered,
1701 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001702 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 }
1704}
1705
1706bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1707 const InjectionState* injectionState) {
1708 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001709 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1711 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001712 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1714 "owned by uid %d",
1715 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001716 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717 windowHandle->getInfo()->ownerUid);
1718 } else {
1719 ALOGW("Permission denied: injecting event from pid %d uid %d",
1720 injectionState->injectorPid, injectionState->injectorUid);
1721 }
1722 return false;
1723 }
1724 return true;
1725}
1726
1727bool InputDispatcher::isWindowObscuredAtPointLocked(
1728 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1729 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001730 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1731 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001733 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 if (otherHandle == windowHandle) {
1735 break;
1736 }
1737
1738 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1739 if (otherInfo->displayId == displayId
1740 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1741 && otherInfo->frameContainsPoint(x, y)) {
1742 return true;
1743 }
1744 }
1745 return false;
1746}
1747
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001748
1749bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1750 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001751 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001752 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hungb92218b2018-08-14 12:00:21 +08001753 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001754 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001755 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001756 if (otherHandle == windowHandle) {
1757 break;
1758 }
1759
1760 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1761 if (otherInfo->displayId == displayId
1762 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1763 && otherInfo->overlaps(windowInfo)) {
1764 return true;
1765 }
1766 }
1767 return false;
1768}
1769
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001770std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001771 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1772 const char* targetType) {
1773 // If the window is paused then keep waiting.
1774 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001775 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001776 }
1777
1778 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001779 ssize_t connectionIndex = getConnectionIndexLocked(
1780 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001781 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001782 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001783 "registered with the input dispatcher. The window may be in the process "
1784 "of being removed.", targetType);
1785 }
1786
1787 // If the connection is dead then keep waiting.
1788 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1789 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001790 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001791 "The window may be in the process of being removed.", targetType,
1792 connection->getStatusLabel());
1793 }
1794
1795 // If the connection is backed up then keep waiting.
1796 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001797 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001798 "Outbound queue length: %d. Wait queue length: %d.",
1799 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1800 }
1801
1802 // Ensure that the dispatch queues aren't too far backed up for this event.
1803 if (eventEntry->type == EventEntry::TYPE_KEY) {
1804 // If the event is a key event, then we must wait for all previous events to
1805 // complete before delivering it because previous events may have the
1806 // side-effect of transferring focus to a different window and we want to
1807 // ensure that the following keys are sent to the new window.
1808 //
1809 // Suppose the user touches a button in a window then immediately presses "A".
1810 // If the button causes a pop-up window to appear then we want to ensure that
1811 // the "A" key is delivered to the new pop-up window. This is because users
1812 // often anticipate pending UI changes when typing on a keyboard.
1813 // To obtain this behavior, we must serialize key events with respect to all
1814 // prior input events.
1815 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001816 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001817 "finished processing all of the input events that were previously "
1818 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1819 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820 }
Jeff Brownffb49772014-10-10 19:01:34 -07001821 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 // Touch events can always be sent to a window immediately because the user intended
1823 // to touch whatever was visible at the time. Even if focus changes or a new
1824 // window appears moments later, the touch event was meant to be delivered to
1825 // whatever window happened to be on screen at the time.
1826 //
1827 // Generic motion events, such as trackball or joystick events are a little trickier.
1828 // Like key events, generic motion events are delivered to the focused window.
1829 // Unlike key events, generic motion events don't tend to transfer focus to other
1830 // windows and it is not important for them to be serialized. So we prefer to deliver
1831 // generic motion events as soon as possible to improve efficiency and reduce lag
1832 // through batching.
1833 //
1834 // The one case where we pause input event delivery is when the wait queue is piling
1835 // up with lots of events because the application is not responding.
1836 // This condition ensures that ANRs are detected reliably.
1837 if (!connection->waitQueue.isEmpty()
1838 && currentTime >= connection->waitQueue.head->deliveryTime
1839 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001840 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001841 "finished processing certain input events that were delivered to it over "
1842 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1843 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1844 connection->waitQueue.count(),
1845 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846 }
1847 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001848 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849}
1850
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001851std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 const sp<InputApplicationHandle>& applicationHandle,
1853 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001854 if (applicationHandle != nullptr) {
1855 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001856 std::string label(applicationHandle->getName());
1857 label += " - ";
1858 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 return label;
1860 } else {
1861 return applicationHandle->getName();
1862 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001863 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 return windowHandle->getName();
1865 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001866 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 }
1868}
1869
1870void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001871 int32_t displayId = getTargetDisplayId(eventEntry);
1872 sp<InputWindowHandle> focusedWindowHandle =
1873 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1874 if (focusedWindowHandle != nullptr) {
1875 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1877#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001878 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879#endif
1880 return;
1881 }
1882 }
1883
1884 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1885 switch (eventEntry->type) {
1886 case EventEntry::TYPE_MOTION: {
1887 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1888 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1889 return;
1890 }
1891
1892 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1893 eventType = USER_ACTIVITY_EVENT_TOUCH;
1894 }
1895 break;
1896 }
1897 case EventEntry::TYPE_KEY: {
1898 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1899 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1900 return;
1901 }
1902 eventType = USER_ACTIVITY_EVENT_BUTTON;
1903 break;
1904 }
1905 }
1906
1907 CommandEntry* commandEntry = postCommandLocked(
1908 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1909 commandEntry->eventTime = eventEntry->eventTime;
1910 commandEntry->userActivityEventType = eventType;
1911}
1912
1913void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1914 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1915#if DEBUG_DISPATCH_CYCLE
1916 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Robert Carre07e1032018-11-26 12:55:53 -08001917 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1918 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001919 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001920 inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001921 inputTarget->globalScaleFactor,
1922 inputTarget->windowXScale, inputTarget->windowYScale,
1923 inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001924#endif
1925
1926 // Skip this event if the connection status is not normal.
1927 // We don't want to enqueue additional outbound events if the connection is broken.
1928 if (connection->status != Connection::STATUS_NORMAL) {
1929#if DEBUG_DISPATCH_CYCLE
1930 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001931 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932#endif
1933 return;
1934 }
1935
1936 // Split a motion event if needed.
1937 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1938 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1939
1940 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1941 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1942 MotionEntry* splitMotionEntry = splitMotionEvent(
1943 originalMotionEntry, inputTarget->pointerIds);
1944 if (!splitMotionEntry) {
1945 return; // split event was dropped
1946 }
1947#if DEBUG_FOCUS
1948 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001949 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1951#endif
1952 enqueueDispatchEntriesLocked(currentTime, connection,
1953 splitMotionEntry, inputTarget);
1954 splitMotionEntry->release();
1955 return;
1956 }
1957 }
1958
1959 // Not splitting. Enqueue dispatch entries for the event as is.
1960 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1961}
1962
1963void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1964 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1965 bool wasEmpty = connection->outboundQueue.isEmpty();
1966
1967 // Enqueue dispatch entries for the requested modes.
1968 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1969 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1970 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1971 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1972 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1973 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1974 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1975 InputTarget::FLAG_DISPATCH_AS_IS);
1976 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1977 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1978 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1979 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1980
1981 // If the outbound queue was previously empty, start the dispatch cycle going.
1982 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1983 startDispatchCycleLocked(currentTime, connection);
1984 }
1985}
1986
1987void InputDispatcher::enqueueDispatchEntryLocked(
1988 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1989 int32_t dispatchMode) {
1990 int32_t inputTargetFlags = inputTarget->flags;
1991 if (!(inputTargetFlags & dispatchMode)) {
1992 return;
1993 }
1994 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1995
1996 // This is a new event.
1997 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1998 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1999 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08002000 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2001 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002
2003 // Apply target flags and update the connection's input state.
2004 switch (eventEntry->type) {
2005 case EventEntry::TYPE_KEY: {
2006 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2007 dispatchEntry->resolvedAction = keyEntry->action;
2008 dispatchEntry->resolvedFlags = keyEntry->flags;
2009
2010 if (!connection->inputState.trackKey(keyEntry,
2011 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2012#if DEBUG_DISPATCH_CYCLE
2013 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002014 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015#endif
2016 delete dispatchEntry;
2017 return; // skip the inconsistent event
2018 }
2019 break;
2020 }
2021
2022 case EventEntry::TYPE_MOTION: {
2023 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2024 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2025 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2026 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2027 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2028 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2029 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2030 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2031 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2032 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2033 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2034 } else {
2035 dispatchEntry->resolvedAction = motionEntry->action;
2036 }
2037 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2038 && !connection->inputState.isHovering(
2039 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2040#if DEBUG_DISPATCH_CYCLE
2041 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002042 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043#endif
2044 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2045 }
2046
2047 dispatchEntry->resolvedFlags = motionEntry->flags;
2048 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2049 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2050 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002051 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2052 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2053 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054
2055 if (!connection->inputState.trackMotion(motionEntry,
2056 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2057#if DEBUG_DISPATCH_CYCLE
2058 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002059 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060#endif
2061 delete dispatchEntry;
2062 return; // skip the inconsistent event
2063 }
2064 break;
2065 }
2066 }
2067
2068 // Remember that we are waiting for this dispatch to complete.
2069 if (dispatchEntry->hasForegroundTarget()) {
2070 incrementPendingForegroundDispatchesLocked(eventEntry);
2071 }
2072
2073 // Enqueue the dispatch entry.
2074 connection->outboundQueue.enqueueAtTail(dispatchEntry);
2075 traceOutboundQueueLengthLocked(connection);
2076}
2077
2078void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2079 const sp<Connection>& connection) {
2080#if DEBUG_DISPATCH_CYCLE
2081 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002082 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002083#endif
2084
2085 while (connection->status == Connection::STATUS_NORMAL
2086 && !connection->outboundQueue.isEmpty()) {
2087 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2088 dispatchEntry->deliveryTime = currentTime;
2089
2090 // Publish the event.
2091 status_t status;
2092 EventEntry* eventEntry = dispatchEntry->eventEntry;
2093 switch (eventEntry->type) {
2094 case EventEntry::TYPE_KEY: {
2095 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2096
2097 // Publish the key event.
2098 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002099 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2101 keyEntry->keyCode, keyEntry->scanCode,
2102 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2103 keyEntry->eventTime);
2104 break;
2105 }
2106
2107 case EventEntry::TYPE_MOTION: {
2108 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2109
2110 PointerCoords scaledCoords[MAX_POINTERS];
2111 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2112
2113 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002114 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2116 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002117 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2118 float wxs = dispatchEntry->windowXScale;
2119 float wys = dispatchEntry->windowYScale;
2120 xOffset = dispatchEntry->xOffset * wxs;
2121 yOffset = dispatchEntry->yOffset * wys;
2122 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002123 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002125 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 }
2127 usingCoords = scaledCoords;
2128 }
2129 } else {
2130 xOffset = 0.0f;
2131 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132
2133 // We don't want the dispatch target to know.
2134 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002135 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002136 scaledCoords[i].clear();
2137 }
2138 usingCoords = scaledCoords;
2139 }
2140 }
2141
2142 // Publish the motion event.
2143 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002144 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002145 dispatchEntry->resolvedAction, motionEntry->actionButton,
2146 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2147 motionEntry->metaState, motionEntry->buttonState,
2148 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 motionEntry->downTime, motionEntry->eventTime,
2150 motionEntry->pointerCount, motionEntry->pointerProperties,
2151 usingCoords);
2152 break;
2153 }
2154
2155 default:
2156 ALOG_ASSERT(false);
2157 return;
2158 }
2159
2160 // Check the result.
2161 if (status) {
2162 if (status == WOULD_BLOCK) {
2163 if (connection->waitQueue.isEmpty()) {
2164 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2165 "This is unexpected because the wait queue is empty, so the pipe "
2166 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002167 "event to it, status=%d", connection->getInputChannelName().c_str(),
2168 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2170 } else {
2171 // Pipe is full and we are waiting for the app to finish process some events
2172 // before sending more events to it.
2173#if DEBUG_DISPATCH_CYCLE
2174 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2175 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002176 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177#endif
2178 connection->inputPublisherBlocked = true;
2179 }
2180 } else {
2181 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002182 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2184 }
2185 return;
2186 }
2187
2188 // Re-enqueue the event on the wait queue.
2189 connection->outboundQueue.dequeue(dispatchEntry);
2190 traceOutboundQueueLengthLocked(connection);
2191 connection->waitQueue.enqueueAtTail(dispatchEntry);
2192 traceWaitQueueLengthLocked(connection);
2193 }
2194}
2195
2196void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2197 const sp<Connection>& connection, uint32_t seq, bool handled) {
2198#if DEBUG_DISPATCH_CYCLE
2199 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002200 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201#endif
2202
2203 connection->inputPublisherBlocked = false;
2204
2205 if (connection->status == Connection::STATUS_BROKEN
2206 || connection->status == Connection::STATUS_ZOMBIE) {
2207 return;
2208 }
2209
2210 // Notify other system components and prepare to start the next dispatch cycle.
2211 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2212}
2213
2214void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2215 const sp<Connection>& connection, bool notify) {
2216#if DEBUG_DISPATCH_CYCLE
2217 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002218 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219#endif
2220
2221 // Clear the dispatch queues.
2222 drainDispatchQueueLocked(&connection->outboundQueue);
2223 traceOutboundQueueLengthLocked(connection);
2224 drainDispatchQueueLocked(&connection->waitQueue);
2225 traceWaitQueueLengthLocked(connection);
2226
2227 // The connection appears to be unrecoverably broken.
2228 // Ignore already broken or zombie connections.
2229 if (connection->status == Connection::STATUS_NORMAL) {
2230 connection->status = Connection::STATUS_BROKEN;
2231
2232 if (notify) {
2233 // Notify other system components.
2234 onDispatchCycleBrokenLocked(currentTime, connection);
2235 }
2236 }
2237}
2238
2239void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2240 while (!queue->isEmpty()) {
2241 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2242 releaseDispatchEntryLocked(dispatchEntry);
2243 }
2244}
2245
2246void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2247 if (dispatchEntry->hasForegroundTarget()) {
2248 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2249 }
2250 delete dispatchEntry;
2251}
2252
2253int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2254 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2255
2256 { // acquire lock
2257 AutoMutex _l(d->mLock);
2258
2259 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2260 if (connectionIndex < 0) {
2261 ALOGE("Received spurious receive callback for unknown input channel. "
2262 "fd=%d, events=0x%x", fd, events);
2263 return 0; // remove the callback
2264 }
2265
2266 bool notify;
2267 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2268 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2269 if (!(events & ALOOPER_EVENT_INPUT)) {
2270 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002271 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 return 1;
2273 }
2274
2275 nsecs_t currentTime = now();
2276 bool gotOne = false;
2277 status_t status;
2278 for (;;) {
2279 uint32_t seq;
2280 bool handled;
2281 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2282 if (status) {
2283 break;
2284 }
2285 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2286 gotOne = true;
2287 }
2288 if (gotOne) {
2289 d->runCommandsLockedInterruptible();
2290 if (status == WOULD_BLOCK) {
2291 return 1;
2292 }
2293 }
2294
2295 notify = status != DEAD_OBJECT || !connection->monitor;
2296 if (notify) {
2297 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002298 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299 }
2300 } else {
2301 // Monitor channels are never explicitly unregistered.
2302 // We do it automatically when the remote endpoint is closed so don't warn
2303 // about them.
2304 notify = !connection->monitor;
2305 if (notify) {
2306 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002307 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 }
2309 }
2310
2311 // Unregister the channel.
2312 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2313 return 0; // remove the callback
2314 } // release lock
2315}
2316
2317void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2318 const CancelationOptions& options) {
2319 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2320 synthesizeCancelationEventsForConnectionLocked(
2321 mConnectionsByFd.valueAt(i), options);
2322 }
2323}
2324
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002325void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2326 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002327 for (auto& it : mMonitoringChannelsByDisplay) {
2328 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
2329 const size_t numChannels = monitoringChannels.size();
2330 for (size_t i = 0; i < numChannels; i++) {
2331 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2332 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002333 }
2334}
2335
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2337 const sp<InputChannel>& channel, const CancelationOptions& options) {
2338 ssize_t index = getConnectionIndexLocked(channel);
2339 if (index >= 0) {
2340 synthesizeCancelationEventsForConnectionLocked(
2341 mConnectionsByFd.valueAt(index), options);
2342 }
2343}
2344
2345void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2346 const sp<Connection>& connection, const CancelationOptions& options) {
2347 if (connection->status == Connection::STATUS_BROKEN) {
2348 return;
2349 }
2350
2351 nsecs_t currentTime = now();
2352
2353 Vector<EventEntry*> cancelationEvents;
2354 connection->inputState.synthesizeCancelationEvents(currentTime,
2355 cancelationEvents, options);
2356
2357 if (!cancelationEvents.isEmpty()) {
2358#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002359 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002361 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 options.reason, options.mode);
2363#endif
2364 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2365 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2366 switch (cancelationEventEntry->type) {
2367 case EventEntry::TYPE_KEY:
2368 logOutboundKeyDetailsLocked("cancel - ",
2369 static_cast<KeyEntry*>(cancelationEventEntry));
2370 break;
2371 case EventEntry::TYPE_MOTION:
2372 logOutboundMotionDetailsLocked("cancel - ",
2373 static_cast<MotionEntry*>(cancelationEventEntry));
2374 break;
2375 }
2376
2377 InputTarget target;
2378 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07002379 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2381 target.xOffset = -windowInfo->frameLeft;
2382 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002383 target.globalScaleFactor = windowInfo->globalScaleFactor;
2384 target.windowXScale = windowInfo->windowXScale;
2385 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 } else {
2387 target.xOffset = 0;
2388 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002389 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390 }
2391 target.inputChannel = connection->inputChannel;
2392 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2393
2394 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2395 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2396
2397 cancelationEventEntry->release();
2398 }
2399
2400 startDispatchCycleLocked(currentTime, connection);
2401 }
2402}
2403
2404InputDispatcher::MotionEntry*
2405InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2406 ALOG_ASSERT(pointerIds.value != 0);
2407
2408 uint32_t splitPointerIndexMap[MAX_POINTERS];
2409 PointerProperties splitPointerProperties[MAX_POINTERS];
2410 PointerCoords splitPointerCoords[MAX_POINTERS];
2411
2412 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2413 uint32_t splitPointerCount = 0;
2414
2415 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2416 originalPointerIndex++) {
2417 const PointerProperties& pointerProperties =
2418 originalMotionEntry->pointerProperties[originalPointerIndex];
2419 uint32_t pointerId = uint32_t(pointerProperties.id);
2420 if (pointerIds.hasBit(pointerId)) {
2421 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2422 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2423 splitPointerCoords[splitPointerCount].copyFrom(
2424 originalMotionEntry->pointerCoords[originalPointerIndex]);
2425 splitPointerCount += 1;
2426 }
2427 }
2428
2429 if (splitPointerCount != pointerIds.count()) {
2430 // This is bad. We are missing some of the pointers that we expected to deliver.
2431 // Most likely this indicates that we received an ACTION_MOVE events that has
2432 // different pointer ids than we expected based on the previous ACTION_DOWN
2433 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2434 // in this way.
2435 ALOGW("Dropping split motion event because the pointer count is %d but "
2436 "we expected there to be %d pointers. This probably means we received "
2437 "a broken sequence of pointer ids from the input device.",
2438 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002439 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 }
2441
2442 int32_t action = originalMotionEntry->action;
2443 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2444 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2445 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2446 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2447 const PointerProperties& pointerProperties =
2448 originalMotionEntry->pointerProperties[originalPointerIndex];
2449 uint32_t pointerId = uint32_t(pointerProperties.id);
2450 if (pointerIds.hasBit(pointerId)) {
2451 if (pointerIds.count() == 1) {
2452 // The first/last pointer went down/up.
2453 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2454 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2455 } else {
2456 // A secondary pointer went down/up.
2457 uint32_t splitPointerIndex = 0;
2458 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2459 splitPointerIndex += 1;
2460 }
2461 action = maskedAction | (splitPointerIndex
2462 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2463 }
2464 } else {
2465 // An unrelated pointer changed.
2466 action = AMOTION_EVENT_ACTION_MOVE;
2467 }
2468 }
2469
2470 MotionEntry* splitMotionEntry = new MotionEntry(
2471 originalMotionEntry->eventTime,
2472 originalMotionEntry->deviceId,
2473 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002474 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475 originalMotionEntry->policyFlags,
2476 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002477 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 originalMotionEntry->flags,
2479 originalMotionEntry->metaState,
2480 originalMotionEntry->buttonState,
2481 originalMotionEntry->edgeFlags,
2482 originalMotionEntry->xPrecision,
2483 originalMotionEntry->yPrecision,
2484 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002485 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486
2487 if (originalMotionEntry->injectionState) {
2488 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2489 splitMotionEntry->injectionState->refCount += 1;
2490 }
2491
2492 return splitMotionEntry;
2493}
2494
2495void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2496#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002497 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498#endif
2499
2500 bool needWake;
2501 { // acquire lock
2502 AutoMutex _l(mLock);
2503
2504 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2505 needWake = enqueueInboundEventLocked(newEntry);
2506 } // release lock
2507
2508 if (needWake) {
2509 mLooper->wake();
2510 }
2511}
2512
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002513/**
2514 * If one of the meta shortcuts is detected, process them here:
2515 * Meta + Backspace -> generate BACK
2516 * Meta + Enter -> generate HOME
2517 * This will potentially overwrite keyCode and metaState.
2518 */
2519void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2520 int32_t& keyCode, int32_t& metaState) {
2521 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2522 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2523 if (keyCode == AKEYCODE_DEL) {
2524 newKeyCode = AKEYCODE_BACK;
2525 } else if (keyCode == AKEYCODE_ENTER) {
2526 newKeyCode = AKEYCODE_HOME;
2527 }
2528 if (newKeyCode != AKEYCODE_UNKNOWN) {
2529 AutoMutex _l(mLock);
2530 struct KeyReplacement replacement = {keyCode, deviceId};
2531 mReplacedKeys.add(replacement, newKeyCode);
2532 keyCode = newKeyCode;
2533 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2534 }
2535 } else if (action == AKEY_EVENT_ACTION_UP) {
2536 // In order to maintain a consistent stream of up and down events, check to see if the key
2537 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2538 // even if the modifier was released between the down and the up events.
2539 AutoMutex _l(mLock);
2540 struct KeyReplacement replacement = {keyCode, deviceId};
2541 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2542 if (index >= 0) {
2543 keyCode = mReplacedKeys.valueAt(index);
2544 mReplacedKeys.removeItemsAt(index);
2545 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2546 }
2547 }
2548}
2549
Michael Wrightd02c5b62014-02-10 15:10:22 -08002550void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2551#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002552 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002553 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002554 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002555 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002557 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558#endif
2559 if (!validateKeyEvent(args->action)) {
2560 return;
2561 }
2562
2563 uint32_t policyFlags = args->policyFlags;
2564 int32_t flags = args->flags;
2565 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002566 // InputDispatcher tracks and generates key repeats on behalf of
2567 // whatever notifies it, so repeatCount should always be set to 0
2568 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2570 policyFlags |= POLICY_FLAG_VIRTUAL;
2571 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2572 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 if (policyFlags & POLICY_FLAG_FUNCTION) {
2574 metaState |= AMETA_FUNCTION_ON;
2575 }
2576
2577 policyFlags |= POLICY_FLAG_TRUSTED;
2578
Michael Wright78f24442014-08-06 15:55:28 -07002579 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002580 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002581
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002583 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002584 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 args->downTime, args->eventTime);
2586
Michael Wright2b3c3302018-03-02 17:19:13 +00002587 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002589 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2590 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2591 std::to_string(t.duration().count()).c_str());
2592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594 bool needWake;
2595 { // acquire lock
2596 mLock.lock();
2597
2598 if (shouldSendKeyToInputFilterLocked(args)) {
2599 mLock.unlock();
2600
2601 policyFlags |= POLICY_FLAG_FILTERED;
2602 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2603 return; // event was consumed by the filter
2604 }
2605
2606 mLock.lock();
2607 }
2608
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 KeyEntry* newEntry = new KeyEntry(args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002610 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002611 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 metaState, repeatCount, args->downTime);
2613
2614 needWake = enqueueInboundEventLocked(newEntry);
2615 mLock.unlock();
2616 } // release lock
2617
2618 if (needWake) {
2619 mLooper->wake();
2620 }
2621}
2622
2623bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2624 return mInputFilterEnabled;
2625}
2626
2627void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2628#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002629 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2630 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002631 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002632 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2633 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002634 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002635 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002636 for (uint32_t i = 0; i < args->pointerCount; i++) {
2637 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2638 "x=%f, y=%f, pressure=%f, size=%f, "
2639 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2640 "orientation=%f",
2641 i, args->pointerProperties[i].id,
2642 args->pointerProperties[i].toolType,
2643 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2644 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2645 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2646 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2647 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2648 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2649 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2650 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2651 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2652 }
2653#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002654 if (!validateMotionEvent(args->action, args->actionButton,
2655 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 return;
2657 }
2658
2659 uint32_t policyFlags = args->policyFlags;
2660 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002661
2662 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002664 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2665 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2666 std::to_string(t.duration().count()).c_str());
2667 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002668
2669 bool needWake;
2670 { // acquire lock
2671 mLock.lock();
2672
2673 if (shouldSendMotionToInputFilterLocked(args)) {
2674 mLock.unlock();
2675
2676 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002677 event.initialize(args->deviceId, args->source, args->displayId,
2678 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002679 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2680 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 args->downTime, args->eventTime,
2682 args->pointerCount, args->pointerProperties, args->pointerCoords);
2683
2684 policyFlags |= POLICY_FLAG_FILTERED;
2685 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2686 return; // event was consumed by the filter
2687 }
2688
2689 mLock.lock();
2690 }
2691
2692 // Just enqueue a new motion event.
2693 MotionEntry* newEntry = new MotionEntry(args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002694 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002695 args->action, args->actionButton, args->flags,
2696 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002698 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699
2700 needWake = enqueueInboundEventLocked(newEntry);
2701 mLock.unlock();
2702 } // release lock
2703
2704 if (needWake) {
2705 mLooper->wake();
2706 }
2707}
2708
2709bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2710 // TODO: support sending secondary display events to input filter
2711 return mInputFilterEnabled && isMainDisplay(args->displayId);
2712}
2713
2714void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2715#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002716 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2717 "switchMask=0x%08x",
2718 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719#endif
2720
2721 uint32_t policyFlags = args->policyFlags;
2722 policyFlags |= POLICY_FLAG_TRUSTED;
2723 mPolicy->notifySwitch(args->eventTime,
2724 args->switchValues, args->switchMask, policyFlags);
2725}
2726
2727void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2728#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002729 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 args->eventTime, args->deviceId);
2731#endif
2732
2733 bool needWake;
2734 { // acquire lock
2735 AutoMutex _l(mLock);
2736
2737 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2738 needWake = enqueueInboundEventLocked(newEntry);
2739 } // release lock
2740
2741 if (needWake) {
2742 mLooper->wake();
2743 }
2744}
2745
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002746int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2748 uint32_t policyFlags) {
2749#if DEBUG_INBOUND_EVENT_DETAILS
2750 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002751 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2752 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753#endif
2754
2755 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2756
2757 policyFlags |= POLICY_FLAG_INJECTED;
2758 if (hasInjectionPermission(injectorPid, injectorUid)) {
2759 policyFlags |= POLICY_FLAG_TRUSTED;
2760 }
2761
2762 EventEntry* firstInjectedEntry;
2763 EventEntry* lastInjectedEntry;
2764 switch (event->getType()) {
2765 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002766 KeyEvent keyEvent;
2767 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2768 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769 if (! validateKeyEvent(action)) {
2770 return INPUT_EVENT_INJECTION_FAILED;
2771 }
2772
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002773 int32_t flags = keyEvent.getFlags();
2774 int32_t keyCode = keyEvent.getKeyCode();
2775 int32_t metaState = keyEvent.getMetaState();
2776 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2777 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002778 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002779 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002780 keyEvent.getDownTime(), keyEvent.getEventTime());
2781
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2783 policyFlags |= POLICY_FLAG_VIRTUAL;
2784 }
2785
2786 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002787 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002788 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002789 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2790 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2791 std::to_string(t.duration().count()).c_str());
2792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 }
2794
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 mLock.lock();
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002796 firstInjectedEntry = new KeyEntry(keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002797 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002799 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2800 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801 lastInjectedEntry = firstInjectedEntry;
2802 break;
2803 }
2804
2805 case AINPUT_EVENT_TYPE_MOTION: {
2806 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 int32_t action = motionEvent->getAction();
2808 size_t pointerCount = motionEvent->getPointerCount();
2809 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002810 int32_t actionButton = motionEvent->getActionButton();
2811 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 return INPUT_EVENT_INJECTION_FAILED;
2813 }
2814
2815 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2816 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002817 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002819 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2820 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2821 std::to_string(t.duration().count()).c_str());
2822 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 }
2824
2825 mLock.lock();
2826 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2827 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2828 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002829 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2830 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002831 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002832 motionEvent->getMetaState(), motionEvent->getButtonState(),
2833 motionEvent->getEdgeFlags(),
2834 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002835 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002836 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2837 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 lastInjectedEntry = firstInjectedEntry;
2839 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2840 sampleEventTimes += 1;
2841 samplePointerCoords += pointerCount;
2842 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002843 motionEvent->getDeviceId(), motionEvent->getSource(),
2844 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002845 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846 motionEvent->getMetaState(), motionEvent->getButtonState(),
2847 motionEvent->getEdgeFlags(),
2848 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002849 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002850 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2851 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 lastInjectedEntry->next = nextInjectedEntry;
2853 lastInjectedEntry = nextInjectedEntry;
2854 }
2855 break;
2856 }
2857
2858 default:
2859 ALOGW("Cannot inject event of type %d", event->getType());
2860 return INPUT_EVENT_INJECTION_FAILED;
2861 }
2862
2863 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2864 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2865 injectionState->injectionIsAsync = true;
2866 }
2867
2868 injectionState->refCount += 1;
2869 lastInjectedEntry->injectionState = injectionState;
2870
2871 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002872 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 EventEntry* nextEntry = entry->next;
2874 needWake |= enqueueInboundEventLocked(entry);
2875 entry = nextEntry;
2876 }
2877
2878 mLock.unlock();
2879
2880 if (needWake) {
2881 mLooper->wake();
2882 }
2883
2884 int32_t injectionResult;
2885 { // acquire lock
2886 AutoMutex _l(mLock);
2887
2888 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2889 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2890 } else {
2891 for (;;) {
2892 injectionResult = injectionState->injectionResult;
2893 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2894 break;
2895 }
2896
2897 nsecs_t remainingTimeout = endTime - now();
2898 if (remainingTimeout <= 0) {
2899#if DEBUG_INJECTION
2900 ALOGD("injectInputEvent - Timed out waiting for injection result "
2901 "to become available.");
2902#endif
2903 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2904 break;
2905 }
2906
2907 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2908 }
2909
2910 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2911 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2912 while (injectionState->pendingForegroundDispatches != 0) {
2913#if DEBUG_INJECTION
2914 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2915 injectionState->pendingForegroundDispatches);
2916#endif
2917 nsecs_t remainingTimeout = endTime - now();
2918 if (remainingTimeout <= 0) {
2919#if DEBUG_INJECTION
2920 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2921 "dispatches to finish.");
2922#endif
2923 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2924 break;
2925 }
2926
2927 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2928 }
2929 }
2930 }
2931
2932 injectionState->release();
2933 } // release lock
2934
2935#if DEBUG_INJECTION
2936 ALOGD("injectInputEvent - Finished with result %d. "
2937 "injectorPid=%d, injectorUid=%d",
2938 injectionResult, injectorPid, injectorUid);
2939#endif
2940
2941 return injectionResult;
2942}
2943
2944bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2945 return injectorUid == 0
2946 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2947}
2948
2949void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2950 InjectionState* injectionState = entry->injectionState;
2951 if (injectionState) {
2952#if DEBUG_INJECTION
2953 ALOGD("Setting input event injection result to %d. "
2954 "injectorPid=%d, injectorUid=%d",
2955 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2956#endif
2957
2958 if (injectionState->injectionIsAsync
2959 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2960 // Log the outcome since the injector did not wait for the injection result.
2961 switch (injectionResult) {
2962 case INPUT_EVENT_INJECTION_SUCCEEDED:
2963 ALOGV("Asynchronous input event injection succeeded.");
2964 break;
2965 case INPUT_EVENT_INJECTION_FAILED:
2966 ALOGW("Asynchronous input event injection failed.");
2967 break;
2968 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2969 ALOGW("Asynchronous input event injection permission denied.");
2970 break;
2971 case INPUT_EVENT_INJECTION_TIMED_OUT:
2972 ALOGW("Asynchronous input event injection timed out.");
2973 break;
2974 }
2975 }
2976
2977 injectionState->injectionResult = injectionResult;
2978 mInjectionResultAvailableCondition.broadcast();
2979 }
2980}
2981
2982void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2983 InjectionState* injectionState = entry->injectionState;
2984 if (injectionState) {
2985 injectionState->pendingForegroundDispatches += 1;
2986 }
2987}
2988
2989void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2990 InjectionState* injectionState = entry->injectionState;
2991 if (injectionState) {
2992 injectionState->pendingForegroundDispatches -= 1;
2993
2994 if (injectionState->pendingForegroundDispatches == 0) {
2995 mInjectionSyncFinishedCondition.broadcast();
2996 }
2997 }
2998}
2999
Arthur Hungb92218b2018-08-14 12:00:21 +08003000Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
3001 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
3002 mWindowHandlesByDisplay.find(displayId);
3003 if(it != mWindowHandlesByDisplay.end()) {
3004 return it->second;
3005 }
3006
3007 // Return an empty one if nothing found.
3008 return Vector<sp<InputWindowHandle>>();
3009}
3010
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3012 const sp<InputChannel>& inputChannel) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003013 for (auto& it : mWindowHandlesByDisplay) {
3014 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3015 size_t numWindows = windowHandles.size();
3016 for (size_t i = 0; i < numWindows; i++) {
3017 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
Robert Carr5c8a0262018-10-03 16:30:44 -07003018 if (windowHandle->getToken() == inputChannel->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003019 return windowHandle;
3020 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021 }
3022 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003023 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024}
3025
3026bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003027 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003028 for (auto& it : mWindowHandlesByDisplay) {
3029 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3030 size_t numWindows = windowHandles.size();
3031 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003032 if (windowHandles.itemAt(i)->getToken()
3033 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003034 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003035 ALOGE("Found window %s in display %" PRId32
3036 ", but it should belong to display %" PRId32,
3037 windowHandle->getName().c_str(), it.first,
3038 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003039 }
3040 return true;
3041 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003042 }
3043 }
3044 return false;
3045}
3046
Robert Carr5c8a0262018-10-03 16:30:44 -07003047sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3048 size_t count = mInputChannelsByToken.count(token);
3049 if (count == 0) {
3050 return nullptr;
3051 }
3052 return mInputChannelsByToken.at(token);
3053}
3054
Arthur Hungb92218b2018-08-14 12:00:21 +08003055/**
3056 * Called from InputManagerService, update window handle list by displayId that can receive input.
3057 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3058 * If set an empty list, remove all handles from the specific display.
3059 * For focused handle, check if need to change and send a cancel event to previous one.
3060 * For removed handle, check if need to send a cancel event if already in touch.
3061 */
3062void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3063 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003065 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066#endif
3067 { // acquire lock
3068 AutoMutex _l(mLock);
3069
Arthur Hungb92218b2018-08-14 12:00:21 +08003070 // Copy old handles for release if they are no longer present.
3071 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003072
Tiger Huang721e26f2018-07-24 22:26:19 +08003073 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003075
3076 if (inputWindowHandles.isEmpty()) {
3077 // Remove all handles on a display if there are no windows left.
3078 mWindowHandlesByDisplay.erase(displayId);
3079 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003080 // Since we compare the pointer of input window handles across window updates, we need
3081 // to make sure the handle object for the same window stays unchanged across updates.
3082 const Vector<sp<InputWindowHandle>>& oldHandles = mWindowHandlesByDisplay[displayId];
3083 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3084 for (size_t i = 0; i < oldHandles.size(); i++) {
3085 const sp<InputWindowHandle>& handle = oldHandles.itemAt(i);
3086 oldHandlesByTokens[handle->getToken()] = handle;
3087 }
3088
3089 const size_t numWindows = inputWindowHandles.size();
3090 Vector<sp<InputWindowHandle>> newHandles;
Arthur Hungb92218b2018-08-14 12:00:21 +08003091 for (size_t i = 0; i < numWindows; i++) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003092 const sp<InputWindowHandle>& handle = inputWindowHandles.itemAt(i);
3093 if (!handle->updateInfo() || getInputChannelLocked(handle->getToken()) == nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003094 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003095 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003096 continue;
3097 }
3098
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003099 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003100 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003101 handle->getName().c_str(), displayId,
3102 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003103 continue;
3104 }
3105
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003106 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3107 const sp<InputWindowHandle> oldHandle =
3108 oldHandlesByTokens.at(handle->getToken());
3109 oldHandle->updateFrom(handle);
3110 newHandles.push_back(oldHandle);
3111 } else {
3112 newHandles.push_back(handle);
3113 }
3114 }
3115
3116 for (size_t i = 0; i < newHandles.size(); i++) {
3117 const sp<InputWindowHandle>& windowHandle = newHandles.itemAt(i);
Siarhei Vishniakou49ee3232018-12-03 15:10:36 -06003118 if (windowHandle->getInfo()->hasFocus && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003119 newFocusedWindowHandle = windowHandle;
3120 }
3121 if (windowHandle == mLastHoverWindowHandle) {
3122 foundHoveredWindow = true;
3123 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003124 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003125
3126 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003127 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 }
3129
3130 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003131 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 }
3133
Tiger Huang721e26f2018-07-24 22:26:19 +08003134 sp<InputWindowHandle> oldFocusedWindowHandle =
3135 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3136
3137 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3138 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003140 ALOGD("Focus left window: %s in display %" PRId32,
3141 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003143 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3144 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003145 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3147 "focus left window");
3148 synthesizeCancelationEventsForInputChannelLocked(
3149 focusedInputChannel, options);
3150 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003151 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003153 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003155 ALOGD("Focus entered window: %s in display %" PRId32,
3156 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003158 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 }
Robert Carrf759f162018-11-13 12:57:11 -08003160
3161 if (mFocusedDisplayId == displayId) {
3162 onFocusChangedLocked(newFocusedWindowHandle);
3163 }
3164
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 }
3166
Arthur Hungb92218b2018-08-14 12:00:21 +08003167 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3168 if (stateIndex >= 0) {
3169 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003170 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003171 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003172 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003174 ALOGD("Touched window was removed: %s in display %" PRId32,
3175 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003177 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003178 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003179 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003180 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3181 "touched window was removed");
3182 synthesizeCancelationEventsForInputChannelLocked(
3183 touchedInputChannel, options);
3184 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003185 state.windows.removeAt(i);
3186 } else {
3187 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 }
3190 }
3191
3192 // Release information for windows that are no longer present.
3193 // This ensures that unused input channels are released promptly.
3194 // Otherwise, they might stick around until the window handle is destroyed
3195 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003196 size_t numWindows = oldWindowHandles.size();
3197 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003199 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003201 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003203 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 }
3205 }
3206 } // release lock
3207
3208 // Wake up poll loop since it may need to make new input dispatching choices.
3209 mLooper->wake();
3210}
3211
3212void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003213 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003215 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216#endif
3217 { // acquire lock
3218 AutoMutex _l(mLock);
3219
Tiger Huang721e26f2018-07-24 22:26:19 +08003220 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3221 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003222 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003223 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3224 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003226 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003228 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003230 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003232 oldFocusedApplicationHandle->releaseInfo();
3233 oldFocusedApplicationHandle.clear();
3234 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 }
3236
3237#if DEBUG_FOCUS
3238 //logDispatchStateLocked();
3239#endif
3240 } // release lock
3241
3242 // Wake up poll loop since it may need to make new input dispatching choices.
3243 mLooper->wake();
3244}
3245
Tiger Huang721e26f2018-07-24 22:26:19 +08003246/**
3247 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3248 * the display not specified.
3249 *
3250 * We track any unreleased events for each window. If a window loses the ability to receive the
3251 * released event, we will send a cancel event to it. So when the focused display is changed, we
3252 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3253 * display. The display-specified events won't be affected.
3254 */
3255void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3256#if DEBUG_FOCUS
3257 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3258#endif
3259 { // acquire lock
3260 AutoMutex _l(mLock);
3261
3262 if (mFocusedDisplayId != displayId) {
3263 sp<InputWindowHandle> oldFocusedWindowHandle =
3264 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3265 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003266 sp<InputChannel> inputChannel =
3267 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003268 if (inputChannel != nullptr) {
3269 CancelationOptions options(
3270 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3271 "The display which contains this window no longer has focus.");
3272 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3273 }
3274 }
3275 mFocusedDisplayId = displayId;
3276
3277 // Sanity check
3278 sp<InputWindowHandle> newFocusedWindowHandle =
3279 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Robert Carrf759f162018-11-13 12:57:11 -08003280 onFocusChangedLocked(newFocusedWindowHandle);
3281
Tiger Huang721e26f2018-07-24 22:26:19 +08003282 if (newFocusedWindowHandle == nullptr) {
3283 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3284 if (!mFocusedWindowHandlesByDisplay.empty()) {
3285 ALOGE("But another display has a focused window:");
3286 for (auto& it : mFocusedWindowHandlesByDisplay) {
3287 const int32_t displayId = it.first;
3288 const sp<InputWindowHandle>& windowHandle = it.second;
3289 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3290 displayId, windowHandle->getName().c_str());
3291 }
3292 }
3293 }
3294 }
3295
3296#if DEBUG_FOCUS
3297 logDispatchStateLocked();
3298#endif
3299 } // release lock
3300
3301 // Wake up poll loop since it may need to make new input dispatching choices.
3302 mLooper->wake();
3303}
3304
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3306#if DEBUG_FOCUS
3307 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3308#endif
3309
3310 bool changed;
3311 { // acquire lock
3312 AutoMutex _l(mLock);
3313
3314 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3315 if (mDispatchFrozen && !frozen) {
3316 resetANRTimeoutsLocked();
3317 }
3318
3319 if (mDispatchEnabled && !enabled) {
3320 resetAndDropEverythingLocked("dispatcher is being disabled");
3321 }
3322
3323 mDispatchEnabled = enabled;
3324 mDispatchFrozen = frozen;
3325 changed = true;
3326 } else {
3327 changed = false;
3328 }
3329
3330#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003331 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332#endif
3333 } // release lock
3334
3335 if (changed) {
3336 // Wake up poll loop since it may need to make new input dispatching choices.
3337 mLooper->wake();
3338 }
3339}
3340
3341void InputDispatcher::setInputFilterEnabled(bool enabled) {
3342#if DEBUG_FOCUS
3343 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3344#endif
3345
3346 { // acquire lock
3347 AutoMutex _l(mLock);
3348
3349 if (mInputFilterEnabled == enabled) {
3350 return;
3351 }
3352
3353 mInputFilterEnabled = enabled;
3354 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3355 } // release lock
3356
3357 // Wake up poll loop since there might be work to do to drop everything.
3358 mLooper->wake();
3359}
3360
3361bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3362 const sp<InputChannel>& toChannel) {
3363#if DEBUG_FOCUS
3364 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003365 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366#endif
3367 { // acquire lock
3368 AutoMutex _l(mLock);
3369
3370 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3371 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07003372 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373#if DEBUG_FOCUS
3374 ALOGD("Cannot transfer focus because from or to window not found.");
3375#endif
3376 return false;
3377 }
3378 if (fromWindowHandle == toWindowHandle) {
3379#if DEBUG_FOCUS
3380 ALOGD("Trivial transfer to same window.");
3381#endif
3382 return true;
3383 }
3384 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3385#if DEBUG_FOCUS
3386 ALOGD("Cannot transfer focus because windows are on different displays.");
3387#endif
3388 return false;
3389 }
3390
3391 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003392 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3393 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3394 for (size_t i = 0; i < state.windows.size(); i++) {
3395 const TouchedWindow& touchedWindow = state.windows[i];
3396 if (touchedWindow.windowHandle == fromWindowHandle) {
3397 int32_t oldTargetFlags = touchedWindow.targetFlags;
3398 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399
Jeff Brownf086ddb2014-02-11 14:28:48 -08003400 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401
Jeff Brownf086ddb2014-02-11 14:28:48 -08003402 int32_t newTargetFlags = oldTargetFlags
3403 & (InputTarget::FLAG_FOREGROUND
3404 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3405 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406
Jeff Brownf086ddb2014-02-11 14:28:48 -08003407 found = true;
3408 goto Found;
3409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 }
3411 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003412Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413
3414 if (! found) {
3415#if DEBUG_FOCUS
3416 ALOGD("Focus transfer failed because from window did not have focus.");
3417#endif
3418 return false;
3419 }
3420
3421 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3422 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3423 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3424 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3425 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3426
3427 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3428 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3429 "transferring touch focus from this window to another window");
3430 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3431 }
3432
3433#if DEBUG_FOCUS
3434 logDispatchStateLocked();
3435#endif
3436 } // release lock
3437
3438 // Wake up poll loop since it may need to make new input dispatching choices.
3439 mLooper->wake();
3440 return true;
3441}
3442
3443void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3444#if DEBUG_FOCUS
3445 ALOGD("Resetting and dropping all events (%s).", reason);
3446#endif
3447
3448 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3449 synthesizeCancelationEventsForAllConnectionsLocked(options);
3450
3451 resetKeyRepeatLocked();
3452 releasePendingEventLocked();
3453 drainInboundQueueLocked();
3454 resetANRTimeoutsLocked();
3455
Jeff Brownf086ddb2014-02-11 14:28:48 -08003456 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003458 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459}
3460
3461void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003462 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463 dumpDispatchStateLocked(dump);
3464
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003465 std::istringstream stream(dump);
3466 std::string line;
3467
3468 while (std::getline(stream, line, '\n')) {
3469 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470 }
3471}
3472
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003473void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3474 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3475 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003476 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477
Tiger Huang721e26f2018-07-24 22:26:19 +08003478 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3479 dump += StringPrintf(INDENT "FocusedApplications:\n");
3480 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3481 const int32_t displayId = it.first;
3482 const sp<InputApplicationHandle>& applicationHandle = it.second;
3483 dump += StringPrintf(
3484 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3485 displayId,
3486 applicationHandle->getName().c_str(),
3487 applicationHandle->getDispatchingTimeout(
3488 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3489 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003491 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003493
3494 if (!mFocusedWindowHandlesByDisplay.empty()) {
3495 dump += StringPrintf(INDENT "FocusedWindows:\n");
3496 for (auto& it : mFocusedWindowHandlesByDisplay) {
3497 const int32_t displayId = it.first;
3498 const sp<InputWindowHandle>& windowHandle = it.second;
3499 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3500 displayId, windowHandle->getName().c_str());
3501 }
3502 } else {
3503 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505
Jeff Brownf086ddb2014-02-11 14:28:48 -08003506 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003507 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003508 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3509 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003510 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003511 state.displayId, toString(state.down), toString(state.split),
3512 state.deviceId, state.source);
3513 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003514 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003515 for (size_t i = 0; i < state.windows.size(); i++) {
3516 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003517 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3518 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003519 touchedWindow.pointerIds.value,
3520 touchedWindow.targetFlags);
3521 }
3522 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003523 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003525 }
3526 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003527 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 }
3529
Arthur Hungb92218b2018-08-14 12:00:21 +08003530 if (!mWindowHandlesByDisplay.empty()) {
3531 for (auto& it : mWindowHandlesByDisplay) {
3532 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003533 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003534 if (!windowHandles.isEmpty()) {
3535 dump += INDENT2 "Windows:\n";
3536 for (size_t i = 0; i < windowHandles.size(); i++) {
3537 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3538 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539
Arthur Hungb92218b2018-08-14 12:00:21 +08003540 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3541 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3542 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Robert Carre07e1032018-11-26 12:55:53 -08003543 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=%f,%f"
Arthur Hungb92218b2018-08-14 12:00:21 +08003544 "touchableRegion=",
3545 i, windowInfo->name.c_str(), windowInfo->displayId,
3546 toString(windowInfo->paused),
3547 toString(windowInfo->hasFocus),
3548 toString(windowInfo->hasWallpaper),
3549 toString(windowInfo->visible),
3550 toString(windowInfo->canReceiveKeys),
3551 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3552 windowInfo->layer,
3553 windowInfo->frameLeft, windowInfo->frameTop,
3554 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003555 windowInfo->globalScaleFactor,
3556 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003557 dumpRegion(dump, windowInfo->touchableRegion);
3558 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3559 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3560 windowInfo->ownerPid, windowInfo->ownerUid,
3561 windowInfo->dispatchingTimeout / 1000000.0);
3562 }
3563 } else {
3564 dump += INDENT2 "Windows: <none>\n";
3565 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566 }
3567 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003568 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569 }
3570
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003571 if (!mMonitoringChannelsByDisplay.empty()) {
3572 for (auto& it : mMonitoringChannelsByDisplay) {
3573 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003574 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003575 const size_t numChannels = monitoringChannels.size();
3576 for (size_t i = 0; i < numChannels; i++) {
3577 const sp<InputChannel>& channel = monitoringChannels[i];
3578 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3579 }
3580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003582 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 }
3584
3585 nsecs_t currentTime = now();
3586
3587 // Dump recently dispatched or dropped events from oldest to newest.
3588 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003589 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003591 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003593 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 (currentTime - entry->eventTime) * 0.000001f);
3595 }
3596 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003597 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 }
3599
3600 // Dump event currently being dispatched.
3601 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003602 dump += INDENT "PendingEvent:\n";
3603 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003605 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3607 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003608 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 }
3610
3611 // Dump inbound events from oldest to newest.
3612 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003613 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003615 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003617 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 (currentTime - entry->eventTime) * 0.000001f);
3619 }
3620 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003621 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 }
3623
Michael Wright78f24442014-08-06 15:55:28 -07003624 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003625 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003626 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3627 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3628 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003629 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003630 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3631 }
3632 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003633 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003634 }
3635
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003637 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3639 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003640 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003642 i, connection->getInputChannelName().c_str(),
3643 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 connection->getStatusLabel(), toString(connection->monitor),
3645 toString(connection->inputPublisherBlocked));
3646
3647 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003648 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 connection->outboundQueue.count());
3650 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3651 entry = entry->next) {
3652 dump.append(INDENT4);
3653 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003654 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655 entry->targetFlags, entry->resolvedAction,
3656 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3657 }
3658 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003659 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 }
3661
3662 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003663 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 connection->waitQueue.count());
3665 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3666 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003667 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003669 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 "age=%0.1fms, wait=%0.1fms\n",
3671 entry->targetFlags, entry->resolvedAction,
3672 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3673 (currentTime - entry->deliveryTime) * 0.000001f);
3674 }
3675 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003676 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 }
3678 }
3679 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003680 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 }
3682
3683 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003684 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 (mAppSwitchDueTime - now()) / 1000000.0);
3686 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003687 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 }
3689
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003690 dump += INDENT "Configuration:\n";
3691 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003693 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 mConfig.keyRepeatTimeout * 0.000001f);
3695}
3696
Robert Carr803535b2018-08-02 16:38:15 -07003697status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003699 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3700 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701#endif
3702
3703 { // acquire lock
3704 AutoMutex _l(mLock);
3705
Robert Carr4e670e52018-08-15 13:26:12 -07003706 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3707 // treat inputChannel as monitor channel for displayId.
3708 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3709 if (monitor) {
3710 inputChannel->setToken(new BBinder());
3711 }
3712
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 if (getConnectionIndexLocked(inputChannel) >= 0) {
3714 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003715 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 return BAD_VALUE;
3717 }
3718
Robert Carr803535b2018-08-02 16:38:15 -07003719 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720
3721 int fd = inputChannel->getFd();
3722 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003723 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003725 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003727 Vector<sp<InputChannel>>& monitoringChannels =
3728 mMonitoringChannelsByDisplay[displayId];
3729 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 }
3731
3732 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3733 } // release lock
3734
3735 // Wake the looper because some connections have changed.
3736 mLooper->wake();
3737 return OK;
3738}
3739
3740status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3741#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003742 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743#endif
3744
3745 { // acquire lock
3746 AutoMutex _l(mLock);
3747
3748 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3749 if (status) {
3750 return status;
3751 }
3752 } // release lock
3753
3754 // Wake the poll loop because removing the connection may have changed the current
3755 // synchronization state.
3756 mLooper->wake();
3757 return OK;
3758}
3759
3760status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3761 bool notify) {
3762 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3763 if (connectionIndex < 0) {
3764 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003765 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 return BAD_VALUE;
3767 }
3768
3769 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3770 mConnectionsByFd.removeItemsAt(connectionIndex);
3771
Robert Carr5c8a0262018-10-03 16:30:44 -07003772 mInputChannelsByToken.erase(inputChannel->getToken());
3773
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 if (connection->monitor) {
3775 removeMonitorChannelLocked(inputChannel);
3776 }
3777
3778 mLooper->removeFd(inputChannel->getFd());
3779
3780 nsecs_t currentTime = now();
3781 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3782
3783 connection->status = Connection::STATUS_ZOMBIE;
3784 return OK;
3785}
3786
3787void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003788 for (auto it = mMonitoringChannelsByDisplay.begin();
3789 it != mMonitoringChannelsByDisplay.end(); ) {
3790 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3791 const size_t numChannels = monitoringChannels.size();
3792 for (size_t i = 0; i < numChannels; i++) {
3793 if (monitoringChannels[i] == inputChannel) {
3794 monitoringChannels.removeAt(i);
3795 break;
3796 }
3797 }
3798 if (monitoringChannels.empty()) {
3799 it = mMonitoringChannelsByDisplay.erase(it);
3800 } else {
3801 ++it;
3802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 }
3804}
3805
3806ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003807 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003808 return -1;
3809 }
3810
Robert Carr4e670e52018-08-15 13:26:12 -07003811 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3812 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3813 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3814 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 }
3816 }
Robert Carr4e670e52018-08-15 13:26:12 -07003817
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 return -1;
3819}
3820
3821void InputDispatcher::onDispatchCycleFinishedLocked(
3822 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3823 CommandEntry* commandEntry = postCommandLocked(
3824 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3825 commandEntry->connection = connection;
3826 commandEntry->eventTime = currentTime;
3827 commandEntry->seq = seq;
3828 commandEntry->handled = handled;
3829}
3830
3831void InputDispatcher::onDispatchCycleBrokenLocked(
3832 nsecs_t currentTime, const sp<Connection>& connection) {
3833 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003834 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835
3836 CommandEntry* commandEntry = postCommandLocked(
3837 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3838 commandEntry->connection = connection;
3839}
3840
Robert Carrf759f162018-11-13 12:57:11 -08003841void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& newFocus) {
3842 sp<IBinder> token = newFocus != nullptr ? newFocus->getToken() : nullptr;
3843 CommandEntry* commandEntry = postCommandLocked(
3844 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
3845 commandEntry->token = token;
3846}
3847
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848void InputDispatcher::onANRLocked(
3849 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3850 const sp<InputWindowHandle>& windowHandle,
3851 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3852 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3853 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3854 ALOGI("Application is not responding: %s. "
3855 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003856 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857 dispatchLatency, waitDuration, reason);
3858
3859 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003860 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861 struct tm tm;
3862 localtime_r(&t, &tm);
3863 char timestr[64];
3864 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3865 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003866 mLastANRState += INDENT "ANR:\n";
3867 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3868 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3869 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3870 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3871 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3872 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873 dumpDispatchStateLocked(mLastANRState);
3874
3875 CommandEntry* commandEntry = postCommandLocked(
3876 & InputDispatcher::doNotifyANRLockedInterruptible);
3877 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003878 commandEntry->inputChannel = windowHandle != nullptr ?
3879 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003880 commandEntry->reason = reason;
3881}
3882
3883void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3884 CommandEntry* commandEntry) {
3885 mLock.unlock();
3886
3887 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3888
3889 mLock.lock();
3890}
3891
3892void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3893 CommandEntry* commandEntry) {
3894 sp<Connection> connection = commandEntry->connection;
3895
3896 if (connection->status != Connection::STATUS_ZOMBIE) {
3897 mLock.unlock();
3898
Robert Carr803535b2018-08-02 16:38:15 -07003899 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900
3901 mLock.lock();
3902 }
3903}
3904
Robert Carrf759f162018-11-13 12:57:11 -08003905void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3906 CommandEntry* commandEntry) {
3907 sp<IBinder> token = commandEntry->token;
3908 mLock.unlock();
3909 mPolicy->notifyFocusChanged(token);
3910 mLock.lock();
3911}
3912
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913void InputDispatcher::doNotifyANRLockedInterruptible(
3914 CommandEntry* commandEntry) {
3915 mLock.unlock();
3916
3917 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003918 commandEntry->inputApplicationHandle,
3919 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 commandEntry->reason);
3921
3922 mLock.lock();
3923
3924 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003925 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926}
3927
3928void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3929 CommandEntry* commandEntry) {
3930 KeyEntry* entry = commandEntry->keyEntry;
3931
3932 KeyEvent event;
3933 initializeKeyEvent(&event, entry);
3934
3935 mLock.unlock();
3936
Michael Wright2b3c3302018-03-02 17:19:13 +00003937 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003938 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3939 commandEntry->inputChannel->getToken() : nullptr;
3940 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003942 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3943 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3944 std::to_string(t.duration().count()).c_str());
3945 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946
3947 mLock.lock();
3948
3949 if (delay < 0) {
3950 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3951 } else if (!delay) {
3952 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3953 } else {
3954 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3955 entry->interceptKeyWakeupTime = now() + delay;
3956 }
3957 entry->release();
3958}
3959
3960void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3961 CommandEntry* commandEntry) {
3962 sp<Connection> connection = commandEntry->connection;
3963 nsecs_t finishTime = commandEntry->eventTime;
3964 uint32_t seq = commandEntry->seq;
3965 bool handled = commandEntry->handled;
3966
3967 // Handle post-event policy actions.
3968 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3969 if (dispatchEntry) {
3970 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3971 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003972 std::string msg =
3973 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003974 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003976 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 }
3978
3979 bool restartEvent;
3980 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3981 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3982 restartEvent = afterKeyEventLockedInterruptible(connection,
3983 dispatchEntry, keyEntry, handled);
3984 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3985 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3986 restartEvent = afterMotionEventLockedInterruptible(connection,
3987 dispatchEntry, motionEntry, handled);
3988 } else {
3989 restartEvent = false;
3990 }
3991
3992 // Dequeue the event and start the next cycle.
3993 // Note that because the lock might have been released, it is possible that the
3994 // contents of the wait queue to have been drained, so we need to double-check
3995 // a few things.
3996 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3997 connection->waitQueue.dequeue(dispatchEntry);
3998 traceWaitQueueLengthLocked(connection);
3999 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4000 connection->outboundQueue.enqueueAtHead(dispatchEntry);
4001 traceOutboundQueueLengthLocked(connection);
4002 } else {
4003 releaseDispatchEntryLocked(dispatchEntry);
4004 }
4005 }
4006
4007 // Start the next dispatch cycle for this connection.
4008 startDispatchCycleLocked(now(), connection);
4009 }
4010}
4011
4012bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4013 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
4014 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
4015 // Get the fallback key state.
4016 // Clear it out after dispatching the UP.
4017 int32_t originalKeyCode = keyEntry->keyCode;
4018 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4019 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4020 connection->inputState.removeFallbackKey(originalKeyCode);
4021 }
4022
4023 if (handled || !dispatchEntry->hasForegroundTarget()) {
4024 // If the application handles the original key for which we previously
4025 // generated a fallback or if the window is not a foreground window,
4026 // then cancel the associated fallback key, if any.
4027 if (fallbackKeyCode != -1) {
4028 // Dispatch the unhandled key to the policy with the cancel flag.
4029#if DEBUG_OUTBOUND_EVENT_DETAILS
4030 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
4031 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4032 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4033 keyEntry->policyFlags);
4034#endif
4035 KeyEvent event;
4036 initializeKeyEvent(&event, keyEntry);
4037 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
4038
4039 mLock.unlock();
4040
Robert Carr803535b2018-08-02 16:38:15 -07004041 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004042 &event, keyEntry->policyFlags, &event);
4043
4044 mLock.lock();
4045
4046 // Cancel the fallback key.
4047 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
4048 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4049 "application handled the original non-fallback key "
4050 "or is no longer a foreground target, "
4051 "canceling previously dispatched fallback key");
4052 options.keyCode = fallbackKeyCode;
4053 synthesizeCancelationEventsForConnectionLocked(connection, options);
4054 }
4055 connection->inputState.removeFallbackKey(originalKeyCode);
4056 }
4057 } else {
4058 // If the application did not handle a non-fallback key, first check
4059 // that we are in a good state to perform unhandled key event processing
4060 // Then ask the policy what to do with it.
4061 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4062 && keyEntry->repeatCount == 0;
4063 if (fallbackKeyCode == -1 && !initialDown) {
4064#if DEBUG_OUTBOUND_EVENT_DETAILS
4065 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4066 "since this is not an initial down. "
4067 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4068 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4069 keyEntry->policyFlags);
4070#endif
4071 return false;
4072 }
4073
4074 // Dispatch the unhandled key to the policy.
4075#if DEBUG_OUTBOUND_EVENT_DETAILS
4076 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4077 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4078 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4079 keyEntry->policyFlags);
4080#endif
4081 KeyEvent event;
4082 initializeKeyEvent(&event, keyEntry);
4083
4084 mLock.unlock();
4085
Robert Carr803535b2018-08-02 16:38:15 -07004086 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 &event, keyEntry->policyFlags, &event);
4088
4089 mLock.lock();
4090
4091 if (connection->status != Connection::STATUS_NORMAL) {
4092 connection->inputState.removeFallbackKey(originalKeyCode);
4093 return false;
4094 }
4095
4096 // Latch the fallback keycode for this key on an initial down.
4097 // The fallback keycode cannot change at any other point in the lifecycle.
4098 if (initialDown) {
4099 if (fallback) {
4100 fallbackKeyCode = event.getKeyCode();
4101 } else {
4102 fallbackKeyCode = AKEYCODE_UNKNOWN;
4103 }
4104 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4105 }
4106
4107 ALOG_ASSERT(fallbackKeyCode != -1);
4108
4109 // Cancel the fallback key if the policy decides not to send it anymore.
4110 // We will continue to dispatch the key to the policy but we will no
4111 // longer dispatch a fallback key to the application.
4112 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4113 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4114#if DEBUG_OUTBOUND_EVENT_DETAILS
4115 if (fallback) {
4116 ALOGD("Unhandled key event: Policy requested to send key %d"
4117 "as a fallback for %d, but on the DOWN it had requested "
4118 "to send %d instead. Fallback canceled.",
4119 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4120 } else {
4121 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4122 "but on the DOWN it had requested to send %d. "
4123 "Fallback canceled.",
4124 originalKeyCode, fallbackKeyCode);
4125 }
4126#endif
4127
4128 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4129 "canceling fallback, policy no longer desires it");
4130 options.keyCode = fallbackKeyCode;
4131 synthesizeCancelationEventsForConnectionLocked(connection, options);
4132
4133 fallback = false;
4134 fallbackKeyCode = AKEYCODE_UNKNOWN;
4135 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4136 connection->inputState.setFallbackKey(originalKeyCode,
4137 fallbackKeyCode);
4138 }
4139 }
4140
4141#if DEBUG_OUTBOUND_EVENT_DETAILS
4142 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004143 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4145 connection->inputState.getFallbackKeys();
4146 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004147 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 fallbackKeys.valueAt(i));
4149 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07004150 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004151 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 }
4153#endif
4154
4155 if (fallback) {
4156 // Restart the dispatch cycle using the fallback key.
4157 keyEntry->eventTime = event.getEventTime();
4158 keyEntry->deviceId = event.getDeviceId();
4159 keyEntry->source = event.getSource();
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004160 keyEntry->displayId = event.getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4162 keyEntry->keyCode = fallbackKeyCode;
4163 keyEntry->scanCode = event.getScanCode();
4164 keyEntry->metaState = event.getMetaState();
4165 keyEntry->repeatCount = event.getRepeatCount();
4166 keyEntry->downTime = event.getDownTime();
4167 keyEntry->syntheticRepeat = false;
4168
4169#if DEBUG_OUTBOUND_EVENT_DETAILS
4170 ALOGD("Unhandled key event: Dispatching fallback key. "
4171 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4172 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4173#endif
4174 return true; // restart the event
4175 } else {
4176#if DEBUG_OUTBOUND_EVENT_DETAILS
4177 ALOGD("Unhandled key event: No fallback key.");
4178#endif
4179 }
4180 }
4181 }
4182 return false;
4183}
4184
4185bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4186 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4187 return false;
4188}
4189
4190void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4191 mLock.unlock();
4192
4193 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4194
4195 mLock.lock();
4196}
4197
4198void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004199 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4201 entry->downTime, entry->eventTime);
4202}
4203
4204void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4205 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4206 // TODO Write some statistics about how long we spend waiting.
4207}
4208
4209void InputDispatcher::traceInboundQueueLengthLocked() {
4210 if (ATRACE_ENABLED()) {
4211 ATRACE_INT("iq", mInboundQueue.count());
4212 }
4213}
4214
4215void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4216 if (ATRACE_ENABLED()) {
4217 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004218 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 ATRACE_INT(counterName, connection->outboundQueue.count());
4220 }
4221}
4222
4223void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4224 if (ATRACE_ENABLED()) {
4225 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004226 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 ATRACE_INT(counterName, connection->waitQueue.count());
4228 }
4229}
4230
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004231void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 AutoMutex _l(mLock);
4233
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004234 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 dumpDispatchStateLocked(dump);
4236
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004237 if (!mLastANRState.empty()) {
4238 dump += "\nInput Dispatcher State at time of last ANR:\n";
4239 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 }
4241}
4242
4243void InputDispatcher::monitor() {
4244 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4245 mLock.lock();
4246 mLooper->wake();
4247 mDispatcherIsAliveCondition.wait(mLock);
4248 mLock.unlock();
4249}
4250
4251
Michael Wrightd02c5b62014-02-10 15:10:22 -08004252// --- InputDispatcher::InjectionState ---
4253
4254InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4255 refCount(1),
4256 injectorPid(injectorPid), injectorUid(injectorUid),
4257 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4258 pendingForegroundDispatches(0) {
4259}
4260
4261InputDispatcher::InjectionState::~InjectionState() {
4262}
4263
4264void InputDispatcher::InjectionState::release() {
4265 refCount -= 1;
4266 if (refCount == 0) {
4267 delete this;
4268 } else {
4269 ALOG_ASSERT(refCount > 0);
4270 }
4271}
4272
4273
4274// --- InputDispatcher::EventEntry ---
4275
4276InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4277 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
Yi Kong9b14ac62018-07-17 13:48:38 -07004278 injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004279}
4280
4281InputDispatcher::EventEntry::~EventEntry() {
4282 releaseInjectionState();
4283}
4284
4285void InputDispatcher::EventEntry::release() {
4286 refCount -= 1;
4287 if (refCount == 0) {
4288 delete this;
4289 } else {
4290 ALOG_ASSERT(refCount > 0);
4291 }
4292}
4293
4294void InputDispatcher::EventEntry::releaseInjectionState() {
4295 if (injectionState) {
4296 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004297 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 }
4299}
4300
4301
4302// --- InputDispatcher::ConfigurationChangedEntry ---
4303
4304InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4305 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4306}
4307
4308InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4309}
4310
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004311void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4312 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313}
4314
4315
4316// --- InputDispatcher::DeviceResetEntry ---
4317
4318InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4319 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4320 deviceId(deviceId) {
4321}
4322
4323InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4324}
4325
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004326void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4327 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 deviceId, policyFlags);
4329}
4330
4331
4332// --- InputDispatcher::KeyEntry ---
4333
4334InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004335 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4337 int32_t repeatCount, nsecs_t downTime) :
4338 EventEntry(TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004339 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4341 repeatCount(repeatCount), downTime(downTime),
4342 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4343 interceptKeyWakeupTime(0) {
4344}
4345
4346InputDispatcher::KeyEntry::~KeyEntry() {
4347}
4348
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004349void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004350 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4352 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004353 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004354 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355}
4356
4357void InputDispatcher::KeyEntry::recycle() {
4358 releaseInjectionState();
4359
4360 dispatchInProgress = false;
4361 syntheticRepeat = false;
4362 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4363 interceptKeyWakeupTime = 0;
4364}
4365
4366
4367// --- InputDispatcher::MotionEntry ---
4368
Michael Wright7b159c92015-05-14 14:48:03 +01004369InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004370 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4371 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004372 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4373 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004374 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004375 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4376 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4378 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004379 deviceId(deviceId), source(source), displayId(displayId), action(action),
4380 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004381 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004382 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 for (uint32_t i = 0; i < pointerCount; i++) {
4384 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4385 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004386 if (xOffset || yOffset) {
4387 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4388 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 }
4390}
4391
4392InputDispatcher::MotionEntry::~MotionEntry() {
4393}
4394
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004395void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004396 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004397 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004398 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004399 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4400 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4401
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402 for (uint32_t i = 0; i < pointerCount; i++) {
4403 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004404 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004405 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004406 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 pointerCoords[i].getX(), pointerCoords[i].getY());
4408 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004409 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004410}
4411
4412
4413// --- InputDispatcher::DispatchEntry ---
4414
4415volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4416
4417InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004418 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4419 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 seq(nextSeq()),
4421 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004422 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4423 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4425 eventEntry->refCount += 1;
4426}
4427
4428InputDispatcher::DispatchEntry::~DispatchEntry() {
4429 eventEntry->release();
4430}
4431
4432uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4433 // Sequence number 0 is reserved and will never be returned.
4434 uint32_t seq;
4435 do {
4436 seq = android_atomic_inc(&sNextSeqAtomic);
4437 } while (!seq);
4438 return seq;
4439}
4440
4441
4442// --- InputDispatcher::InputState ---
4443
4444InputDispatcher::InputState::InputState() {
4445}
4446
4447InputDispatcher::InputState::~InputState() {
4448}
4449
4450bool InputDispatcher::InputState::isNeutral() const {
4451 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4452}
4453
4454bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4455 int32_t displayId) const {
4456 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4457 const MotionMemento& memento = mMotionMementos.itemAt(i);
4458 if (memento.deviceId == deviceId
4459 && memento.source == source
4460 && memento.displayId == displayId
4461 && memento.hovering) {
4462 return true;
4463 }
4464 }
4465 return false;
4466}
4467
4468bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4469 int32_t action, int32_t flags) {
4470 switch (action) {
4471 case AKEY_EVENT_ACTION_UP: {
4472 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4473 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4474 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4475 mFallbackKeys.removeItemsAt(i);
4476 } else {
4477 i += 1;
4478 }
4479 }
4480 }
4481 ssize_t index = findKeyMemento(entry);
4482 if (index >= 0) {
4483 mKeyMementos.removeAt(index);
4484 return true;
4485 }
4486 /* FIXME: We can't just drop the key up event because that prevents creating
4487 * popup windows that are automatically shown when a key is held and then
4488 * dismissed when the key is released. The problem is that the popup will
4489 * not have received the original key down, so the key up will be considered
4490 * to be inconsistent with its observed state. We could perhaps handle this
4491 * by synthesizing a key down but that will cause other problems.
4492 *
4493 * So for now, allow inconsistent key up events to be dispatched.
4494 *
4495#if DEBUG_OUTBOUND_EVENT_DETAILS
4496 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4497 "keyCode=%d, scanCode=%d",
4498 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4499#endif
4500 return false;
4501 */
4502 return true;
4503 }
4504
4505 case AKEY_EVENT_ACTION_DOWN: {
4506 ssize_t index = findKeyMemento(entry);
4507 if (index >= 0) {
4508 mKeyMementos.removeAt(index);
4509 }
4510 addKeyMemento(entry, flags);
4511 return true;
4512 }
4513
4514 default:
4515 return true;
4516 }
4517}
4518
4519bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4520 int32_t action, int32_t flags) {
4521 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4522 switch (actionMasked) {
4523 case AMOTION_EVENT_ACTION_UP:
4524 case AMOTION_EVENT_ACTION_CANCEL: {
4525 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4526 if (index >= 0) {
4527 mMotionMementos.removeAt(index);
4528 return true;
4529 }
4530#if DEBUG_OUTBOUND_EVENT_DETAILS
4531 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004532 "displayId=%" PRId32 ", actionMasked=%d",
4533 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004534#endif
4535 return false;
4536 }
4537
4538 case AMOTION_EVENT_ACTION_DOWN: {
4539 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4540 if (index >= 0) {
4541 mMotionMementos.removeAt(index);
4542 }
4543 addMotionMemento(entry, flags, false /*hovering*/);
4544 return true;
4545 }
4546
4547 case AMOTION_EVENT_ACTION_POINTER_UP:
4548 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4549 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004550 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4551 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4552 // generate cancellation events for these since they're based in relative rather than
4553 // absolute units.
4554 return true;
4555 }
4556
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004558
4559 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4560 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4561 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4562 // other value and we need to track the motion so we can send cancellation events for
4563 // anything generating fallback events (e.g. DPad keys for joystick movements).
4564 if (index >= 0) {
4565 if (entry->pointerCoords[0].isEmpty()) {
4566 mMotionMementos.removeAt(index);
4567 } else {
4568 MotionMemento& memento = mMotionMementos.editItemAt(index);
4569 memento.setPointers(entry);
4570 }
4571 } else if (!entry->pointerCoords[0].isEmpty()) {
4572 addMotionMemento(entry, flags, false /*hovering*/);
4573 }
4574
4575 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4576 return true;
4577 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004578 if (index >= 0) {
4579 MotionMemento& memento = mMotionMementos.editItemAt(index);
4580 memento.setPointers(entry);
4581 return true;
4582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004583#if DEBUG_OUTBOUND_EVENT_DETAILS
4584 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004585 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4586 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587#endif
4588 return false;
4589 }
4590
4591 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4592 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4593 if (index >= 0) {
4594 mMotionMementos.removeAt(index);
4595 return true;
4596 }
4597#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004598 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4599 "displayId=%" PRId32,
4600 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601#endif
4602 return false;
4603 }
4604
4605 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4606 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4607 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4608 if (index >= 0) {
4609 mMotionMementos.removeAt(index);
4610 }
4611 addMotionMemento(entry, flags, true /*hovering*/);
4612 return true;
4613 }
4614
4615 default:
4616 return true;
4617 }
4618}
4619
4620ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4621 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4622 const KeyMemento& memento = mKeyMementos.itemAt(i);
4623 if (memento.deviceId == entry->deviceId
4624 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004625 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626 && memento.keyCode == entry->keyCode
4627 && memento.scanCode == entry->scanCode) {
4628 return i;
4629 }
4630 }
4631 return -1;
4632}
4633
4634ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4635 bool hovering) const {
4636 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4637 const MotionMemento& memento = mMotionMementos.itemAt(i);
4638 if (memento.deviceId == entry->deviceId
4639 && memento.source == entry->source
4640 && memento.displayId == entry->displayId
4641 && memento.hovering == hovering) {
4642 return i;
4643 }
4644 }
4645 return -1;
4646}
4647
4648void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4649 mKeyMementos.push();
4650 KeyMemento& memento = mKeyMementos.editTop();
4651 memento.deviceId = entry->deviceId;
4652 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004653 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654 memento.keyCode = entry->keyCode;
4655 memento.scanCode = entry->scanCode;
4656 memento.metaState = entry->metaState;
4657 memento.flags = flags;
4658 memento.downTime = entry->downTime;
4659 memento.policyFlags = entry->policyFlags;
4660}
4661
4662void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4663 int32_t flags, bool hovering) {
4664 mMotionMementos.push();
4665 MotionMemento& memento = mMotionMementos.editTop();
4666 memento.deviceId = entry->deviceId;
4667 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004668 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669 memento.flags = flags;
4670 memento.xPrecision = entry->xPrecision;
4671 memento.yPrecision = entry->yPrecision;
4672 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673 memento.setPointers(entry);
4674 memento.hovering = hovering;
4675 memento.policyFlags = entry->policyFlags;
4676}
4677
4678void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4679 pointerCount = entry->pointerCount;
4680 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4681 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4682 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4683 }
4684}
4685
4686void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4687 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4688 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4689 const KeyMemento& memento = mKeyMementos.itemAt(i);
4690 if (shouldCancelKey(memento, options)) {
4691 outEvents.push(new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004692 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4694 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4695 }
4696 }
4697
4698 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4699 const MotionMemento& memento = mMotionMementos.itemAt(i);
4700 if (shouldCancelMotion(memento, options)) {
4701 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004702 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 memento.hovering
4704 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4705 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004706 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004708 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4709 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710 }
4711 }
4712}
4713
4714void InputDispatcher::InputState::clear() {
4715 mKeyMementos.clear();
4716 mMotionMementos.clear();
4717 mFallbackKeys.clear();
4718}
4719
4720void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4721 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4722 const MotionMemento& memento = mMotionMementos.itemAt(i);
4723 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4724 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4725 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4726 if (memento.deviceId == otherMemento.deviceId
4727 && memento.source == otherMemento.source
4728 && memento.displayId == otherMemento.displayId) {
4729 other.mMotionMementos.removeAt(j);
4730 } else {
4731 j += 1;
4732 }
4733 }
4734 other.mMotionMementos.push(memento);
4735 }
4736 }
4737}
4738
4739int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4740 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4741 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4742}
4743
4744void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4745 int32_t fallbackKeyCode) {
4746 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4747 if (index >= 0) {
4748 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4749 } else {
4750 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4751 }
4752}
4753
4754void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4755 mFallbackKeys.removeItem(originalKeyCode);
4756}
4757
4758bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4759 const CancelationOptions& options) {
4760 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4761 return false;
4762 }
4763
4764 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4765 return false;
4766 }
4767
4768 switch (options.mode) {
4769 case CancelationOptions::CANCEL_ALL_EVENTS:
4770 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4771 return true;
4772 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4773 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004774 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4775 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776 default:
4777 return false;
4778 }
4779}
4780
4781bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4782 const CancelationOptions& options) {
4783 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4784 return false;
4785 }
4786
4787 switch (options.mode) {
4788 case CancelationOptions::CANCEL_ALL_EVENTS:
4789 return true;
4790 case CancelationOptions::CANCEL_POINTER_EVENTS:
4791 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4792 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4793 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004794 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4795 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796 default:
4797 return false;
4798 }
4799}
4800
4801
4802// --- InputDispatcher::Connection ---
4803
Robert Carr803535b2018-08-02 16:38:15 -07004804InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4805 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806 monitor(monitor),
4807 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4808}
4809
4810InputDispatcher::Connection::~Connection() {
4811}
4812
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004813const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004814 if (inputChannel != nullptr) {
4815 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816 }
4817 if (monitor) {
4818 return "monitor";
4819 }
4820 return "?";
4821}
4822
4823const char* InputDispatcher::Connection::getStatusLabel() const {
4824 switch (status) {
4825 case STATUS_NORMAL:
4826 return "NORMAL";
4827
4828 case STATUS_BROKEN:
4829 return "BROKEN";
4830
4831 case STATUS_ZOMBIE:
4832 return "ZOMBIE";
4833
4834 default:
4835 return "UNKNOWN";
4836 }
4837}
4838
4839InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004840 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 if (entry->seq == seq) {
4842 return entry;
4843 }
4844 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004845 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846}
4847
4848
4849// --- InputDispatcher::CommandEntry ---
4850
4851InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004852 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853 seq(0), handled(false) {
4854}
4855
4856InputDispatcher::CommandEntry::~CommandEntry() {
4857}
4858
4859
4860// --- InputDispatcher::TouchState ---
4861
4862InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004863 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864}
4865
4866InputDispatcher::TouchState::~TouchState() {
4867}
4868
4869void InputDispatcher::TouchState::reset() {
4870 down = false;
4871 split = false;
4872 deviceId = -1;
4873 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004874 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 windows.clear();
4876}
4877
4878void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4879 down = other.down;
4880 split = other.split;
4881 deviceId = other.deviceId;
4882 source = other.source;
4883 displayId = other.displayId;
4884 windows = other.windows;
4885}
4886
4887void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4888 int32_t targetFlags, BitSet32 pointerIds) {
4889 if (targetFlags & InputTarget::FLAG_SPLIT) {
4890 split = true;
4891 }
4892
4893 for (size_t i = 0; i < windows.size(); i++) {
4894 TouchedWindow& touchedWindow = windows.editItemAt(i);
4895 if (touchedWindow.windowHandle == windowHandle) {
4896 touchedWindow.targetFlags |= targetFlags;
4897 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4898 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4899 }
4900 touchedWindow.pointerIds.value |= pointerIds.value;
4901 return;
4902 }
4903 }
4904
4905 windows.push();
4906
4907 TouchedWindow& touchedWindow = windows.editTop();
4908 touchedWindow.windowHandle = windowHandle;
4909 touchedWindow.targetFlags = targetFlags;
4910 touchedWindow.pointerIds = pointerIds;
4911}
4912
4913void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4914 for (size_t i = 0; i < windows.size(); i++) {
4915 if (windows.itemAt(i).windowHandle == windowHandle) {
4916 windows.removeAt(i);
4917 return;
4918 }
4919 }
4920}
4921
Robert Carr803535b2018-08-02 16:38:15 -07004922void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4923 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004924 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004925 windows.removeAt(i);
4926 return;
4927 }
4928 }
4929}
4930
Michael Wrightd02c5b62014-02-10 15:10:22 -08004931void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4932 for (size_t i = 0 ; i < windows.size(); ) {
4933 TouchedWindow& window = windows.editItemAt(i);
4934 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4935 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4936 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4937 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4938 i += 1;
4939 } else {
4940 windows.removeAt(i);
4941 }
4942 }
4943}
4944
4945sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4946 for (size_t i = 0; i < windows.size(); i++) {
4947 const TouchedWindow& window = windows.itemAt(i);
4948 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4949 return window.windowHandle;
4950 }
4951 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004952 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953}
4954
4955bool InputDispatcher::TouchState::isSlippery() const {
4956 // Must have exactly one foreground window.
4957 bool haveSlipperyForegroundWindow = false;
4958 for (size_t i = 0; i < windows.size(); i++) {
4959 const TouchedWindow& window = windows.itemAt(i);
4960 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4961 if (haveSlipperyForegroundWindow
4962 || !(window.windowHandle->getInfo()->layoutParamsFlags
4963 & InputWindowInfo::FLAG_SLIPPERY)) {
4964 return false;
4965 }
4966 haveSlipperyForegroundWindow = true;
4967 }
4968 }
4969 return haveSlipperyForegroundWindow;
4970}
4971
4972
4973// --- InputDispatcherThread ---
4974
4975InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4976 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4977}
4978
4979InputDispatcherThread::~InputDispatcherThread() {
4980}
4981
4982bool InputDispatcherThread::threadLoop() {
4983 mDispatcher->dispatchOnce();
4984 return true;
4985}
4986
4987} // namespace android