blob: e0082a5a95905ed913d996d22587895cd80f12cd [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
Yi Kong9b14ac62018-07-17 13:48:38 -0700492 && mInputTargetWaitApplicationHandle != 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
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500 && touchedWindowHandle->inputApplicationHandle
501 != mInputTargetWaitApplicationHandle) {
502 // 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 Carr5c8a0262018-10-03 16:30:44 -0700822 commandEntry->inputChannel = getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 }
824 commandEntry->keyEntry = entry;
825 entry->refCount += 1;
826 return false; // wait for the command to run
827 } else {
828 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
829 }
830 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
831 if (*dropReason == DROP_REASON_NOT_DROPPED) {
832 *dropReason = DROP_REASON_POLICY;
833 }
834 }
835
836 // Clean up if dropping the event.
837 if (*dropReason != DROP_REASON_NOT_DROPPED) {
838 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
839 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
840 return true;
841 }
842
843 // Identify targets.
844 Vector<InputTarget> inputTargets;
845 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
846 entry, inputTargets, nextWakeupTime);
847 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
848 return false;
849 }
850
851 setInjectionResultLocked(entry, injectionResult);
852 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
853 return true;
854 }
855
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800856 // Add monitor channels from event's or focused display.
857 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858
859 // Dispatch the key.
860 dispatchEventLocked(currentTime, entry, inputTargets);
861 return true;
862}
863
864void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
865#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100866 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
867 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800868 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100870 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800872 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873#endif
874}
875
876bool InputDispatcher::dispatchMotionLocked(
877 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
878 // Preprocessing.
879 if (! entry->dispatchInProgress) {
880 entry->dispatchInProgress = true;
881
882 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
883 }
884
885 // Clean up if dropping the event.
886 if (*dropReason != DROP_REASON_NOT_DROPPED) {
887 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
888 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
889 return true;
890 }
891
892 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
893
894 // Identify targets.
895 Vector<InputTarget> inputTargets;
896
897 bool conflictingPointerActions = false;
898 int32_t injectionResult;
899 if (isPointerEvent) {
900 // Pointer event. (eg. touchscreen)
901 injectionResult = findTouchedWindowTargetsLocked(currentTime,
902 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
903 } else {
904 // Non touch event. (eg. trackball)
905 injectionResult = findFocusedWindowTargetsLocked(currentTime,
906 entry, inputTargets, nextWakeupTime);
907 }
908 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
909 return false;
910 }
911
912 setInjectionResultLocked(entry, injectionResult);
913 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100914 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
915 CancelationOptions::Mode mode(isPointerEvent ?
916 CancelationOptions::CANCEL_POINTER_EVENTS :
917 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
918 CancelationOptions options(mode, "input event injection failed");
919 synthesizeCancelationEventsForMonitorsLocked(options);
920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 return true;
922 }
923
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800924 // Add monitor channels from event's or focused display.
925 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926
927 // Dispatch the motion.
928 if (conflictingPointerActions) {
929 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
930 "conflicting pointer actions");
931 synthesizeCancelationEventsForAllConnectionsLocked(options);
932 }
933 dispatchEventLocked(currentTime, entry, inputTargets);
934 return true;
935}
936
937
938void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
939#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800940 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
941 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100942 "action=0x%x, actionButton=0x%x, flags=0x%x, "
943 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800944 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800946 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100947 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948 entry->metaState, entry->buttonState,
949 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800950 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951
952 for (uint32_t i = 0; i < entry->pointerCount; i++) {
953 ALOGD(" Pointer %d: id=%d, toolType=%d, "
954 "x=%f, y=%f, pressure=%f, size=%f, "
955 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800956 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 i, entry->pointerProperties[i].id,
958 entry->pointerProperties[i].toolType,
959 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
960 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
961 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
962 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
963 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
964 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
965 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
966 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800967 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 }
969#endif
970}
971
972void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
973 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
974#if DEBUG_DISPATCH_CYCLE
975 ALOGD("dispatchEventToCurrentInputTargets");
976#endif
977
978 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
979
980 pokeUserActivityLocked(eventEntry);
981
982 for (size_t i = 0; i < inputTargets.size(); i++) {
983 const InputTarget& inputTarget = inputTargets.itemAt(i);
984
985 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
986 if (connectionIndex >= 0) {
987 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
988 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
989 } else {
990#if DEBUG_FOCUS
991 ALOGD("Dropping event delivery to target with channel '%s' because it "
992 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800993 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994#endif
995 }
996 }
997}
998
999int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1000 const EventEntry* entry,
1001 const sp<InputApplicationHandle>& applicationHandle,
1002 const sp<InputWindowHandle>& windowHandle,
1003 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001004 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1006#if DEBUG_FOCUS
1007 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1008#endif
1009 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1010 mInputTargetWaitStartTime = currentTime;
1011 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1012 mInputTargetWaitTimeoutExpired = false;
1013 mInputTargetWaitApplicationHandle.clear();
1014 }
1015 } else {
1016 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1017#if DEBUG_FOCUS
1018 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001019 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 reason);
1021#endif
1022 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001023 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001025 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 timeout = applicationHandle->getDispatchingTimeout(
1027 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1028 } else {
1029 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1030 }
1031
1032 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1033 mInputTargetWaitStartTime = currentTime;
1034 mInputTargetWaitTimeoutTime = currentTime + timeout;
1035 mInputTargetWaitTimeoutExpired = false;
1036 mInputTargetWaitApplicationHandle.clear();
1037
Yi Kong9b14ac62018-07-17 13:48:38 -07001038 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
1040 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001041 if (mInputTargetWaitApplicationHandle == nullptr && applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 mInputTargetWaitApplicationHandle = applicationHandle;
1043 }
1044 }
1045 }
1046
1047 if (mInputTargetWaitTimeoutExpired) {
1048 return INPUT_EVENT_INJECTION_TIMED_OUT;
1049 }
1050
1051 if (currentTime >= mInputTargetWaitTimeoutTime) {
1052 onANRLocked(currentTime, applicationHandle, windowHandle,
1053 entry->eventTime, mInputTargetWaitStartTime, reason);
1054
1055 // Force poll loop to wake up immediately on next iteration once we get the
1056 // ANR response back from the policy.
1057 *nextWakeupTime = LONG_LONG_MIN;
1058 return INPUT_EVENT_INJECTION_PENDING;
1059 } else {
1060 // Force poll loop to wake up when timeout is due.
1061 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1062 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1063 }
1064 return INPUT_EVENT_INJECTION_PENDING;
1065 }
1066}
1067
Robert Carr803535b2018-08-02 16:38:15 -07001068void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1069 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1070 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1071 state.removeWindowByToken(token);
1072 }
1073}
1074
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1076 const sp<InputChannel>& inputChannel) {
1077 if (newTimeout > 0) {
1078 // Extend the timeout.
1079 mInputTargetWaitTimeoutTime = now() + newTimeout;
1080 } else {
1081 // Give up.
1082 mInputTargetWaitTimeoutExpired = true;
1083
1084 // Input state will not be realistic. Mark it out of sync.
1085 if (inputChannel.get()) {
1086 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1087 if (connectionIndex >= 0) {
1088 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001089 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090
Robert Carr803535b2018-08-02 16:38:15 -07001091 if (token != nullptr) {
1092 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093 }
1094
1095 if (connection->status == Connection::STATUS_NORMAL) {
1096 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1097 "application not responding");
1098 synthesizeCancelationEventsForConnectionLocked(connection, options);
1099 }
1100 }
1101 }
1102 }
1103}
1104
1105nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1106 nsecs_t currentTime) {
1107 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1108 return currentTime - mInputTargetWaitStartTime;
1109 }
1110 return 0;
1111}
1112
1113void InputDispatcher::resetANRTimeoutsLocked() {
1114#if DEBUG_FOCUS
1115 ALOGD("Resetting ANR timeouts.");
1116#endif
1117
1118 // Reset input target wait timeout.
1119 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1120 mInputTargetWaitApplicationHandle.clear();
1121}
1122
Tiger Huang721e26f2018-07-24 22:26:19 +08001123/**
1124 * Get the display id that the given event should go to. If this event specifies a valid display id,
1125 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1126 * Focused display is the display that the user most recently interacted with.
1127 */
1128int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1129 int32_t displayId;
1130 switch (entry->type) {
1131 case EventEntry::TYPE_KEY: {
1132 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1133 displayId = typedEntry->displayId;
1134 break;
1135 }
1136 case EventEntry::TYPE_MOTION: {
1137 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1138 displayId = typedEntry->displayId;
1139 break;
1140 }
1141 default: {
1142 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1143 return ADISPLAY_ID_NONE;
1144 }
1145 }
1146 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1147}
1148
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1150 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1151 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001152 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153
Tiger Huang721e26f2018-07-24 22:26:19 +08001154 int32_t displayId = getTargetDisplayId(entry);
1155 sp<InputWindowHandle> focusedWindowHandle =
1156 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1157 sp<InputApplicationHandle> focusedApplicationHandle =
1158 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1159
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 // If there is no currently focused window and no focused application
1161 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001162 if (focusedWindowHandle == nullptr) {
1163 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001165 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 "Waiting because no window has focus but there is a "
1167 "focused application that may eventually add a window "
1168 "when it finishes starting up.");
1169 goto Unresponsive;
1170 }
1171
Arthur Hung3b413f22018-10-26 18:05:34 +08001172 ALOGI("Dropping event because there is no focused window or focused application in display "
1173 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1175 goto Failed;
1176 }
1177
1178 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001179 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1181 goto Failed;
1182 }
1183
Jeff Brownffb49772014-10-10 19:01:34 -07001184 // Check whether the window is ready for more input.
1185 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001186 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001187 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001189 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 goto Unresponsive;
1191 }
1192
1193 // Success! Output targets.
1194 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001195 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1197 inputTargets);
1198
1199 // Done.
1200Failed:
1201Unresponsive:
1202 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1203 updateDispatchStatisticsLocked(currentTime, entry,
1204 injectionResult, timeSpentWaitingForApplication);
1205#if DEBUG_FOCUS
1206 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1207 "timeSpentWaitingForApplication=%0.1fms",
1208 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1209#endif
1210 return injectionResult;
1211}
1212
1213int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1214 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1215 bool* outConflictingPointerActions) {
1216 enum InjectionPermission {
1217 INJECTION_PERMISSION_UNKNOWN,
1218 INJECTION_PERMISSION_GRANTED,
1219 INJECTION_PERMISSION_DENIED
1220 };
1221
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 // For security reasons, we defer updating the touch state until we are sure that
1223 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 int32_t displayId = entry->displayId;
1225 int32_t action = entry->action;
1226 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1227
1228 // Update the touch state as needed based on the properties of the touch event.
1229 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1230 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1231 sp<InputWindowHandle> newHoverWindowHandle;
1232
Jeff Brownf086ddb2014-02-11 14:28:48 -08001233 // Copy current touch state into mTempTouchState.
1234 // This state is always reset at the end of this function, so if we don't find state
1235 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001236 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001237 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1238 if (oldStateIndex >= 0) {
1239 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1240 mTempTouchState.copyFrom(*oldState);
1241 }
1242
1243 bool isSplit = mTempTouchState.split;
1244 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1245 && (mTempTouchState.deviceId != entry->deviceId
1246 || mTempTouchState.source != entry->source
1247 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1249 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1250 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1251 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1252 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1253 || isHoverAction);
1254 bool wrongDevice = false;
1255 if (newGesture) {
1256 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001257 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001259 ALOGD("Dropping event because a pointer for a different device is already down "
1260 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001262 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1264 switchedDevice = false;
1265 wrongDevice = true;
1266 goto Failed;
1267 }
1268 mTempTouchState.reset();
1269 mTempTouchState.down = down;
1270 mTempTouchState.deviceId = entry->deviceId;
1271 mTempTouchState.source = entry->source;
1272 mTempTouchState.displayId = displayId;
1273 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001274 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1275#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001276 ALOGI("Dropping move event because a pointer for a different device is already active "
1277 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001278#endif
1279 // TODO: test multiple simultaneous input streams.
1280 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1281 switchedDevice = false;
1282 wrongDevice = true;
1283 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 }
1285
1286 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1287 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1288
1289 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1290 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1291 getAxisValue(AMOTION_EVENT_AXIS_X));
1292 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1293 getAxisValue(AMOTION_EVENT_AXIS_Y));
1294 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 bool isTouchModal = false;
1296
1297 // Traverse windows from front to back to find touched window and outside targets.
Arthur Hungb92218b2018-08-14 12:00:21 +08001298 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1299 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001301 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1303 if (windowInfo->displayId != displayId) {
1304 continue; // wrong display
1305 }
1306
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 int32_t flags = windowInfo->layoutParamsFlags;
1308 if (windowInfo->visible) {
1309 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1310 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1311 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1312 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001313 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 break; // found touched window, exit window loop
1315 }
1316 }
1317
1318 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1319 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001321 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 }
1323 }
1324 }
1325
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001327 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1329 // New window supports splitting.
1330 isSplit = true;
1331 } else if (isSplit) {
1332 // New window does not support splitting but we have already split events.
1333 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001334 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 }
1336
1337 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001338 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 // Try to assign the pointer to the first foreground window we find, if there is one.
1340 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001341 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001342 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1343 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1345 goto Failed;
1346 }
1347 }
1348
1349 // Set target flags.
1350 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1351 if (isSplit) {
1352 targetFlags |= InputTarget::FLAG_SPLIT;
1353 }
1354 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1355 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001356 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1357 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 }
1359
1360 // Update hover state.
1361 if (isHoverAction) {
1362 newHoverWindowHandle = newTouchedWindowHandle;
1363 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1364 newHoverWindowHandle = mLastHoverWindowHandle;
1365 }
1366
1367 // Update the temporary touch state.
1368 BitSet32 pointerIds;
1369 if (isSplit) {
1370 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1371 pointerIds.markBit(pointerId);
1372 }
1373 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1374 } else {
1375 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1376
1377 // If the pointer is not currently down, then ignore the event.
1378 if (! mTempTouchState.down) {
1379#if DEBUG_FOCUS
1380 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001381 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382#endif
1383 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1384 goto Failed;
1385 }
1386
1387 // Check whether touches should slip outside of the current foreground window.
1388 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1389 && entry->pointerCount == 1
1390 && mTempTouchState.isSlippery()) {
1391 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1392 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1393
1394 sp<InputWindowHandle> oldTouchedWindowHandle =
1395 mTempTouchState.getFirstForegroundWindowHandle();
1396 sp<InputWindowHandle> newTouchedWindowHandle =
1397 findTouchedWindowAtLocked(displayId, x, y);
1398 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001399 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001401 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001402 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001403 newTouchedWindowHandle->getName().c_str(),
1404 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405#endif
1406 // Make a slippery exit from the old window.
1407 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1408 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1409
1410 // Make a slippery entrance into the new window.
1411 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1412 isSplit = true;
1413 }
1414
1415 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1416 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1417 if (isSplit) {
1418 targetFlags |= InputTarget::FLAG_SPLIT;
1419 }
1420 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1421 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1422 }
1423
1424 BitSet32 pointerIds;
1425 if (isSplit) {
1426 pointerIds.markBit(entry->pointerProperties[0].id);
1427 }
1428 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1429 }
1430 }
1431 }
1432
1433 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1434 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001435 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436#if DEBUG_HOVER
1437 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001438 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439#endif
1440 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1441 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1442 }
1443
1444 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001445 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446#if DEBUG_HOVER
1447 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001448 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449#endif
1450 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1451 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1452 }
1453 }
1454
1455 // Check permission to inject into all touched foreground windows and ensure there
1456 // is at least one touched foreground window.
1457 {
1458 bool haveForegroundWindow = false;
1459 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1460 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1461 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1462 haveForegroundWindow = true;
1463 if (! checkInjectionPermission(touchedWindow.windowHandle,
1464 entry->injectionState)) {
1465 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1466 injectionPermission = INJECTION_PERMISSION_DENIED;
1467 goto Failed;
1468 }
1469 }
1470 }
1471 if (! haveForegroundWindow) {
1472#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001473 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1474 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475#endif
1476 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1477 goto Failed;
1478 }
1479
1480 // Permission granted to injection into all touched foreground windows.
1481 injectionPermission = INJECTION_PERMISSION_GRANTED;
1482 }
1483
1484 // Check whether windows listening for outside touches are owned by the same UID. If it is
1485 // set the policy flag that we will not reveal coordinate information to this window.
1486 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1487 sp<InputWindowHandle> foregroundWindowHandle =
1488 mTempTouchState.getFirstForegroundWindowHandle();
1489 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1490 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1491 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1492 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1493 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1494 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1495 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1496 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1497 }
1498 }
1499 }
1500 }
1501
1502 // Ensure all touched foreground windows are ready for new input.
1503 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1504 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1505 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001506 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001507 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001508 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001509 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001511 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 goto Unresponsive;
1513 }
1514 }
1515 }
1516
1517 // If this is the first pointer going down and the touched window has a wallpaper
1518 // then also add the touched wallpaper windows so they are locked in for the duration
1519 // of the touch gesture.
1520 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1521 // engine only supports touch events. We would need to add a mechanism similar
1522 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1523 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1524 sp<InputWindowHandle> foregroundWindowHandle =
1525 mTempTouchState.getFirstForegroundWindowHandle();
1526 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001527 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1528 size_t numWindows = windowHandles.size();
1529 for (size_t i = 0; i < numWindows; i++) {
1530 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 const InputWindowInfo* info = windowHandle->getInfo();
1532 if (info->displayId == displayId
1533 && windowHandle->getInfo()->layoutParamsType
1534 == InputWindowInfo::TYPE_WALLPAPER) {
1535 mTempTouchState.addOrUpdateWindow(windowHandle,
1536 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001537 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 | InputTarget::FLAG_DISPATCH_AS_IS,
1539 BitSet32(0));
1540 }
1541 }
1542 }
1543 }
1544
1545 // Success! Output targets.
1546 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1547
1548 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1549 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1550 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1551 touchedWindow.pointerIds, inputTargets);
1552 }
1553
1554 // Drop the outside or hover touch windows since we will not care about them
1555 // in the next iteration.
1556 mTempTouchState.filterNonAsIsTouchWindows();
1557
1558Failed:
1559 // Check injection permission once and for all.
1560 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001561 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 injectionPermission = INJECTION_PERMISSION_GRANTED;
1563 } else {
1564 injectionPermission = INJECTION_PERMISSION_DENIED;
1565 }
1566 }
1567
1568 // Update final pieces of touch state if the injector had permission.
1569 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1570 if (!wrongDevice) {
1571 if (switchedDevice) {
1572#if DEBUG_FOCUS
1573 ALOGD("Conflicting pointer actions: Switched to a different device.");
1574#endif
1575 *outConflictingPointerActions = true;
1576 }
1577
1578 if (isHoverAction) {
1579 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001580 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581#if DEBUG_FOCUS
1582 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1583#endif
1584 *outConflictingPointerActions = true;
1585 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001586 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1588 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001589 mTempTouchState.deviceId = entry->deviceId;
1590 mTempTouchState.source = entry->source;
1591 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 }
1593 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1594 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1595 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001596 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1598 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001599 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600#if DEBUG_FOCUS
1601 ALOGD("Conflicting pointer actions: Down received while already down.");
1602#endif
1603 *outConflictingPointerActions = true;
1604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1606 // One pointer went up.
1607 if (isSplit) {
1608 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1609 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1610
1611 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1612 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1613 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1614 touchedWindow.pointerIds.clearBit(pointerId);
1615 if (touchedWindow.pointerIds.isEmpty()) {
1616 mTempTouchState.windows.removeAt(i);
1617 continue;
1618 }
1619 }
1620 i += 1;
1621 }
1622 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001623 }
1624
1625 // Save changes unless the action was scroll in which case the temporary touch
1626 // state was only valid for this one action.
1627 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1628 if (mTempTouchState.displayId >= 0) {
1629 if (oldStateIndex >= 0) {
1630 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1631 } else {
1632 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1633 }
1634 } else if (oldStateIndex >= 0) {
1635 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1636 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 }
1638
1639 // Update hover state.
1640 mLastHoverWindowHandle = newHoverWindowHandle;
1641 }
1642 } else {
1643#if DEBUG_FOCUS
1644 ALOGD("Not updating touch focus because injection was denied.");
1645#endif
1646 }
1647
1648Unresponsive:
1649 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1650 mTempTouchState.reset();
1651
1652 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1653 updateDispatchStatisticsLocked(currentTime, entry,
1654 injectionResult, timeSpentWaitingForApplication);
1655#if DEBUG_FOCUS
1656 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1657 "timeSpentWaitingForApplication=%0.1fms",
1658 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1659#endif
1660 return injectionResult;
1661}
1662
1663void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1664 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1665 inputTargets.push();
1666
1667 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1668 InputTarget& target = inputTargets.editTop();
Robert Carr5c8a0262018-10-03 16:30:44 -07001669 target.inputChannel = getInputChannelLocked(windowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 target.flags = targetFlags;
1671 target.xOffset = - windowInfo->frameLeft;
1672 target.yOffset = - windowInfo->frameTop;
1673 target.scaleFactor = windowInfo->scaleFactor;
1674 target.pointerIds = pointerIds;
1675}
1676
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001677void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets,
1678 int32_t displayId) {
1679 std::unordered_map<int32_t, Vector<sp<InputChannel>>>::const_iterator it =
1680 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001682 if (it != mMonitoringChannelsByDisplay.end()) {
1683 const Vector<sp<InputChannel>>& monitoringChannels = it->second;
1684 const size_t numChannels = monitoringChannels.size();
1685 for (size_t i = 0; i < numChannels; i++) {
1686 inputTargets.push();
1687
1688 InputTarget& target = inputTargets.editTop();
1689 target.inputChannel = monitoringChannels[i];
1690 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1691 target.xOffset = 0;
1692 target.yOffset = 0;
1693 target.pointerIds.clear();
1694 target.scaleFactor = 1.0f;
1695 }
1696 } else {
1697 // If there is no monitor channel registered or all monitor channel unregistered,
1698 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001699 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 }
1701}
1702
1703bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1704 const InjectionState* injectionState) {
1705 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001706 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1708 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001709 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1711 "owned by uid %d",
1712 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001713 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 windowHandle->getInfo()->ownerUid);
1715 } else {
1716 ALOGW("Permission denied: injecting event from pid %d uid %d",
1717 injectionState->injectorPid, injectionState->injectorUid);
1718 }
1719 return false;
1720 }
1721 return true;
1722}
1723
1724bool InputDispatcher::isWindowObscuredAtPointLocked(
1725 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1726 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001727 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1728 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001730 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 if (otherHandle == windowHandle) {
1732 break;
1733 }
1734
1735 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1736 if (otherInfo->displayId == displayId
1737 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1738 && otherInfo->frameContainsPoint(x, y)) {
1739 return true;
1740 }
1741 }
1742 return false;
1743}
1744
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001745
1746bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1747 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001748 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001749 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hungb92218b2018-08-14 12:00:21 +08001750 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001751 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001752 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001753 if (otherHandle == windowHandle) {
1754 break;
1755 }
1756
1757 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1758 if (otherInfo->displayId == displayId
1759 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1760 && otherInfo->overlaps(windowInfo)) {
1761 return true;
1762 }
1763 }
1764 return false;
1765}
1766
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001767std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001768 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1769 const char* targetType) {
1770 // If the window is paused then keep waiting.
1771 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001772 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001773 }
1774
1775 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001776 ssize_t connectionIndex = getConnectionIndexLocked(
1777 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001778 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001779 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001780 "registered with the input dispatcher. The window may be in the process "
1781 "of being removed.", targetType);
1782 }
1783
1784 // If the connection is dead then keep waiting.
1785 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1786 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001787 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001788 "The window may be in the process of being removed.", targetType,
1789 connection->getStatusLabel());
1790 }
1791
1792 // If the connection is backed up then keep waiting.
1793 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001794 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001795 "Outbound queue length: %d. Wait queue length: %d.",
1796 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1797 }
1798
1799 // Ensure that the dispatch queues aren't too far backed up for this event.
1800 if (eventEntry->type == EventEntry::TYPE_KEY) {
1801 // If the event is a key event, then we must wait for all previous events to
1802 // complete before delivering it because previous events may have the
1803 // side-effect of transferring focus to a different window and we want to
1804 // ensure that the following keys are sent to the new window.
1805 //
1806 // Suppose the user touches a button in a window then immediately presses "A".
1807 // If the button causes a pop-up window to appear then we want to ensure that
1808 // the "A" key is delivered to the new pop-up window. This is because users
1809 // often anticipate pending UI changes when typing on a keyboard.
1810 // To obtain this behavior, we must serialize key events with respect to all
1811 // prior input events.
1812 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001813 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001814 "finished processing all of the input events that were previously "
1815 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1816 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 }
Jeff Brownffb49772014-10-10 19:01:34 -07001818 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 // Touch events can always be sent to a window immediately because the user intended
1820 // to touch whatever was visible at the time. Even if focus changes or a new
1821 // window appears moments later, the touch event was meant to be delivered to
1822 // whatever window happened to be on screen at the time.
1823 //
1824 // Generic motion events, such as trackball or joystick events are a little trickier.
1825 // Like key events, generic motion events are delivered to the focused window.
1826 // Unlike key events, generic motion events don't tend to transfer focus to other
1827 // windows and it is not important for them to be serialized. So we prefer to deliver
1828 // generic motion events as soon as possible to improve efficiency and reduce lag
1829 // through batching.
1830 //
1831 // The one case where we pause input event delivery is when the wait queue is piling
1832 // up with lots of events because the application is not responding.
1833 // This condition ensures that ANRs are detected reliably.
1834 if (!connection->waitQueue.isEmpty()
1835 && currentTime >= connection->waitQueue.head->deliveryTime
1836 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001837 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001838 "finished processing certain input events that were delivered to it over "
1839 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1840 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1841 connection->waitQueue.count(),
1842 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 }
1844 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001845 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001846}
1847
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001848std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 const sp<InputApplicationHandle>& applicationHandle,
1850 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001851 if (applicationHandle != nullptr) {
1852 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001853 std::string label(applicationHandle->getName());
1854 label += " - ";
1855 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856 return label;
1857 } else {
1858 return applicationHandle->getName();
1859 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001860 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 return windowHandle->getName();
1862 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001863 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 }
1865}
1866
1867void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001868 int32_t displayId = getTargetDisplayId(eventEntry);
1869 sp<InputWindowHandle> focusedWindowHandle =
1870 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1871 if (focusedWindowHandle != nullptr) {
1872 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1874#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001875 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876#endif
1877 return;
1878 }
1879 }
1880
1881 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1882 switch (eventEntry->type) {
1883 case EventEntry::TYPE_MOTION: {
1884 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1885 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1886 return;
1887 }
1888
1889 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1890 eventType = USER_ACTIVITY_EVENT_TOUCH;
1891 }
1892 break;
1893 }
1894 case EventEntry::TYPE_KEY: {
1895 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1896 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1897 return;
1898 }
1899 eventType = USER_ACTIVITY_EVENT_BUTTON;
1900 break;
1901 }
1902 }
1903
1904 CommandEntry* commandEntry = postCommandLocked(
1905 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1906 commandEntry->eventTime = eventEntry->eventTime;
1907 commandEntry->userActivityEventType = eventType;
1908}
1909
1910void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1911 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1912#if DEBUG_DISPATCH_CYCLE
1913 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1914 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1915 "pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001916 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 inputTarget->xOffset, inputTarget->yOffset,
1918 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1919#endif
1920
1921 // Skip this event if the connection status is not normal.
1922 // We don't want to enqueue additional outbound events if the connection is broken.
1923 if (connection->status != Connection::STATUS_NORMAL) {
1924#if DEBUG_DISPATCH_CYCLE
1925 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001926 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927#endif
1928 return;
1929 }
1930
1931 // Split a motion event if needed.
1932 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1933 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1934
1935 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1936 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1937 MotionEntry* splitMotionEntry = splitMotionEvent(
1938 originalMotionEntry, inputTarget->pointerIds);
1939 if (!splitMotionEntry) {
1940 return; // split event was dropped
1941 }
1942#if DEBUG_FOCUS
1943 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001944 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001945 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1946#endif
1947 enqueueDispatchEntriesLocked(currentTime, connection,
1948 splitMotionEntry, inputTarget);
1949 splitMotionEntry->release();
1950 return;
1951 }
1952 }
1953
1954 // Not splitting. Enqueue dispatch entries for the event as is.
1955 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1956}
1957
1958void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1959 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1960 bool wasEmpty = connection->outboundQueue.isEmpty();
1961
1962 // Enqueue dispatch entries for the requested modes.
1963 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1964 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1965 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1966 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1967 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1968 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1969 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1970 InputTarget::FLAG_DISPATCH_AS_IS);
1971 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1972 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1973 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1974 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1975
1976 // If the outbound queue was previously empty, start the dispatch cycle going.
1977 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1978 startDispatchCycleLocked(currentTime, connection);
1979 }
1980}
1981
1982void InputDispatcher::enqueueDispatchEntryLocked(
1983 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1984 int32_t dispatchMode) {
1985 int32_t inputTargetFlags = inputTarget->flags;
1986 if (!(inputTargetFlags & dispatchMode)) {
1987 return;
1988 }
1989 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1990
1991 // This is a new event.
1992 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1993 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1994 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1995 inputTarget->scaleFactor);
1996
1997 // Apply target flags and update the connection's input state.
1998 switch (eventEntry->type) {
1999 case EventEntry::TYPE_KEY: {
2000 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2001 dispatchEntry->resolvedAction = keyEntry->action;
2002 dispatchEntry->resolvedFlags = keyEntry->flags;
2003
2004 if (!connection->inputState.trackKey(keyEntry,
2005 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2006#if DEBUG_DISPATCH_CYCLE
2007 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002008 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002009#endif
2010 delete dispatchEntry;
2011 return; // skip the inconsistent event
2012 }
2013 break;
2014 }
2015
2016 case EventEntry::TYPE_MOTION: {
2017 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2018 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2019 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2020 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2021 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2022 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2023 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2024 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2025 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2026 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2027 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2028 } else {
2029 dispatchEntry->resolvedAction = motionEntry->action;
2030 }
2031 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2032 && !connection->inputState.isHovering(
2033 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2034#if DEBUG_DISPATCH_CYCLE
2035 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002036 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037#endif
2038 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2039 }
2040
2041 dispatchEntry->resolvedFlags = motionEntry->flags;
2042 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2043 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2044 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002045 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2046 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048
2049 if (!connection->inputState.trackMotion(motionEntry,
2050 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2051#if DEBUG_DISPATCH_CYCLE
2052 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002053 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054#endif
2055 delete dispatchEntry;
2056 return; // skip the inconsistent event
2057 }
2058 break;
2059 }
2060 }
2061
2062 // Remember that we are waiting for this dispatch to complete.
2063 if (dispatchEntry->hasForegroundTarget()) {
2064 incrementPendingForegroundDispatchesLocked(eventEntry);
2065 }
2066
2067 // Enqueue the dispatch entry.
2068 connection->outboundQueue.enqueueAtTail(dispatchEntry);
2069 traceOutboundQueueLengthLocked(connection);
2070}
2071
2072void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2073 const sp<Connection>& connection) {
2074#if DEBUG_DISPATCH_CYCLE
2075 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002076 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077#endif
2078
2079 while (connection->status == Connection::STATUS_NORMAL
2080 && !connection->outboundQueue.isEmpty()) {
2081 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2082 dispatchEntry->deliveryTime = currentTime;
2083
2084 // Publish the event.
2085 status_t status;
2086 EventEntry* eventEntry = dispatchEntry->eventEntry;
2087 switch (eventEntry->type) {
2088 case EventEntry::TYPE_KEY: {
2089 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2090
2091 // Publish the key event.
2092 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002093 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2095 keyEntry->keyCode, keyEntry->scanCode,
2096 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2097 keyEntry->eventTime);
2098 break;
2099 }
2100
2101 case EventEntry::TYPE_MOTION: {
2102 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2103
2104 PointerCoords scaledCoords[MAX_POINTERS];
2105 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2106
2107 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002108 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2110 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002111 float scaleFactor = dispatchEntry->scaleFactor;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112 xOffset = dispatchEntry->xOffset * scaleFactor;
2113 yOffset = dispatchEntry->yOffset * scaleFactor;
2114 if (scaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002115 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 scaledCoords[i] = motionEntry->pointerCoords[i];
2117 scaledCoords[i].scale(scaleFactor);
2118 }
2119 usingCoords = scaledCoords;
2120 }
2121 } else {
2122 xOffset = 0.0f;
2123 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124
2125 // We don't want the dispatch target to know.
2126 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002127 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002128 scaledCoords[i].clear();
2129 }
2130 usingCoords = scaledCoords;
2131 }
2132 }
2133
2134 // Publish the motion event.
2135 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002136 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002137 dispatchEntry->resolvedAction, motionEntry->actionButton,
2138 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2139 motionEntry->metaState, motionEntry->buttonState,
2140 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141 motionEntry->downTime, motionEntry->eventTime,
2142 motionEntry->pointerCount, motionEntry->pointerProperties,
2143 usingCoords);
2144 break;
2145 }
2146
2147 default:
2148 ALOG_ASSERT(false);
2149 return;
2150 }
2151
2152 // Check the result.
2153 if (status) {
2154 if (status == WOULD_BLOCK) {
2155 if (connection->waitQueue.isEmpty()) {
2156 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2157 "This is unexpected because the wait queue is empty, so the pipe "
2158 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002159 "event to it, status=%d", connection->getInputChannelName().c_str(),
2160 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2162 } else {
2163 // Pipe is full and we are waiting for the app to finish process some events
2164 // before sending more events to it.
2165#if DEBUG_DISPATCH_CYCLE
2166 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2167 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002168 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169#endif
2170 connection->inputPublisherBlocked = true;
2171 }
2172 } else {
2173 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002174 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2176 }
2177 return;
2178 }
2179
2180 // Re-enqueue the event on the wait queue.
2181 connection->outboundQueue.dequeue(dispatchEntry);
2182 traceOutboundQueueLengthLocked(connection);
2183 connection->waitQueue.enqueueAtTail(dispatchEntry);
2184 traceWaitQueueLengthLocked(connection);
2185 }
2186}
2187
2188void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2189 const sp<Connection>& connection, uint32_t seq, bool handled) {
2190#if DEBUG_DISPATCH_CYCLE
2191 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002192 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193#endif
2194
2195 connection->inputPublisherBlocked = false;
2196
2197 if (connection->status == Connection::STATUS_BROKEN
2198 || connection->status == Connection::STATUS_ZOMBIE) {
2199 return;
2200 }
2201
2202 // Notify other system components and prepare to start the next dispatch cycle.
2203 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2204}
2205
2206void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2207 const sp<Connection>& connection, bool notify) {
2208#if DEBUG_DISPATCH_CYCLE
2209 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002210 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211#endif
2212
2213 // Clear the dispatch queues.
2214 drainDispatchQueueLocked(&connection->outboundQueue);
2215 traceOutboundQueueLengthLocked(connection);
2216 drainDispatchQueueLocked(&connection->waitQueue);
2217 traceWaitQueueLengthLocked(connection);
2218
2219 // The connection appears to be unrecoverably broken.
2220 // Ignore already broken or zombie connections.
2221 if (connection->status == Connection::STATUS_NORMAL) {
2222 connection->status = Connection::STATUS_BROKEN;
2223
2224 if (notify) {
2225 // Notify other system components.
2226 onDispatchCycleBrokenLocked(currentTime, connection);
2227 }
2228 }
2229}
2230
2231void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2232 while (!queue->isEmpty()) {
2233 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2234 releaseDispatchEntryLocked(dispatchEntry);
2235 }
2236}
2237
2238void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2239 if (dispatchEntry->hasForegroundTarget()) {
2240 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2241 }
2242 delete dispatchEntry;
2243}
2244
2245int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2246 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2247
2248 { // acquire lock
2249 AutoMutex _l(d->mLock);
2250
2251 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2252 if (connectionIndex < 0) {
2253 ALOGE("Received spurious receive callback for unknown input channel. "
2254 "fd=%d, events=0x%x", fd, events);
2255 return 0; // remove the callback
2256 }
2257
2258 bool notify;
2259 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2260 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2261 if (!(events & ALOOPER_EVENT_INPUT)) {
2262 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002263 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 return 1;
2265 }
2266
2267 nsecs_t currentTime = now();
2268 bool gotOne = false;
2269 status_t status;
2270 for (;;) {
2271 uint32_t seq;
2272 bool handled;
2273 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2274 if (status) {
2275 break;
2276 }
2277 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2278 gotOne = true;
2279 }
2280 if (gotOne) {
2281 d->runCommandsLockedInterruptible();
2282 if (status == WOULD_BLOCK) {
2283 return 1;
2284 }
2285 }
2286
2287 notify = status != DEAD_OBJECT || !connection->monitor;
2288 if (notify) {
2289 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002290 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 }
2292 } else {
2293 // Monitor channels are never explicitly unregistered.
2294 // We do it automatically when the remote endpoint is closed so don't warn
2295 // about them.
2296 notify = !connection->monitor;
2297 if (notify) {
2298 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002299 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002300 }
2301 }
2302
2303 // Unregister the channel.
2304 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2305 return 0; // remove the callback
2306 } // release lock
2307}
2308
2309void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2310 const CancelationOptions& options) {
2311 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2312 synthesizeCancelationEventsForConnectionLocked(
2313 mConnectionsByFd.valueAt(i), options);
2314 }
2315}
2316
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002317void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2318 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002319 for (auto& it : mMonitoringChannelsByDisplay) {
2320 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
2321 const size_t numChannels = monitoringChannels.size();
2322 for (size_t i = 0; i < numChannels; i++) {
2323 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2324 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002325 }
2326}
2327
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2329 const sp<InputChannel>& channel, const CancelationOptions& options) {
2330 ssize_t index = getConnectionIndexLocked(channel);
2331 if (index >= 0) {
2332 synthesizeCancelationEventsForConnectionLocked(
2333 mConnectionsByFd.valueAt(index), options);
2334 }
2335}
2336
2337void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2338 const sp<Connection>& connection, const CancelationOptions& options) {
2339 if (connection->status == Connection::STATUS_BROKEN) {
2340 return;
2341 }
2342
2343 nsecs_t currentTime = now();
2344
2345 Vector<EventEntry*> cancelationEvents;
2346 connection->inputState.synthesizeCancelationEvents(currentTime,
2347 cancelationEvents, options);
2348
2349 if (!cancelationEvents.isEmpty()) {
2350#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002351 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002353 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 options.reason, options.mode);
2355#endif
2356 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2357 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2358 switch (cancelationEventEntry->type) {
2359 case EventEntry::TYPE_KEY:
2360 logOutboundKeyDetailsLocked("cancel - ",
2361 static_cast<KeyEntry*>(cancelationEventEntry));
2362 break;
2363 case EventEntry::TYPE_MOTION:
2364 logOutboundMotionDetailsLocked("cancel - ",
2365 static_cast<MotionEntry*>(cancelationEventEntry));
2366 break;
2367 }
2368
2369 InputTarget target;
2370 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07002371 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2373 target.xOffset = -windowInfo->frameLeft;
2374 target.yOffset = -windowInfo->frameTop;
2375 target.scaleFactor = windowInfo->scaleFactor;
2376 } else {
2377 target.xOffset = 0;
2378 target.yOffset = 0;
2379 target.scaleFactor = 1.0f;
2380 }
2381 target.inputChannel = connection->inputChannel;
2382 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2383
2384 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2385 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2386
2387 cancelationEventEntry->release();
2388 }
2389
2390 startDispatchCycleLocked(currentTime, connection);
2391 }
2392}
2393
2394InputDispatcher::MotionEntry*
2395InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2396 ALOG_ASSERT(pointerIds.value != 0);
2397
2398 uint32_t splitPointerIndexMap[MAX_POINTERS];
2399 PointerProperties splitPointerProperties[MAX_POINTERS];
2400 PointerCoords splitPointerCoords[MAX_POINTERS];
2401
2402 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2403 uint32_t splitPointerCount = 0;
2404
2405 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2406 originalPointerIndex++) {
2407 const PointerProperties& pointerProperties =
2408 originalMotionEntry->pointerProperties[originalPointerIndex];
2409 uint32_t pointerId = uint32_t(pointerProperties.id);
2410 if (pointerIds.hasBit(pointerId)) {
2411 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2412 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2413 splitPointerCoords[splitPointerCount].copyFrom(
2414 originalMotionEntry->pointerCoords[originalPointerIndex]);
2415 splitPointerCount += 1;
2416 }
2417 }
2418
2419 if (splitPointerCount != pointerIds.count()) {
2420 // This is bad. We are missing some of the pointers that we expected to deliver.
2421 // Most likely this indicates that we received an ACTION_MOVE events that has
2422 // different pointer ids than we expected based on the previous ACTION_DOWN
2423 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2424 // in this way.
2425 ALOGW("Dropping split motion event because the pointer count is %d but "
2426 "we expected there to be %d pointers. This probably means we received "
2427 "a broken sequence of pointer ids from the input device.",
2428 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002429 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 }
2431
2432 int32_t action = originalMotionEntry->action;
2433 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2434 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2435 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2436 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2437 const PointerProperties& pointerProperties =
2438 originalMotionEntry->pointerProperties[originalPointerIndex];
2439 uint32_t pointerId = uint32_t(pointerProperties.id);
2440 if (pointerIds.hasBit(pointerId)) {
2441 if (pointerIds.count() == 1) {
2442 // The first/last pointer went down/up.
2443 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2444 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2445 } else {
2446 // A secondary pointer went down/up.
2447 uint32_t splitPointerIndex = 0;
2448 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2449 splitPointerIndex += 1;
2450 }
2451 action = maskedAction | (splitPointerIndex
2452 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2453 }
2454 } else {
2455 // An unrelated pointer changed.
2456 action = AMOTION_EVENT_ACTION_MOVE;
2457 }
2458 }
2459
2460 MotionEntry* splitMotionEntry = new MotionEntry(
2461 originalMotionEntry->eventTime,
2462 originalMotionEntry->deviceId,
2463 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002464 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 originalMotionEntry->policyFlags,
2466 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002467 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002468 originalMotionEntry->flags,
2469 originalMotionEntry->metaState,
2470 originalMotionEntry->buttonState,
2471 originalMotionEntry->edgeFlags,
2472 originalMotionEntry->xPrecision,
2473 originalMotionEntry->yPrecision,
2474 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002475 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476
2477 if (originalMotionEntry->injectionState) {
2478 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2479 splitMotionEntry->injectionState->refCount += 1;
2480 }
2481
2482 return splitMotionEntry;
2483}
2484
2485void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2486#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002487 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488#endif
2489
2490 bool needWake;
2491 { // acquire lock
2492 AutoMutex _l(mLock);
2493
2494 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2495 needWake = enqueueInboundEventLocked(newEntry);
2496 } // release lock
2497
2498 if (needWake) {
2499 mLooper->wake();
2500 }
2501}
2502
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002503/**
2504 * If one of the meta shortcuts is detected, process them here:
2505 * Meta + Backspace -> generate BACK
2506 * Meta + Enter -> generate HOME
2507 * This will potentially overwrite keyCode and metaState.
2508 */
2509void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2510 int32_t& keyCode, int32_t& metaState) {
2511 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2512 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2513 if (keyCode == AKEYCODE_DEL) {
2514 newKeyCode = AKEYCODE_BACK;
2515 } else if (keyCode == AKEYCODE_ENTER) {
2516 newKeyCode = AKEYCODE_HOME;
2517 }
2518 if (newKeyCode != AKEYCODE_UNKNOWN) {
2519 AutoMutex _l(mLock);
2520 struct KeyReplacement replacement = {keyCode, deviceId};
2521 mReplacedKeys.add(replacement, newKeyCode);
2522 keyCode = newKeyCode;
2523 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2524 }
2525 } else if (action == AKEY_EVENT_ACTION_UP) {
2526 // In order to maintain a consistent stream of up and down events, check to see if the key
2527 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2528 // even if the modifier was released between the down and the up events.
2529 AutoMutex _l(mLock);
2530 struct KeyReplacement replacement = {keyCode, deviceId};
2531 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2532 if (index >= 0) {
2533 keyCode = mReplacedKeys.valueAt(index);
2534 mReplacedKeys.removeItemsAt(index);
2535 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2536 }
2537 }
2538}
2539
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2541#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002542 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002543 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002544 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002545 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002547 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548#endif
2549 if (!validateKeyEvent(args->action)) {
2550 return;
2551 }
2552
2553 uint32_t policyFlags = args->policyFlags;
2554 int32_t flags = args->flags;
2555 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002556 // InputDispatcher tracks and generates key repeats on behalf of
2557 // whatever notifies it, so repeatCount should always be set to 0
2558 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2560 policyFlags |= POLICY_FLAG_VIRTUAL;
2561 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 if (policyFlags & POLICY_FLAG_FUNCTION) {
2564 metaState |= AMETA_FUNCTION_ON;
2565 }
2566
2567 policyFlags |= POLICY_FLAG_TRUSTED;
2568
Michael Wright78f24442014-08-06 15:55:28 -07002569 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002570 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002571
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002573 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002574 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575 args->downTime, args->eventTime);
2576
Michael Wright2b3c3302018-03-02 17:19:13 +00002577 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002579 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2580 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2581 std::to_string(t.duration().count()).c_str());
2582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 bool needWake;
2585 { // acquire lock
2586 mLock.lock();
2587
2588 if (shouldSendKeyToInputFilterLocked(args)) {
2589 mLock.unlock();
2590
2591 policyFlags |= POLICY_FLAG_FILTERED;
2592 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2593 return; // event was consumed by the filter
2594 }
2595
2596 mLock.lock();
2597 }
2598
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 KeyEntry* newEntry = new KeyEntry(args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002600 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002601 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 metaState, repeatCount, args->downTime);
2603
2604 needWake = enqueueInboundEventLocked(newEntry);
2605 mLock.unlock();
2606 } // release lock
2607
2608 if (needWake) {
2609 mLooper->wake();
2610 }
2611}
2612
2613bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2614 return mInputFilterEnabled;
2615}
2616
2617void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2618#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002619 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2620 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002621 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002622 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2623 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002624 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002625 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626 for (uint32_t i = 0; i < args->pointerCount; i++) {
2627 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2628 "x=%f, y=%f, pressure=%f, size=%f, "
2629 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2630 "orientation=%f",
2631 i, args->pointerProperties[i].id,
2632 args->pointerProperties[i].toolType,
2633 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2634 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2635 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2636 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2637 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2638 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2639 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2640 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2641 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2642 }
2643#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002644 if (!validateMotionEvent(args->action, args->actionButton,
2645 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 return;
2647 }
2648
2649 uint32_t policyFlags = args->policyFlags;
2650 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002651
2652 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002654 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2655 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2656 std::to_string(t.duration().count()).c_str());
2657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658
2659 bool needWake;
2660 { // acquire lock
2661 mLock.lock();
2662
2663 if (shouldSendMotionToInputFilterLocked(args)) {
2664 mLock.unlock();
2665
2666 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002667 event.initialize(args->deviceId, args->source, args->displayId,
2668 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002669 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2670 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 args->downTime, args->eventTime,
2672 args->pointerCount, args->pointerProperties, args->pointerCoords);
2673
2674 policyFlags |= POLICY_FLAG_FILTERED;
2675 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2676 return; // event was consumed by the filter
2677 }
2678
2679 mLock.lock();
2680 }
2681
2682 // Just enqueue a new motion event.
2683 MotionEntry* newEntry = new MotionEntry(args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002684 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002685 args->action, args->actionButton, args->flags,
2686 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002688 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689
2690 needWake = enqueueInboundEventLocked(newEntry);
2691 mLock.unlock();
2692 } // release lock
2693
2694 if (needWake) {
2695 mLooper->wake();
2696 }
2697}
2698
2699bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2700 // TODO: support sending secondary display events to input filter
2701 return mInputFilterEnabled && isMainDisplay(args->displayId);
2702}
2703
2704void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2705#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002706 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2707 "switchMask=0x%08x",
2708 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709#endif
2710
2711 uint32_t policyFlags = args->policyFlags;
2712 policyFlags |= POLICY_FLAG_TRUSTED;
2713 mPolicy->notifySwitch(args->eventTime,
2714 args->switchValues, args->switchMask, policyFlags);
2715}
2716
2717void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2718#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002719 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 args->eventTime, args->deviceId);
2721#endif
2722
2723 bool needWake;
2724 { // acquire lock
2725 AutoMutex _l(mLock);
2726
2727 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2728 needWake = enqueueInboundEventLocked(newEntry);
2729 } // release lock
2730
2731 if (needWake) {
2732 mLooper->wake();
2733 }
2734}
2735
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002736int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2738 uint32_t policyFlags) {
2739#if DEBUG_INBOUND_EVENT_DETAILS
2740 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002741 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2742 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743#endif
2744
2745 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2746
2747 policyFlags |= POLICY_FLAG_INJECTED;
2748 if (hasInjectionPermission(injectorPid, injectorUid)) {
2749 policyFlags |= POLICY_FLAG_TRUSTED;
2750 }
2751
2752 EventEntry* firstInjectedEntry;
2753 EventEntry* lastInjectedEntry;
2754 switch (event->getType()) {
2755 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002756 KeyEvent keyEvent;
2757 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2758 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759 if (! validateKeyEvent(action)) {
2760 return INPUT_EVENT_INJECTION_FAILED;
2761 }
2762
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002763 int32_t flags = keyEvent.getFlags();
2764 int32_t keyCode = keyEvent.getKeyCode();
2765 int32_t metaState = keyEvent.getMetaState();
2766 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2767 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002768 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002769 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002770 keyEvent.getDownTime(), keyEvent.getEventTime());
2771
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2773 policyFlags |= POLICY_FLAG_VIRTUAL;
2774 }
2775
2776 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002777 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002778 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002779 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2780 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2781 std::to_string(t.duration().count()).c_str());
2782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783 }
2784
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 mLock.lock();
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002786 firstInjectedEntry = new KeyEntry(keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002787 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002789 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2790 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791 lastInjectedEntry = firstInjectedEntry;
2792 break;
2793 }
2794
2795 case AINPUT_EVENT_TYPE_MOTION: {
2796 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797 int32_t action = motionEvent->getAction();
2798 size_t pointerCount = motionEvent->getPointerCount();
2799 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002800 int32_t actionButton = motionEvent->getActionButton();
2801 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802 return INPUT_EVENT_INJECTION_FAILED;
2803 }
2804
2805 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2806 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002807 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002809 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2810 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2811 std::to_string(t.duration().count()).c_str());
2812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 }
2814
2815 mLock.lock();
2816 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2817 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2818 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002819 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2820 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002821 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 motionEvent->getMetaState(), motionEvent->getButtonState(),
2823 motionEvent->getEdgeFlags(),
2824 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002825 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002826 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2827 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 lastInjectedEntry = firstInjectedEntry;
2829 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2830 sampleEventTimes += 1;
2831 samplePointerCoords += pointerCount;
2832 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002833 motionEvent->getDeviceId(), motionEvent->getSource(),
2834 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002835 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 motionEvent->getMetaState(), motionEvent->getButtonState(),
2837 motionEvent->getEdgeFlags(),
2838 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002839 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002840 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2841 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 lastInjectedEntry->next = nextInjectedEntry;
2843 lastInjectedEntry = nextInjectedEntry;
2844 }
2845 break;
2846 }
2847
2848 default:
2849 ALOGW("Cannot inject event of type %d", event->getType());
2850 return INPUT_EVENT_INJECTION_FAILED;
2851 }
2852
2853 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2854 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2855 injectionState->injectionIsAsync = true;
2856 }
2857
2858 injectionState->refCount += 1;
2859 lastInjectedEntry->injectionState = injectionState;
2860
2861 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002862 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 EventEntry* nextEntry = entry->next;
2864 needWake |= enqueueInboundEventLocked(entry);
2865 entry = nextEntry;
2866 }
2867
2868 mLock.unlock();
2869
2870 if (needWake) {
2871 mLooper->wake();
2872 }
2873
2874 int32_t injectionResult;
2875 { // acquire lock
2876 AutoMutex _l(mLock);
2877
2878 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2879 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2880 } else {
2881 for (;;) {
2882 injectionResult = injectionState->injectionResult;
2883 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2884 break;
2885 }
2886
2887 nsecs_t remainingTimeout = endTime - now();
2888 if (remainingTimeout <= 0) {
2889#if DEBUG_INJECTION
2890 ALOGD("injectInputEvent - Timed out waiting for injection result "
2891 "to become available.");
2892#endif
2893 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2894 break;
2895 }
2896
2897 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2898 }
2899
2900 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2901 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2902 while (injectionState->pendingForegroundDispatches != 0) {
2903#if DEBUG_INJECTION
2904 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2905 injectionState->pendingForegroundDispatches);
2906#endif
2907 nsecs_t remainingTimeout = endTime - now();
2908 if (remainingTimeout <= 0) {
2909#if DEBUG_INJECTION
2910 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2911 "dispatches to finish.");
2912#endif
2913 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2914 break;
2915 }
2916
2917 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2918 }
2919 }
2920 }
2921
2922 injectionState->release();
2923 } // release lock
2924
2925#if DEBUG_INJECTION
2926 ALOGD("injectInputEvent - Finished with result %d. "
2927 "injectorPid=%d, injectorUid=%d",
2928 injectionResult, injectorPid, injectorUid);
2929#endif
2930
2931 return injectionResult;
2932}
2933
2934bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2935 return injectorUid == 0
2936 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2937}
2938
2939void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2940 InjectionState* injectionState = entry->injectionState;
2941 if (injectionState) {
2942#if DEBUG_INJECTION
2943 ALOGD("Setting input event injection result to %d. "
2944 "injectorPid=%d, injectorUid=%d",
2945 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2946#endif
2947
2948 if (injectionState->injectionIsAsync
2949 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2950 // Log the outcome since the injector did not wait for the injection result.
2951 switch (injectionResult) {
2952 case INPUT_EVENT_INJECTION_SUCCEEDED:
2953 ALOGV("Asynchronous input event injection succeeded.");
2954 break;
2955 case INPUT_EVENT_INJECTION_FAILED:
2956 ALOGW("Asynchronous input event injection failed.");
2957 break;
2958 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2959 ALOGW("Asynchronous input event injection permission denied.");
2960 break;
2961 case INPUT_EVENT_INJECTION_TIMED_OUT:
2962 ALOGW("Asynchronous input event injection timed out.");
2963 break;
2964 }
2965 }
2966
2967 injectionState->injectionResult = injectionResult;
2968 mInjectionResultAvailableCondition.broadcast();
2969 }
2970}
2971
2972void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2973 InjectionState* injectionState = entry->injectionState;
2974 if (injectionState) {
2975 injectionState->pendingForegroundDispatches += 1;
2976 }
2977}
2978
2979void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2980 InjectionState* injectionState = entry->injectionState;
2981 if (injectionState) {
2982 injectionState->pendingForegroundDispatches -= 1;
2983
2984 if (injectionState->pendingForegroundDispatches == 0) {
2985 mInjectionSyncFinishedCondition.broadcast();
2986 }
2987 }
2988}
2989
Arthur Hungb92218b2018-08-14 12:00:21 +08002990Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
2991 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
2992 mWindowHandlesByDisplay.find(displayId);
2993 if(it != mWindowHandlesByDisplay.end()) {
2994 return it->second;
2995 }
2996
2997 // Return an empty one if nothing found.
2998 return Vector<sp<InputWindowHandle>>();
2999}
3000
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3002 const sp<InputChannel>& inputChannel) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003003 for (auto& it : mWindowHandlesByDisplay) {
3004 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3005 size_t numWindows = windowHandles.size();
3006 for (size_t i = 0; i < numWindows; i++) {
3007 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
Robert Carr5c8a0262018-10-03 16:30:44 -07003008 if (windowHandle->getToken() == inputChannel->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003009 return windowHandle;
3010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 }
3012 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003013 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014}
3015
3016bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003017 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003018 for (auto& it : mWindowHandlesByDisplay) {
3019 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3020 size_t numWindows = windowHandles.size();
3021 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003022 if (windowHandles.itemAt(i)->getToken()
3023 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003024 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003025 ALOGE("Found window %s in display %" PRId32
3026 ", but it should belong to display %" PRId32,
3027 windowHandle->getName().c_str(), it.first,
3028 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003029 }
3030 return true;
3031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032 }
3033 }
3034 return false;
3035}
3036
Robert Carr5c8a0262018-10-03 16:30:44 -07003037sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3038 size_t count = mInputChannelsByToken.count(token);
3039 if (count == 0) {
3040 return nullptr;
3041 }
3042 return mInputChannelsByToken.at(token);
3043}
3044
Arthur Hungb92218b2018-08-14 12:00:21 +08003045/**
3046 * Called from InputManagerService, update window handle list by displayId that can receive input.
3047 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3048 * If set an empty list, remove all handles from the specific display.
3049 * For focused handle, check if need to change and send a cancel event to previous one.
3050 * For removed handle, check if need to send a cancel event if already in touch.
3051 */
3052void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3053 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003055 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056#endif
3057 { // acquire lock
3058 AutoMutex _l(mLock);
3059
Arthur Hungb92218b2018-08-14 12:00:21 +08003060 // Copy old handles for release if they are no longer present.
3061 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062
Tiger Huang721e26f2018-07-24 22:26:19 +08003063 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003064 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003065
3066 if (inputWindowHandles.isEmpty()) {
3067 // Remove all handles on a display if there are no windows left.
3068 mWindowHandlesByDisplay.erase(displayId);
3069 } else {
3070 size_t numWindows = inputWindowHandles.size();
3071 for (size_t i = 0; i < numWindows; i++) {
3072 const sp<InputWindowHandle>& windowHandle = inputWindowHandles.itemAt(i);
Robert Carr5c8a0262018-10-03 16:30:44 -07003073 if (!windowHandle->updateInfo() || getInputChannelLocked(windowHandle->getToken()) == nullptr) {
3074 ALOGE("Window handle %s has no registered input channel",
3075 windowHandle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003076 continue;
3077 }
3078
3079 if (windowHandle->getInfo()->displayId != displayId) {
3080 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3081 windowHandle->getName().c_str(), displayId,
3082 windowHandle->getInfo()->displayId);
3083 continue;
3084 }
3085
3086 if (windowHandle->getInfo()->hasFocus) {
3087 newFocusedWindowHandle = windowHandle;
3088 }
3089 if (windowHandle == mLastHoverWindowHandle) {
3090 foundHoveredWindow = true;
3091 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003092 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003093
3094 // Insert or replace
3095 mWindowHandlesByDisplay[displayId] = inputWindowHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003096 }
3097
3098 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003099 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 }
3101
Tiger Huang721e26f2018-07-24 22:26:19 +08003102 sp<InputWindowHandle> oldFocusedWindowHandle =
3103 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3104
3105 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3106 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003108 ALOGD("Focus left window: %s in display %" PRId32,
3109 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003111 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3112 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003113 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3115 "focus left window");
3116 synthesizeCancelationEventsForInputChannelLocked(
3117 focusedInputChannel, options);
3118 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003119 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003121 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003123 ALOGD("Focus entered window: %s in display %" PRId32,
3124 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003126 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003127 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 }
3129
Arthur Hungb92218b2018-08-14 12:00:21 +08003130 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3131 if (stateIndex >= 0) {
3132 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003133 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003134 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003135 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003137 ALOGD("Touched window was removed: %s in display %" PRId32,
3138 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003140 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003141 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003142 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003143 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3144 "touched window was removed");
3145 synthesizeCancelationEventsForInputChannelLocked(
3146 touchedInputChannel, options);
3147 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003148 state.windows.removeAt(i);
3149 } else {
3150 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 }
3153 }
3154
3155 // Release information for windows that are no longer present.
3156 // This ensures that unused input channels are released promptly.
3157 // Otherwise, they might stick around until the window handle is destroyed
3158 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003159 size_t numWindows = oldWindowHandles.size();
3160 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003162 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003164 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003166 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 }
3168 }
3169 } // release lock
3170
3171 // Wake up poll loop since it may need to make new input dispatching choices.
3172 mLooper->wake();
3173}
3174
3175void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003176 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003178 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179#endif
3180 { // acquire lock
3181 AutoMutex _l(mLock);
3182
Tiger Huang721e26f2018-07-24 22:26:19 +08003183 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3184 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003185 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003186 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3187 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003189 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003191 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003193 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003195 oldFocusedApplicationHandle->releaseInfo();
3196 oldFocusedApplicationHandle.clear();
3197 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 }
3199
3200#if DEBUG_FOCUS
3201 //logDispatchStateLocked();
3202#endif
3203 } // release lock
3204
3205 // Wake up poll loop since it may need to make new input dispatching choices.
3206 mLooper->wake();
3207}
3208
Tiger Huang721e26f2018-07-24 22:26:19 +08003209/**
3210 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3211 * the display not specified.
3212 *
3213 * We track any unreleased events for each window. If a window loses the ability to receive the
3214 * released event, we will send a cancel event to it. So when the focused display is changed, we
3215 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3216 * display. The display-specified events won't be affected.
3217 */
3218void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3219#if DEBUG_FOCUS
3220 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3221#endif
3222 { // acquire lock
3223 AutoMutex _l(mLock);
3224
3225 if (mFocusedDisplayId != displayId) {
3226 sp<InputWindowHandle> oldFocusedWindowHandle =
3227 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3228 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003229 sp<InputChannel> inputChannel =
3230 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003231 if (inputChannel != nullptr) {
3232 CancelationOptions options(
3233 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3234 "The display which contains this window no longer has focus.");
3235 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3236 }
3237 }
3238 mFocusedDisplayId = displayId;
3239
3240 // Sanity check
3241 sp<InputWindowHandle> newFocusedWindowHandle =
3242 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3243 if (newFocusedWindowHandle == nullptr) {
3244 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3245 if (!mFocusedWindowHandlesByDisplay.empty()) {
3246 ALOGE("But another display has a focused window:");
3247 for (auto& it : mFocusedWindowHandlesByDisplay) {
3248 const int32_t displayId = it.first;
3249 const sp<InputWindowHandle>& windowHandle = it.second;
3250 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3251 displayId, windowHandle->getName().c_str());
3252 }
3253 }
3254 }
3255 }
3256
3257#if DEBUG_FOCUS
3258 logDispatchStateLocked();
3259#endif
3260 } // release lock
3261
3262 // Wake up poll loop since it may need to make new input dispatching choices.
3263 mLooper->wake();
3264}
3265
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3267#if DEBUG_FOCUS
3268 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3269#endif
3270
3271 bool changed;
3272 { // acquire lock
3273 AutoMutex _l(mLock);
3274
3275 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3276 if (mDispatchFrozen && !frozen) {
3277 resetANRTimeoutsLocked();
3278 }
3279
3280 if (mDispatchEnabled && !enabled) {
3281 resetAndDropEverythingLocked("dispatcher is being disabled");
3282 }
3283
3284 mDispatchEnabled = enabled;
3285 mDispatchFrozen = frozen;
3286 changed = true;
3287 } else {
3288 changed = false;
3289 }
3290
3291#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003292 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293#endif
3294 } // release lock
3295
3296 if (changed) {
3297 // Wake up poll loop since it may need to make new input dispatching choices.
3298 mLooper->wake();
3299 }
3300}
3301
3302void InputDispatcher::setInputFilterEnabled(bool enabled) {
3303#if DEBUG_FOCUS
3304 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3305#endif
3306
3307 { // acquire lock
3308 AutoMutex _l(mLock);
3309
3310 if (mInputFilterEnabled == enabled) {
3311 return;
3312 }
3313
3314 mInputFilterEnabled = enabled;
3315 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3316 } // release lock
3317
3318 // Wake up poll loop since there might be work to do to drop everything.
3319 mLooper->wake();
3320}
3321
3322bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3323 const sp<InputChannel>& toChannel) {
3324#if DEBUG_FOCUS
3325 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003326 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327#endif
3328 { // acquire lock
3329 AutoMutex _l(mLock);
3330
3331 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3332 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07003333 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334#if DEBUG_FOCUS
3335 ALOGD("Cannot transfer focus because from or to window not found.");
3336#endif
3337 return false;
3338 }
3339 if (fromWindowHandle == toWindowHandle) {
3340#if DEBUG_FOCUS
3341 ALOGD("Trivial transfer to same window.");
3342#endif
3343 return true;
3344 }
3345 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3346#if DEBUG_FOCUS
3347 ALOGD("Cannot transfer focus because windows are on different displays.");
3348#endif
3349 return false;
3350 }
3351
3352 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003353 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3354 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3355 for (size_t i = 0; i < state.windows.size(); i++) {
3356 const TouchedWindow& touchedWindow = state.windows[i];
3357 if (touchedWindow.windowHandle == fromWindowHandle) {
3358 int32_t oldTargetFlags = touchedWindow.targetFlags;
3359 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360
Jeff Brownf086ddb2014-02-11 14:28:48 -08003361 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362
Jeff Brownf086ddb2014-02-11 14:28:48 -08003363 int32_t newTargetFlags = oldTargetFlags
3364 & (InputTarget::FLAG_FOREGROUND
3365 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3366 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367
Jeff Brownf086ddb2014-02-11 14:28:48 -08003368 found = true;
3369 goto Found;
3370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 }
3372 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003373Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374
3375 if (! found) {
3376#if DEBUG_FOCUS
3377 ALOGD("Focus transfer failed because from window did not have focus.");
3378#endif
3379 return false;
3380 }
3381
3382 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3383 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3384 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3385 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3386 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3387
3388 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3389 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3390 "transferring touch focus from this window to another window");
3391 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3392 }
3393
3394#if DEBUG_FOCUS
3395 logDispatchStateLocked();
3396#endif
3397 } // release lock
3398
3399 // Wake up poll loop since it may need to make new input dispatching choices.
3400 mLooper->wake();
3401 return true;
3402}
3403
3404void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3405#if DEBUG_FOCUS
3406 ALOGD("Resetting and dropping all events (%s).", reason);
3407#endif
3408
3409 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3410 synthesizeCancelationEventsForAllConnectionsLocked(options);
3411
3412 resetKeyRepeatLocked();
3413 releasePendingEventLocked();
3414 drainInboundQueueLocked();
3415 resetANRTimeoutsLocked();
3416
Jeff Brownf086ddb2014-02-11 14:28:48 -08003417 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003419 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420}
3421
3422void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003423 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 dumpDispatchStateLocked(dump);
3425
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003426 std::istringstream stream(dump);
3427 std::string line;
3428
3429 while (std::getline(stream, line, '\n')) {
3430 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431 }
3432}
3433
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003434void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3435 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3436 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003437 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438
Tiger Huang721e26f2018-07-24 22:26:19 +08003439 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3440 dump += StringPrintf(INDENT "FocusedApplications:\n");
3441 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3442 const int32_t displayId = it.first;
3443 const sp<InputApplicationHandle>& applicationHandle = it.second;
3444 dump += StringPrintf(
3445 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3446 displayId,
3447 applicationHandle->getName().c_str(),
3448 applicationHandle->getDispatchingTimeout(
3449 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003452 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003454
3455 if (!mFocusedWindowHandlesByDisplay.empty()) {
3456 dump += StringPrintf(INDENT "FocusedWindows:\n");
3457 for (auto& it : mFocusedWindowHandlesByDisplay) {
3458 const int32_t displayId = it.first;
3459 const sp<InputWindowHandle>& windowHandle = it.second;
3460 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3461 displayId, windowHandle->getName().c_str());
3462 }
3463 } else {
3464 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3465 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466
Jeff Brownf086ddb2014-02-11 14:28:48 -08003467 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003468 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003469 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3470 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003471 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003472 state.displayId, toString(state.down), toString(state.split),
3473 state.deviceId, state.source);
3474 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003475 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003476 for (size_t i = 0; i < state.windows.size(); i++) {
3477 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003478 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3479 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003480 touchedWindow.pointerIds.value,
3481 touchedWindow.targetFlags);
3482 }
3483 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003484 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003485 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 }
3487 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003488 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489 }
3490
Arthur Hungb92218b2018-08-14 12:00:21 +08003491 if (!mWindowHandlesByDisplay.empty()) {
3492 for (auto& it : mWindowHandlesByDisplay) {
3493 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003494 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003495 if (!windowHandles.isEmpty()) {
3496 dump += INDENT2 "Windows:\n";
3497 for (size_t i = 0; i < windowHandles.size(); i++) {
3498 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3499 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500
Arthur Hungb92218b2018-08-14 12:00:21 +08003501 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3502 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3503 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3504 "frame=[%d,%d][%d,%d], scale=%f, "
3505 "touchableRegion=",
3506 i, windowInfo->name.c_str(), windowInfo->displayId,
3507 toString(windowInfo->paused),
3508 toString(windowInfo->hasFocus),
3509 toString(windowInfo->hasWallpaper),
3510 toString(windowInfo->visible),
3511 toString(windowInfo->canReceiveKeys),
3512 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3513 windowInfo->layer,
3514 windowInfo->frameLeft, windowInfo->frameTop,
3515 windowInfo->frameRight, windowInfo->frameBottom,
3516 windowInfo->scaleFactor);
3517 dumpRegion(dump, windowInfo->touchableRegion);
3518 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3519 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3520 windowInfo->ownerPid, windowInfo->ownerUid,
3521 windowInfo->dispatchingTimeout / 1000000.0);
3522 }
3523 } else {
3524 dump += INDENT2 "Windows: <none>\n";
3525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 }
3527 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003528 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 }
3530
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003531 if (!mMonitoringChannelsByDisplay.empty()) {
3532 for (auto& it : mMonitoringChannelsByDisplay) {
3533 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003534 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003535 const size_t numChannels = monitoringChannels.size();
3536 for (size_t i = 0; i < numChannels; i++) {
3537 const sp<InputChannel>& channel = monitoringChannels[i];
3538 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3539 }
3540 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003542 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543 }
3544
3545 nsecs_t currentTime = now();
3546
3547 // Dump recently dispatched or dropped events from oldest to newest.
3548 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003549 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003551 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003553 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554 (currentTime - entry->eventTime) * 0.000001f);
3555 }
3556 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003557 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 }
3559
3560 // Dump event currently being dispatched.
3561 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003562 dump += INDENT "PendingEvent:\n";
3563 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003565 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3567 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003568 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569 }
3570
3571 // Dump inbound events from oldest to newest.
3572 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003573 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003575 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003577 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003578 (currentTime - entry->eventTime) * 0.000001f);
3579 }
3580 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003581 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 }
3583
Michael Wright78f24442014-08-06 15:55:28 -07003584 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003585 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003586 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3587 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3588 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003589 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003590 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3591 }
3592 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003593 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003594 }
3595
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003597 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3599 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003600 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003602 i, connection->getInputChannelName().c_str(),
3603 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 connection->getStatusLabel(), toString(connection->monitor),
3605 toString(connection->inputPublisherBlocked));
3606
3607 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003608 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 connection->outboundQueue.count());
3610 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3611 entry = entry->next) {
3612 dump.append(INDENT4);
3613 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003614 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 entry->targetFlags, entry->resolvedAction,
3616 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3617 }
3618 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003619 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 }
3621
3622 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003623 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 connection->waitQueue.count());
3625 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3626 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003627 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003629 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 "age=%0.1fms, wait=%0.1fms\n",
3631 entry->targetFlags, entry->resolvedAction,
3632 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3633 (currentTime - entry->deliveryTime) * 0.000001f);
3634 }
3635 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003636 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 }
3638 }
3639 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003640 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 }
3642
3643 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003644 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 (mAppSwitchDueTime - now()) / 1000000.0);
3646 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003647 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 }
3649
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003650 dump += INDENT "Configuration:\n";
3651 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003653 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 mConfig.keyRepeatTimeout * 0.000001f);
3655}
3656
Robert Carr803535b2018-08-02 16:38:15 -07003657status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003659 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3660 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661#endif
3662
3663 { // acquire lock
3664 AutoMutex _l(mLock);
3665
Robert Carr4e670e52018-08-15 13:26:12 -07003666 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3667 // treat inputChannel as monitor channel for displayId.
3668 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3669 if (monitor) {
3670 inputChannel->setToken(new BBinder());
3671 }
3672
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673 if (getConnectionIndexLocked(inputChannel) >= 0) {
3674 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003675 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 return BAD_VALUE;
3677 }
3678
Robert Carr803535b2018-08-02 16:38:15 -07003679 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680
3681 int fd = inputChannel->getFd();
3682 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003683 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003685 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003687 Vector<sp<InputChannel>>& monitoringChannels =
3688 mMonitoringChannelsByDisplay[displayId];
3689 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 }
3691
3692 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3693 } // release lock
3694
3695 // Wake the looper because some connections have changed.
3696 mLooper->wake();
3697 return OK;
3698}
3699
3700status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3701#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003702 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703#endif
3704
3705 { // acquire lock
3706 AutoMutex _l(mLock);
3707
3708 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3709 if (status) {
3710 return status;
3711 }
3712 } // release lock
3713
3714 // Wake the poll loop because removing the connection may have changed the current
3715 // synchronization state.
3716 mLooper->wake();
3717 return OK;
3718}
3719
3720status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3721 bool notify) {
3722 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3723 if (connectionIndex < 0) {
3724 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003725 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 return BAD_VALUE;
3727 }
3728
3729 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3730 mConnectionsByFd.removeItemsAt(connectionIndex);
3731
Robert Carr5c8a0262018-10-03 16:30:44 -07003732 mInputChannelsByToken.erase(inputChannel->getToken());
3733
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 if (connection->monitor) {
3735 removeMonitorChannelLocked(inputChannel);
3736 }
3737
3738 mLooper->removeFd(inputChannel->getFd());
3739
3740 nsecs_t currentTime = now();
3741 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3742
3743 connection->status = Connection::STATUS_ZOMBIE;
3744 return OK;
3745}
3746
3747void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003748 for (auto it = mMonitoringChannelsByDisplay.begin();
3749 it != mMonitoringChannelsByDisplay.end(); ) {
3750 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3751 const size_t numChannels = monitoringChannels.size();
3752 for (size_t i = 0; i < numChannels; i++) {
3753 if (monitoringChannels[i] == inputChannel) {
3754 monitoringChannels.removeAt(i);
3755 break;
3756 }
3757 }
3758 if (monitoringChannels.empty()) {
3759 it = mMonitoringChannelsByDisplay.erase(it);
3760 } else {
3761 ++it;
3762 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763 }
3764}
3765
3766ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003767 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003768 return -1;
3769 }
3770
Robert Carr4e670e52018-08-15 13:26:12 -07003771 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3772 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3773 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3774 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 }
3776 }
Robert Carr4e670e52018-08-15 13:26:12 -07003777
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 return -1;
3779}
3780
3781void InputDispatcher::onDispatchCycleFinishedLocked(
3782 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3783 CommandEntry* commandEntry = postCommandLocked(
3784 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3785 commandEntry->connection = connection;
3786 commandEntry->eventTime = currentTime;
3787 commandEntry->seq = seq;
3788 commandEntry->handled = handled;
3789}
3790
3791void InputDispatcher::onDispatchCycleBrokenLocked(
3792 nsecs_t currentTime, const sp<Connection>& connection) {
3793 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003794 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795
3796 CommandEntry* commandEntry = postCommandLocked(
3797 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3798 commandEntry->connection = connection;
3799}
3800
3801void InputDispatcher::onANRLocked(
3802 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3803 const sp<InputWindowHandle>& windowHandle,
3804 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3805 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3806 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3807 ALOGI("Application is not responding: %s. "
3808 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003809 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 dispatchLatency, waitDuration, reason);
3811
3812 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003813 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 struct tm tm;
3815 localtime_r(&t, &tm);
3816 char timestr[64];
3817 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3818 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003819 mLastANRState += INDENT "ANR:\n";
3820 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3821 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3822 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3823 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3824 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3825 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003826 dumpDispatchStateLocked(mLastANRState);
3827
3828 CommandEntry* commandEntry = postCommandLocked(
3829 & InputDispatcher::doNotifyANRLockedInterruptible);
3830 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003831 commandEntry->inputChannel = windowHandle != nullptr ?
3832 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003833 commandEntry->reason = reason;
3834}
3835
3836void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3837 CommandEntry* commandEntry) {
3838 mLock.unlock();
3839
3840 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3841
3842 mLock.lock();
3843}
3844
3845void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3846 CommandEntry* commandEntry) {
3847 sp<Connection> connection = commandEntry->connection;
3848
3849 if (connection->status != Connection::STATUS_ZOMBIE) {
3850 mLock.unlock();
3851
Robert Carr803535b2018-08-02 16:38:15 -07003852 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853
3854 mLock.lock();
3855 }
3856}
3857
3858void InputDispatcher::doNotifyANRLockedInterruptible(
3859 CommandEntry* commandEntry) {
3860 mLock.unlock();
3861
3862 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003863 commandEntry->inputApplicationHandle,
3864 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003865 commandEntry->reason);
3866
3867 mLock.lock();
3868
3869 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003870 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003871}
3872
3873void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3874 CommandEntry* commandEntry) {
3875 KeyEntry* entry = commandEntry->keyEntry;
3876
3877 KeyEvent event;
3878 initializeKeyEvent(&event, entry);
3879
3880 mLock.unlock();
3881
Michael Wright2b3c3302018-03-02 17:19:13 +00003882 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003883 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3884 commandEntry->inputChannel->getToken() : nullptr;
3885 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003887 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3888 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3889 std::to_string(t.duration().count()).c_str());
3890 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891
3892 mLock.lock();
3893
3894 if (delay < 0) {
3895 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3896 } else if (!delay) {
3897 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3898 } else {
3899 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3900 entry->interceptKeyWakeupTime = now() + delay;
3901 }
3902 entry->release();
3903}
3904
3905void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3906 CommandEntry* commandEntry) {
3907 sp<Connection> connection = commandEntry->connection;
3908 nsecs_t finishTime = commandEntry->eventTime;
3909 uint32_t seq = commandEntry->seq;
3910 bool handled = commandEntry->handled;
3911
3912 // Handle post-event policy actions.
3913 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3914 if (dispatchEntry) {
3915 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3916 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003917 std::string msg =
3918 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003919 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003920 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003921 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 }
3923
3924 bool restartEvent;
3925 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3926 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3927 restartEvent = afterKeyEventLockedInterruptible(connection,
3928 dispatchEntry, keyEntry, handled);
3929 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3930 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3931 restartEvent = afterMotionEventLockedInterruptible(connection,
3932 dispatchEntry, motionEntry, handled);
3933 } else {
3934 restartEvent = false;
3935 }
3936
3937 // Dequeue the event and start the next cycle.
3938 // Note that because the lock might have been released, it is possible that the
3939 // contents of the wait queue to have been drained, so we need to double-check
3940 // a few things.
3941 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3942 connection->waitQueue.dequeue(dispatchEntry);
3943 traceWaitQueueLengthLocked(connection);
3944 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3945 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3946 traceOutboundQueueLengthLocked(connection);
3947 } else {
3948 releaseDispatchEntryLocked(dispatchEntry);
3949 }
3950 }
3951
3952 // Start the next dispatch cycle for this connection.
3953 startDispatchCycleLocked(now(), connection);
3954 }
3955}
3956
3957bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3958 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3959 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3960 // Get the fallback key state.
3961 // Clear it out after dispatching the UP.
3962 int32_t originalKeyCode = keyEntry->keyCode;
3963 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3964 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3965 connection->inputState.removeFallbackKey(originalKeyCode);
3966 }
3967
3968 if (handled || !dispatchEntry->hasForegroundTarget()) {
3969 // If the application handles the original key for which we previously
3970 // generated a fallback or if the window is not a foreground window,
3971 // then cancel the associated fallback key, if any.
3972 if (fallbackKeyCode != -1) {
3973 // Dispatch the unhandled key to the policy with the cancel flag.
3974#if DEBUG_OUTBOUND_EVENT_DETAILS
3975 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3976 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3977 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3978 keyEntry->policyFlags);
3979#endif
3980 KeyEvent event;
3981 initializeKeyEvent(&event, keyEntry);
3982 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3983
3984 mLock.unlock();
3985
Robert Carr803535b2018-08-02 16:38:15 -07003986 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 &event, keyEntry->policyFlags, &event);
3988
3989 mLock.lock();
3990
3991 // Cancel the fallback key.
3992 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3993 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3994 "application handled the original non-fallback key "
3995 "or is no longer a foreground target, "
3996 "canceling previously dispatched fallback key");
3997 options.keyCode = fallbackKeyCode;
3998 synthesizeCancelationEventsForConnectionLocked(connection, options);
3999 }
4000 connection->inputState.removeFallbackKey(originalKeyCode);
4001 }
4002 } else {
4003 // If the application did not handle a non-fallback key, first check
4004 // that we are in a good state to perform unhandled key event processing
4005 // Then ask the policy what to do with it.
4006 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4007 && keyEntry->repeatCount == 0;
4008 if (fallbackKeyCode == -1 && !initialDown) {
4009#if DEBUG_OUTBOUND_EVENT_DETAILS
4010 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4011 "since this is not an initial down. "
4012 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4013 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4014 keyEntry->policyFlags);
4015#endif
4016 return false;
4017 }
4018
4019 // Dispatch the unhandled key to the policy.
4020#if DEBUG_OUTBOUND_EVENT_DETAILS
4021 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4022 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4023 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4024 keyEntry->policyFlags);
4025#endif
4026 KeyEvent event;
4027 initializeKeyEvent(&event, keyEntry);
4028
4029 mLock.unlock();
4030
Robert Carr803535b2018-08-02 16:38:15 -07004031 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004032 &event, keyEntry->policyFlags, &event);
4033
4034 mLock.lock();
4035
4036 if (connection->status != Connection::STATUS_NORMAL) {
4037 connection->inputState.removeFallbackKey(originalKeyCode);
4038 return false;
4039 }
4040
4041 // Latch the fallback keycode for this key on an initial down.
4042 // The fallback keycode cannot change at any other point in the lifecycle.
4043 if (initialDown) {
4044 if (fallback) {
4045 fallbackKeyCode = event.getKeyCode();
4046 } else {
4047 fallbackKeyCode = AKEYCODE_UNKNOWN;
4048 }
4049 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4050 }
4051
4052 ALOG_ASSERT(fallbackKeyCode != -1);
4053
4054 // Cancel the fallback key if the policy decides not to send it anymore.
4055 // We will continue to dispatch the key to the policy but we will no
4056 // longer dispatch a fallback key to the application.
4057 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4058 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4059#if DEBUG_OUTBOUND_EVENT_DETAILS
4060 if (fallback) {
4061 ALOGD("Unhandled key event: Policy requested to send key %d"
4062 "as a fallback for %d, but on the DOWN it had requested "
4063 "to send %d instead. Fallback canceled.",
4064 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4065 } else {
4066 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4067 "but on the DOWN it had requested to send %d. "
4068 "Fallback canceled.",
4069 originalKeyCode, fallbackKeyCode);
4070 }
4071#endif
4072
4073 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4074 "canceling fallback, policy no longer desires it");
4075 options.keyCode = fallbackKeyCode;
4076 synthesizeCancelationEventsForConnectionLocked(connection, options);
4077
4078 fallback = false;
4079 fallbackKeyCode = AKEYCODE_UNKNOWN;
4080 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4081 connection->inputState.setFallbackKey(originalKeyCode,
4082 fallbackKeyCode);
4083 }
4084 }
4085
4086#if DEBUG_OUTBOUND_EVENT_DETAILS
4087 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004088 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4090 connection->inputState.getFallbackKeys();
4091 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004092 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 fallbackKeys.valueAt(i));
4094 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07004095 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004096 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 }
4098#endif
4099
4100 if (fallback) {
4101 // Restart the dispatch cycle using the fallback key.
4102 keyEntry->eventTime = event.getEventTime();
4103 keyEntry->deviceId = event.getDeviceId();
4104 keyEntry->source = event.getSource();
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004105 keyEntry->displayId = event.getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4107 keyEntry->keyCode = fallbackKeyCode;
4108 keyEntry->scanCode = event.getScanCode();
4109 keyEntry->metaState = event.getMetaState();
4110 keyEntry->repeatCount = event.getRepeatCount();
4111 keyEntry->downTime = event.getDownTime();
4112 keyEntry->syntheticRepeat = false;
4113
4114#if DEBUG_OUTBOUND_EVENT_DETAILS
4115 ALOGD("Unhandled key event: Dispatching fallback key. "
4116 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4117 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4118#endif
4119 return true; // restart the event
4120 } else {
4121#if DEBUG_OUTBOUND_EVENT_DETAILS
4122 ALOGD("Unhandled key event: No fallback key.");
4123#endif
4124 }
4125 }
4126 }
4127 return false;
4128}
4129
4130bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4131 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4132 return false;
4133}
4134
4135void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4136 mLock.unlock();
4137
4138 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4139
4140 mLock.lock();
4141}
4142
4143void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004144 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4146 entry->downTime, entry->eventTime);
4147}
4148
4149void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4150 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4151 // TODO Write some statistics about how long we spend waiting.
4152}
4153
4154void InputDispatcher::traceInboundQueueLengthLocked() {
4155 if (ATRACE_ENABLED()) {
4156 ATRACE_INT("iq", mInboundQueue.count());
4157 }
4158}
4159
4160void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4161 if (ATRACE_ENABLED()) {
4162 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004163 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 ATRACE_INT(counterName, connection->outboundQueue.count());
4165 }
4166}
4167
4168void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4169 if (ATRACE_ENABLED()) {
4170 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004171 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 ATRACE_INT(counterName, connection->waitQueue.count());
4173 }
4174}
4175
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004176void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 AutoMutex _l(mLock);
4178
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004179 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 dumpDispatchStateLocked(dump);
4181
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004182 if (!mLastANRState.empty()) {
4183 dump += "\nInput Dispatcher State at time of last ANR:\n";
4184 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 }
4186}
4187
4188void InputDispatcher::monitor() {
4189 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4190 mLock.lock();
4191 mLooper->wake();
4192 mDispatcherIsAliveCondition.wait(mLock);
4193 mLock.unlock();
4194}
4195
4196
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197// --- InputDispatcher::InjectionState ---
4198
4199InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4200 refCount(1),
4201 injectorPid(injectorPid), injectorUid(injectorUid),
4202 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4203 pendingForegroundDispatches(0) {
4204}
4205
4206InputDispatcher::InjectionState::~InjectionState() {
4207}
4208
4209void InputDispatcher::InjectionState::release() {
4210 refCount -= 1;
4211 if (refCount == 0) {
4212 delete this;
4213 } else {
4214 ALOG_ASSERT(refCount > 0);
4215 }
4216}
4217
4218
4219// --- InputDispatcher::EventEntry ---
4220
4221InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4222 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
Yi Kong9b14ac62018-07-17 13:48:38 -07004223 injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224}
4225
4226InputDispatcher::EventEntry::~EventEntry() {
4227 releaseInjectionState();
4228}
4229
4230void InputDispatcher::EventEntry::release() {
4231 refCount -= 1;
4232 if (refCount == 0) {
4233 delete this;
4234 } else {
4235 ALOG_ASSERT(refCount > 0);
4236 }
4237}
4238
4239void InputDispatcher::EventEntry::releaseInjectionState() {
4240 if (injectionState) {
4241 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004242 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004243 }
4244}
4245
4246
4247// --- InputDispatcher::ConfigurationChangedEntry ---
4248
4249InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4250 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4251}
4252
4253InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4254}
4255
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004256void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4257 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258}
4259
4260
4261// --- InputDispatcher::DeviceResetEntry ---
4262
4263InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4264 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4265 deviceId(deviceId) {
4266}
4267
4268InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4269}
4270
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004271void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4272 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 deviceId, policyFlags);
4274}
4275
4276
4277// --- InputDispatcher::KeyEntry ---
4278
4279InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004280 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4282 int32_t repeatCount, nsecs_t downTime) :
4283 EventEntry(TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004284 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4286 repeatCount(repeatCount), downTime(downTime),
4287 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4288 interceptKeyWakeupTime(0) {
4289}
4290
4291InputDispatcher::KeyEntry::~KeyEntry() {
4292}
4293
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004294void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004295 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4297 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004298 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004299 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300}
4301
4302void InputDispatcher::KeyEntry::recycle() {
4303 releaseInjectionState();
4304
4305 dispatchInProgress = false;
4306 syntheticRepeat = false;
4307 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4308 interceptKeyWakeupTime = 0;
4309}
4310
4311
4312// --- InputDispatcher::MotionEntry ---
4313
Michael Wright7b159c92015-05-14 14:48:03 +01004314InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004315 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4316 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004317 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4318 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004319 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004320 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4321 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4323 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004324 deviceId(deviceId), source(source), displayId(displayId), action(action),
4325 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004326 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004327 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 for (uint32_t i = 0; i < pointerCount; i++) {
4329 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4330 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004331 if (xOffset || yOffset) {
4332 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 }
4335}
4336
4337InputDispatcher::MotionEntry::~MotionEntry() {
4338}
4339
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004340void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004341 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004342 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004343 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004344 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4345 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4346
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 for (uint32_t i = 0; i < pointerCount; i++) {
4348 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004349 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004351 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 pointerCoords[i].getX(), pointerCoords[i].getY());
4353 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004354 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355}
4356
4357
4358// --- InputDispatcher::DispatchEntry ---
4359
4360volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4361
4362InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4363 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4364 seq(nextSeq()),
4365 eventEntry(eventEntry), targetFlags(targetFlags),
4366 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4367 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4368 eventEntry->refCount += 1;
4369}
4370
4371InputDispatcher::DispatchEntry::~DispatchEntry() {
4372 eventEntry->release();
4373}
4374
4375uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4376 // Sequence number 0 is reserved and will never be returned.
4377 uint32_t seq;
4378 do {
4379 seq = android_atomic_inc(&sNextSeqAtomic);
4380 } while (!seq);
4381 return seq;
4382}
4383
4384
4385// --- InputDispatcher::InputState ---
4386
4387InputDispatcher::InputState::InputState() {
4388}
4389
4390InputDispatcher::InputState::~InputState() {
4391}
4392
4393bool InputDispatcher::InputState::isNeutral() const {
4394 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4395}
4396
4397bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4398 int32_t displayId) const {
4399 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4400 const MotionMemento& memento = mMotionMementos.itemAt(i);
4401 if (memento.deviceId == deviceId
4402 && memento.source == source
4403 && memento.displayId == displayId
4404 && memento.hovering) {
4405 return true;
4406 }
4407 }
4408 return false;
4409}
4410
4411bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4412 int32_t action, int32_t flags) {
4413 switch (action) {
4414 case AKEY_EVENT_ACTION_UP: {
4415 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4416 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4417 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4418 mFallbackKeys.removeItemsAt(i);
4419 } else {
4420 i += 1;
4421 }
4422 }
4423 }
4424 ssize_t index = findKeyMemento(entry);
4425 if (index >= 0) {
4426 mKeyMementos.removeAt(index);
4427 return true;
4428 }
4429 /* FIXME: We can't just drop the key up event because that prevents creating
4430 * popup windows that are automatically shown when a key is held and then
4431 * dismissed when the key is released. The problem is that the popup will
4432 * not have received the original key down, so the key up will be considered
4433 * to be inconsistent with its observed state. We could perhaps handle this
4434 * by synthesizing a key down but that will cause other problems.
4435 *
4436 * So for now, allow inconsistent key up events to be dispatched.
4437 *
4438#if DEBUG_OUTBOUND_EVENT_DETAILS
4439 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4440 "keyCode=%d, scanCode=%d",
4441 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4442#endif
4443 return false;
4444 */
4445 return true;
4446 }
4447
4448 case AKEY_EVENT_ACTION_DOWN: {
4449 ssize_t index = findKeyMemento(entry);
4450 if (index >= 0) {
4451 mKeyMementos.removeAt(index);
4452 }
4453 addKeyMemento(entry, flags);
4454 return true;
4455 }
4456
4457 default:
4458 return true;
4459 }
4460}
4461
4462bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4463 int32_t action, int32_t flags) {
4464 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4465 switch (actionMasked) {
4466 case AMOTION_EVENT_ACTION_UP:
4467 case AMOTION_EVENT_ACTION_CANCEL: {
4468 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4469 if (index >= 0) {
4470 mMotionMementos.removeAt(index);
4471 return true;
4472 }
4473#if DEBUG_OUTBOUND_EVENT_DETAILS
4474 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004475 "displayId=%" PRId32 ", actionMasked=%d",
4476 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477#endif
4478 return false;
4479 }
4480
4481 case AMOTION_EVENT_ACTION_DOWN: {
4482 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4483 if (index >= 0) {
4484 mMotionMementos.removeAt(index);
4485 }
4486 addMotionMemento(entry, flags, false /*hovering*/);
4487 return true;
4488 }
4489
4490 case AMOTION_EVENT_ACTION_POINTER_UP:
4491 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4492 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004493 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4494 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4495 // generate cancellation events for these since they're based in relative rather than
4496 // absolute units.
4497 return true;
4498 }
4499
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004501
4502 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4503 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4504 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4505 // other value and we need to track the motion so we can send cancellation events for
4506 // anything generating fallback events (e.g. DPad keys for joystick movements).
4507 if (index >= 0) {
4508 if (entry->pointerCoords[0].isEmpty()) {
4509 mMotionMementos.removeAt(index);
4510 } else {
4511 MotionMemento& memento = mMotionMementos.editItemAt(index);
4512 memento.setPointers(entry);
4513 }
4514 } else if (!entry->pointerCoords[0].isEmpty()) {
4515 addMotionMemento(entry, flags, false /*hovering*/);
4516 }
4517
4518 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4519 return true;
4520 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521 if (index >= 0) {
4522 MotionMemento& memento = mMotionMementos.editItemAt(index);
4523 memento.setPointers(entry);
4524 return true;
4525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526#if DEBUG_OUTBOUND_EVENT_DETAILS
4527 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004528 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4529 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004530#endif
4531 return false;
4532 }
4533
4534 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4535 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4536 if (index >= 0) {
4537 mMotionMementos.removeAt(index);
4538 return true;
4539 }
4540#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004541 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4542 "displayId=%" PRId32,
4543 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544#endif
4545 return false;
4546 }
4547
4548 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4549 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4550 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4551 if (index >= 0) {
4552 mMotionMementos.removeAt(index);
4553 }
4554 addMotionMemento(entry, flags, true /*hovering*/);
4555 return true;
4556 }
4557
4558 default:
4559 return true;
4560 }
4561}
4562
4563ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4564 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4565 const KeyMemento& memento = mKeyMementos.itemAt(i);
4566 if (memento.deviceId == entry->deviceId
4567 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004568 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 && memento.keyCode == entry->keyCode
4570 && memento.scanCode == entry->scanCode) {
4571 return i;
4572 }
4573 }
4574 return -1;
4575}
4576
4577ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4578 bool hovering) const {
4579 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4580 const MotionMemento& memento = mMotionMementos.itemAt(i);
4581 if (memento.deviceId == entry->deviceId
4582 && memento.source == entry->source
4583 && memento.displayId == entry->displayId
4584 && memento.hovering == hovering) {
4585 return i;
4586 }
4587 }
4588 return -1;
4589}
4590
4591void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4592 mKeyMementos.push();
4593 KeyMemento& memento = mKeyMementos.editTop();
4594 memento.deviceId = entry->deviceId;
4595 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004596 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 memento.keyCode = entry->keyCode;
4598 memento.scanCode = entry->scanCode;
4599 memento.metaState = entry->metaState;
4600 memento.flags = flags;
4601 memento.downTime = entry->downTime;
4602 memento.policyFlags = entry->policyFlags;
4603}
4604
4605void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4606 int32_t flags, bool hovering) {
4607 mMotionMementos.push();
4608 MotionMemento& memento = mMotionMementos.editTop();
4609 memento.deviceId = entry->deviceId;
4610 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004611 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612 memento.flags = flags;
4613 memento.xPrecision = entry->xPrecision;
4614 memento.yPrecision = entry->yPrecision;
4615 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616 memento.setPointers(entry);
4617 memento.hovering = hovering;
4618 memento.policyFlags = entry->policyFlags;
4619}
4620
4621void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4622 pointerCount = entry->pointerCount;
4623 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4624 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4625 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4626 }
4627}
4628
4629void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4630 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4631 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4632 const KeyMemento& memento = mKeyMementos.itemAt(i);
4633 if (shouldCancelKey(memento, options)) {
4634 outEvents.push(new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004635 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4637 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4638 }
4639 }
4640
4641 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4642 const MotionMemento& memento = mMotionMementos.itemAt(i);
4643 if (shouldCancelMotion(memento, options)) {
4644 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004645 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646 memento.hovering
4647 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4648 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004649 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004651 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4652 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 }
4654 }
4655}
4656
4657void InputDispatcher::InputState::clear() {
4658 mKeyMementos.clear();
4659 mMotionMementos.clear();
4660 mFallbackKeys.clear();
4661}
4662
4663void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4664 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4665 const MotionMemento& memento = mMotionMementos.itemAt(i);
4666 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4667 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4668 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4669 if (memento.deviceId == otherMemento.deviceId
4670 && memento.source == otherMemento.source
4671 && memento.displayId == otherMemento.displayId) {
4672 other.mMotionMementos.removeAt(j);
4673 } else {
4674 j += 1;
4675 }
4676 }
4677 other.mMotionMementos.push(memento);
4678 }
4679 }
4680}
4681
4682int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4683 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4684 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4685}
4686
4687void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4688 int32_t fallbackKeyCode) {
4689 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4690 if (index >= 0) {
4691 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4692 } else {
4693 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4694 }
4695}
4696
4697void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4698 mFallbackKeys.removeItem(originalKeyCode);
4699}
4700
4701bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4702 const CancelationOptions& options) {
4703 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4704 return false;
4705 }
4706
4707 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4708 return false;
4709 }
4710
4711 switch (options.mode) {
4712 case CancelationOptions::CANCEL_ALL_EVENTS:
4713 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4714 return true;
4715 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4716 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004717 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4718 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 default:
4720 return false;
4721 }
4722}
4723
4724bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4725 const CancelationOptions& options) {
4726 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4727 return false;
4728 }
4729
4730 switch (options.mode) {
4731 case CancelationOptions::CANCEL_ALL_EVENTS:
4732 return true;
4733 case CancelationOptions::CANCEL_POINTER_EVENTS:
4734 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4735 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4736 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004737 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4738 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 default:
4740 return false;
4741 }
4742}
4743
4744
4745// --- InputDispatcher::Connection ---
4746
Robert Carr803535b2018-08-02 16:38:15 -07004747InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4748 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749 monitor(monitor),
4750 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4751}
4752
4753InputDispatcher::Connection::~Connection() {
4754}
4755
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004756const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004757 if (inputChannel != nullptr) {
4758 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759 }
4760 if (monitor) {
4761 return "monitor";
4762 }
4763 return "?";
4764}
4765
4766const char* InputDispatcher::Connection::getStatusLabel() const {
4767 switch (status) {
4768 case STATUS_NORMAL:
4769 return "NORMAL";
4770
4771 case STATUS_BROKEN:
4772 return "BROKEN";
4773
4774 case STATUS_ZOMBIE:
4775 return "ZOMBIE";
4776
4777 default:
4778 return "UNKNOWN";
4779 }
4780}
4781
4782InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004783 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 if (entry->seq == seq) {
4785 return entry;
4786 }
4787 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004788 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789}
4790
4791
4792// --- InputDispatcher::CommandEntry ---
4793
4794InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004795 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796 seq(0), handled(false) {
4797}
4798
4799InputDispatcher::CommandEntry::~CommandEntry() {
4800}
4801
4802
4803// --- InputDispatcher::TouchState ---
4804
4805InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004806 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807}
4808
4809InputDispatcher::TouchState::~TouchState() {
4810}
4811
4812void InputDispatcher::TouchState::reset() {
4813 down = false;
4814 split = false;
4815 deviceId = -1;
4816 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004817 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 windows.clear();
4819}
4820
4821void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4822 down = other.down;
4823 split = other.split;
4824 deviceId = other.deviceId;
4825 source = other.source;
4826 displayId = other.displayId;
4827 windows = other.windows;
4828}
4829
4830void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4831 int32_t targetFlags, BitSet32 pointerIds) {
4832 if (targetFlags & InputTarget::FLAG_SPLIT) {
4833 split = true;
4834 }
4835
4836 for (size_t i = 0; i < windows.size(); i++) {
4837 TouchedWindow& touchedWindow = windows.editItemAt(i);
4838 if (touchedWindow.windowHandle == windowHandle) {
4839 touchedWindow.targetFlags |= targetFlags;
4840 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4841 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4842 }
4843 touchedWindow.pointerIds.value |= pointerIds.value;
4844 return;
4845 }
4846 }
4847
4848 windows.push();
4849
4850 TouchedWindow& touchedWindow = windows.editTop();
4851 touchedWindow.windowHandle = windowHandle;
4852 touchedWindow.targetFlags = targetFlags;
4853 touchedWindow.pointerIds = pointerIds;
4854}
4855
4856void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4857 for (size_t i = 0; i < windows.size(); i++) {
4858 if (windows.itemAt(i).windowHandle == windowHandle) {
4859 windows.removeAt(i);
4860 return;
4861 }
4862 }
4863}
4864
Robert Carr803535b2018-08-02 16:38:15 -07004865void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4866 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004867 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004868 windows.removeAt(i);
4869 return;
4870 }
4871 }
4872}
4873
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4875 for (size_t i = 0 ; i < windows.size(); ) {
4876 TouchedWindow& window = windows.editItemAt(i);
4877 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4878 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4879 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4880 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4881 i += 1;
4882 } else {
4883 windows.removeAt(i);
4884 }
4885 }
4886}
4887
4888sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4889 for (size_t i = 0; i < windows.size(); i++) {
4890 const TouchedWindow& window = windows.itemAt(i);
4891 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4892 return window.windowHandle;
4893 }
4894 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004895 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896}
4897
4898bool InputDispatcher::TouchState::isSlippery() const {
4899 // Must have exactly one foreground window.
4900 bool haveSlipperyForegroundWindow = false;
4901 for (size_t i = 0; i < windows.size(); i++) {
4902 const TouchedWindow& window = windows.itemAt(i);
4903 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4904 if (haveSlipperyForegroundWindow
4905 || !(window.windowHandle->getInfo()->layoutParamsFlags
4906 & InputWindowInfo::FLAG_SLIPPERY)) {
4907 return false;
4908 }
4909 haveSlipperyForegroundWindow = true;
4910 }
4911 }
4912 return haveSlipperyForegroundWindow;
4913}
4914
4915
4916// --- InputDispatcherThread ---
4917
4918InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4919 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4920}
4921
4922InputDispatcherThread::~InputDispatcherThread() {
4923}
4924
4925bool InputDispatcherThread::threadLoop() {
4926 mDispatcher->dispatchOnce();
4927 return true;
4928}
4929
4930} // namespace android