blob: 49aac72e28ed46036c4ae37a10d1b8cafe91eb05 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
20//#define LOG_NDEBUG 0
21
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
38#define DEBUG_FOCUS 0
39
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wrightd02c5b62014-02-10 15:10:22 -080048#include <errno.h>
49#include <limits.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080050#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070051#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070053#include <unistd.h>
54
Michael Wright2b3c3302018-03-02 17:19:13 +000055#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080056#include <android-base/stringprintf.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070057#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <utils/Trace.h>
59#include <powermanager/PowerManager.h>
60#include <ui/Region.h>
Robert Carr4e670e52018-08-15 13:26:12 -070061#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080062
63#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66#define INDENT4 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
72// Default input dispatching timeout if there is no focused application or paused window
73// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000074constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
76// Amount of time to allow for all pending events to be processed when an app switch
77// key is on the way. This is used to preempt input dispatch and drop input events
78// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000079constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080080
81// Amount of time to allow for an event to be dispatched (measured since its eventTime)
82// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000083constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow touch events to be streamed out to a connection before requiring
86// that the first event be finished. This value extends the ANR timeout by the specified
87// amount. For example, if streaming is allowed to get ahead by one second relative to the
88// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000089constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
91// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
93
94// Log a warning when an interception call takes longer than this to process.
95constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
97// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
99
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100
101static inline nsecs_t now() {
102 return systemTime(SYSTEM_TIME_MONOTONIC);
103}
104
105static inline const char* toString(bool value) {
106 return value ? "true" : "false";
107}
108
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800109static std::string motionActionToString(int32_t action) {
110 // Convert MotionEvent action to string
111 switch(action & AMOTION_EVENT_ACTION_MASK) {
112 case AMOTION_EVENT_ACTION_DOWN:
113 return "DOWN";
114 case AMOTION_EVENT_ACTION_MOVE:
115 return "MOVE";
116 case AMOTION_EVENT_ACTION_UP:
117 return "UP";
118 case AMOTION_EVENT_ACTION_POINTER_DOWN:
119 return "POINTER_DOWN";
120 case AMOTION_EVENT_ACTION_POINTER_UP:
121 return "POINTER_UP";
122 }
123 return StringPrintf("%" PRId32, action);
124}
125
126static std::string keyActionToString(int32_t action) {
127 // Convert KeyEvent action to string
128 switch(action) {
129 case AKEY_EVENT_ACTION_DOWN:
130 return "DOWN";
131 case AKEY_EVENT_ACTION_UP:
132 return "UP";
133 case AKEY_EVENT_ACTION_MULTIPLE:
134 return "MULTIPLE";
135 }
136 return StringPrintf("%" PRId32, action);
137}
138
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
140 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
141 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
142}
143
144static bool isValidKeyAction(int32_t action) {
145 switch (action) {
146 case AKEY_EVENT_ACTION_DOWN:
147 case AKEY_EVENT_ACTION_UP:
148 return true;
149 default:
150 return false;
151 }
152}
153
154static bool validateKeyEvent(int32_t action) {
155 if (! isValidKeyAction(action)) {
156 ALOGE("Key event has invalid action code 0x%x", action);
157 return false;
158 }
159 return true;
160}
161
Michael Wright7b159c92015-05-14 14:48:03 +0100162static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800163 switch (action & AMOTION_EVENT_ACTION_MASK) {
164 case AMOTION_EVENT_ACTION_DOWN:
165 case AMOTION_EVENT_ACTION_UP:
166 case AMOTION_EVENT_ACTION_CANCEL:
167 case AMOTION_EVENT_ACTION_MOVE:
168 case AMOTION_EVENT_ACTION_OUTSIDE:
169 case AMOTION_EVENT_ACTION_HOVER_ENTER:
170 case AMOTION_EVENT_ACTION_HOVER_MOVE:
171 case AMOTION_EVENT_ACTION_HOVER_EXIT:
172 case AMOTION_EVENT_ACTION_SCROLL:
173 return true;
174 case AMOTION_EVENT_ACTION_POINTER_DOWN:
175 case AMOTION_EVENT_ACTION_POINTER_UP: {
176 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800177 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800178 }
Michael Wright7b159c92015-05-14 14:48:03 +0100179 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
180 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
181 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800182 default:
183 return false;
184 }
185}
186
Michael Wright7b159c92015-05-14 14:48:03 +0100187static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800188 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100189 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190 ALOGE("Motion event has invalid action code 0x%x", action);
191 return false;
192 }
193 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000194 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 pointerCount, MAX_POINTERS);
196 return false;
197 }
198 BitSet32 pointerIdBits;
199 for (size_t i = 0; i < pointerCount; i++) {
200 int32_t id = pointerProperties[i].id;
201 if (id < 0 || id > MAX_POINTER_ID) {
202 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
203 id, MAX_POINTER_ID);
204 return false;
205 }
206 if (pointerIdBits.hasBit(id)) {
207 ALOGE("Motion event has duplicate pointer id %d", id);
208 return false;
209 }
210 pointerIdBits.markBit(id);
211 }
212 return true;
213}
214
215static bool isMainDisplay(int32_t displayId) {
216 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
217}
218
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800219static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800221 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 return;
223 }
224
225 bool first = true;
226 Region::const_iterator cur = region.begin();
227 Region::const_iterator const tail = region.end();
228 while (cur != tail) {
229 if (first) {
230 first = false;
231 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800232 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800234 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800235 cur++;
236 }
237}
238
Tiger Huang721e26f2018-07-24 22:26:19 +0800239template<typename T, typename U>
240static T getValueByKey(std::unordered_map<U, T>& map, U key) {
241 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
242 return it != map.end() ? it->second : T{};
243}
244
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245
246// --- InputDispatcher ---
247
248InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
249 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700250 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100251 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700252 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800254 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
256 mLooper = new Looper(false);
257
Yi Kong9b14ac62018-07-17 13:48:38 -0700258 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259
260 policy->getDispatcherConfiguration(&mConfig);
261}
262
263InputDispatcher::~InputDispatcher() {
264 { // acquire lock
265 AutoMutex _l(mLock);
266
267 resetKeyRepeatLocked();
268 releasePendingEventLocked();
269 drainInboundQueueLocked();
270 }
271
272 while (mConnectionsByFd.size() != 0) {
273 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
274 }
275}
276
277void InputDispatcher::dispatchOnce() {
278 nsecs_t nextWakeupTime = LONG_LONG_MAX;
279 { // acquire lock
280 AutoMutex _l(mLock);
281 mDispatcherIsAliveCondition.broadcast();
282
283 // Run a dispatch loop if there are no pending commands.
284 // The dispatch loop might enqueue commands to run afterwards.
285 if (!haveCommandsLocked()) {
286 dispatchOnceInnerLocked(&nextWakeupTime);
287 }
288
289 // Run all pending commands if there are any.
290 // If any commands were run then force the next poll to wake up immediately.
291 if (runCommandsLockedInterruptible()) {
292 nextWakeupTime = LONG_LONG_MIN;
293 }
294 } // release lock
295
296 // Wait for callback or timeout or wake. (make sure we round up, not down)
297 nsecs_t currentTime = now();
298 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
299 mLooper->pollOnce(timeoutMillis);
300}
301
302void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
303 nsecs_t currentTime = now();
304
Jeff Browndc5992e2014-04-11 01:27:26 -0700305 // Reset the key repeat timer whenever normal dispatch is suspended while the
306 // device is in a non-interactive state. This is to ensure that we abort a key
307 // repeat if the device is just coming out of sleep.
308 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800309 resetKeyRepeatLocked();
310 }
311
312 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
313 if (mDispatchFrozen) {
314#if DEBUG_FOCUS
315 ALOGD("Dispatch frozen. Waiting some more.");
316#endif
317 return;
318 }
319
320 // Optimize latency of app switches.
321 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
322 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
323 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
324 if (mAppSwitchDueTime < *nextWakeupTime) {
325 *nextWakeupTime = mAppSwitchDueTime;
326 }
327
328 // Ready to start a new event.
329 // If we don't already have a pending event, go grab one.
330 if (! mPendingEvent) {
331 if (mInboundQueue.isEmpty()) {
332 if (isAppSwitchDue) {
333 // The inbound queue is empty so the app switch key we were waiting
334 // for will never arrive. Stop waiting for it.
335 resetPendingAppSwitchLocked(false);
336 isAppSwitchDue = false;
337 }
338
339 // Synthesize a key repeat if appropriate.
340 if (mKeyRepeatState.lastKeyEntry) {
341 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
342 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
343 } else {
344 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
345 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
346 }
347 }
348 }
349
350 // Nothing to do if there is no pending event.
351 if (!mPendingEvent) {
352 return;
353 }
354 } else {
355 // Inbound queue has at least one entry.
356 mPendingEvent = mInboundQueue.dequeueAtHead();
357 traceInboundQueueLengthLocked();
358 }
359
360 // Poke user activity for this event.
361 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
362 pokeUserActivityLocked(mPendingEvent);
363 }
364
365 // Get ready to dispatch the event.
366 resetANRTimeoutsLocked();
367 }
368
369 // Now we have an event to dispatch.
370 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700371 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372 bool done = false;
373 DropReason dropReason = DROP_REASON_NOT_DROPPED;
374 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
375 dropReason = DROP_REASON_POLICY;
376 } else if (!mDispatchEnabled) {
377 dropReason = DROP_REASON_DISABLED;
378 }
379
380 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700381 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800382 }
383
384 switch (mPendingEvent->type) {
385 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
386 ConfigurationChangedEntry* typedEntry =
387 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
388 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
389 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
390 break;
391 }
392
393 case EventEntry::TYPE_DEVICE_RESET: {
394 DeviceResetEntry* typedEntry =
395 static_cast<DeviceResetEntry*>(mPendingEvent);
396 done = dispatchDeviceResetLocked(currentTime, typedEntry);
397 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
398 break;
399 }
400
401 case EventEntry::TYPE_KEY: {
402 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
403 if (isAppSwitchDue) {
404 if (isAppSwitchKeyEventLocked(typedEntry)) {
405 resetPendingAppSwitchLocked(true);
406 isAppSwitchDue = false;
407 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
408 dropReason = DROP_REASON_APP_SWITCH;
409 }
410 }
411 if (dropReason == DROP_REASON_NOT_DROPPED
412 && isStaleEventLocked(currentTime, typedEntry)) {
413 dropReason = DROP_REASON_STALE;
414 }
415 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
416 dropReason = DROP_REASON_BLOCKED;
417 }
418 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
419 break;
420 }
421
422 case EventEntry::TYPE_MOTION: {
423 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
424 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
425 dropReason = DROP_REASON_APP_SWITCH;
426 }
427 if (dropReason == DROP_REASON_NOT_DROPPED
428 && isStaleEventLocked(currentTime, typedEntry)) {
429 dropReason = DROP_REASON_STALE;
430 }
431 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
432 dropReason = DROP_REASON_BLOCKED;
433 }
434 done = dispatchMotionLocked(currentTime, typedEntry,
435 &dropReason, nextWakeupTime);
436 break;
437 }
438
439 default:
440 ALOG_ASSERT(false);
441 break;
442 }
443
444 if (done) {
445 if (dropReason != DROP_REASON_NOT_DROPPED) {
446 dropInboundEventLocked(mPendingEvent, dropReason);
447 }
Michael Wright3a981722015-06-10 15:26:13 +0100448 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449
450 releasePendingEventLocked();
451 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
452 }
453}
454
455bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
456 bool needWake = mInboundQueue.isEmpty();
457 mInboundQueue.enqueueAtTail(entry);
458 traceInboundQueueLengthLocked();
459
460 switch (entry->type) {
461 case EventEntry::TYPE_KEY: {
462 // Optimize app switch latency.
463 // If the application takes too long to catch up then we drop all events preceding
464 // the app switch key.
465 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
466 if (isAppSwitchKeyEventLocked(keyEntry)) {
467 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
468 mAppSwitchSawKeyDown = true;
469 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
470 if (mAppSwitchSawKeyDown) {
471#if DEBUG_APP_SWITCH
472 ALOGD("App switch is pending!");
473#endif
474 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
475 mAppSwitchSawKeyDown = false;
476 needWake = true;
477 }
478 }
479 }
480 break;
481 }
482
483 case EventEntry::TYPE_MOTION: {
484 // Optimize case where the current application is unresponsive and the user
485 // decides to touch a window in a different application.
486 // If the application takes too long to catch up then we drop all events preceding
487 // the touch into the other window.
488 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
489 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
490 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
491 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Robert Carr740167f2018-10-11 19:03:41 -0700492 && mInputTargetWaitApplicationToken != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 int32_t displayId = motionEntry->displayId;
494 int32_t x = int32_t(motionEntry->pointerCoords[0].
495 getAxisValue(AMOTION_EVENT_AXIS_X));
496 int32_t y = int32_t(motionEntry->pointerCoords[0].
497 getAxisValue(AMOTION_EVENT_AXIS_Y));
498 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700499 if (touchedWindowHandle != nullptr
Robert Carr740167f2018-10-11 19:03:41 -0700500 && touchedWindowHandle->getApplicationToken()
501 != mInputTargetWaitApplicationToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 // User touched a different application than the one we are waiting on.
503 // Flag the event, and start pruning the input queue.
504 mNextUnblockedEvent = motionEntry;
505 needWake = true;
506 }
507 }
508 break;
509 }
510 }
511
512 return needWake;
513}
514
515void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
516 entry->refCount += 1;
517 mRecentQueue.enqueueAtTail(entry);
518 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
519 mRecentQueue.dequeueAtHead()->release();
520 }
521}
522
523sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
524 int32_t x, int32_t y) {
525 // Traverse windows from front to back to find touched window.
Arthur Hungb92218b2018-08-14 12:00:21 +0800526 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
527 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800529 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 const InputWindowInfo* windowInfo = windowHandle->getInfo();
531 if (windowInfo->displayId == displayId) {
532 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533
534 if (windowInfo->visible) {
535 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
536 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
537 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
538 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
539 // Found window.
540 return windowHandle;
541 }
542 }
543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 }
545 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700546 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547}
548
549void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
550 const char* reason;
551 switch (dropReason) {
552 case DROP_REASON_POLICY:
553#if DEBUG_INBOUND_EVENT_DETAILS
554 ALOGD("Dropped event because policy consumed it.");
555#endif
556 reason = "inbound event was dropped because the policy consumed it";
557 break;
558 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100559 if (mLastDropReason != DROP_REASON_DISABLED) {
560 ALOGI("Dropped event because input dispatch is disabled.");
561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 reason = "inbound event was dropped because input dispatch is disabled";
563 break;
564 case DROP_REASON_APP_SWITCH:
565 ALOGI("Dropped event because of pending overdue app switch.");
566 reason = "inbound event was dropped because of pending overdue app switch";
567 break;
568 case DROP_REASON_BLOCKED:
569 ALOGI("Dropped event because the current application is not responding and the user "
570 "has started interacting with a different application.");
571 reason = "inbound event was dropped because the current application is not responding "
572 "and the user has started interacting with a different application";
573 break;
574 case DROP_REASON_STALE:
575 ALOGI("Dropped event because it is stale.");
576 reason = "inbound event was dropped because it is stale";
577 break;
578 default:
579 ALOG_ASSERT(false);
580 return;
581 }
582
583 switch (entry->type) {
584 case EventEntry::TYPE_KEY: {
585 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
586 synthesizeCancelationEventsForAllConnectionsLocked(options);
587 break;
588 }
589 case EventEntry::TYPE_MOTION: {
590 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
591 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
592 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
593 synthesizeCancelationEventsForAllConnectionsLocked(options);
594 } else {
595 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
596 synthesizeCancelationEventsForAllConnectionsLocked(options);
597 }
598 break;
599 }
600 }
601}
602
603bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
604 return keyCode == AKEYCODE_HOME
605 || keyCode == AKEYCODE_ENDCALL
606 || keyCode == AKEYCODE_APP_SWITCH;
607}
608
609bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
610 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
611 && isAppSwitchKeyCode(keyEntry->keyCode)
612 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
613 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
614}
615
616bool InputDispatcher::isAppSwitchPendingLocked() {
617 return mAppSwitchDueTime != LONG_LONG_MAX;
618}
619
620void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
621 mAppSwitchDueTime = LONG_LONG_MAX;
622
623#if DEBUG_APP_SWITCH
624 if (handled) {
625 ALOGD("App switch has arrived.");
626 } else {
627 ALOGD("App switch was abandoned.");
628 }
629#endif
630}
631
632bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
633 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
634}
635
636bool InputDispatcher::haveCommandsLocked() const {
637 return !mCommandQueue.isEmpty();
638}
639
640bool InputDispatcher::runCommandsLockedInterruptible() {
641 if (mCommandQueue.isEmpty()) {
642 return false;
643 }
644
645 do {
646 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
647
648 Command command = commandEntry->command;
649 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
650
651 commandEntry->connection.clear();
652 delete commandEntry;
653 } while (! mCommandQueue.isEmpty());
654 return true;
655}
656
657InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
658 CommandEntry* commandEntry = new CommandEntry(command);
659 mCommandQueue.enqueueAtTail(commandEntry);
660 return commandEntry;
661}
662
663void InputDispatcher::drainInboundQueueLocked() {
664 while (! mInboundQueue.isEmpty()) {
665 EventEntry* entry = mInboundQueue.dequeueAtHead();
666 releaseInboundEventLocked(entry);
667 }
668 traceInboundQueueLengthLocked();
669}
670
671void InputDispatcher::releasePendingEventLocked() {
672 if (mPendingEvent) {
673 resetANRTimeoutsLocked();
674 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700675 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 }
677}
678
679void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
680 InjectionState* injectionState = entry->injectionState;
681 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
682#if DEBUG_DISPATCH_CYCLE
683 ALOGD("Injected inbound event was dropped.");
684#endif
685 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
686 }
687 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700688 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 }
690 addRecentEventLocked(entry);
691 entry->release();
692}
693
694void InputDispatcher::resetKeyRepeatLocked() {
695 if (mKeyRepeatState.lastKeyEntry) {
696 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700697 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
699}
700
701InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
702 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
703
704 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700705 uint32_t policyFlags = entry->policyFlags &
706 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 if (entry->refCount == 1) {
708 entry->recycle();
709 entry->eventTime = currentTime;
710 entry->policyFlags = policyFlags;
711 entry->repeatCount += 1;
712 } else {
713 KeyEntry* newEntry = new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100714 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 entry->action, entry->flags, entry->keyCode, entry->scanCode,
716 entry->metaState, entry->repeatCount + 1, entry->downTime);
717
718 mKeyRepeatState.lastKeyEntry = newEntry;
719 entry->release();
720
721 entry = newEntry;
722 }
723 entry->syntheticRepeat = true;
724
725 // Increment reference count since we keep a reference to the event in
726 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
727 entry->refCount += 1;
728
729 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
730 return entry;
731}
732
733bool InputDispatcher::dispatchConfigurationChangedLocked(
734 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
735#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700736 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737#endif
738
739 // Reset key repeating in case a keyboard device was added or removed or something.
740 resetKeyRepeatLocked();
741
742 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
743 CommandEntry* commandEntry = postCommandLocked(
744 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
745 commandEntry->eventTime = entry->eventTime;
746 return true;
747}
748
749bool InputDispatcher::dispatchDeviceResetLocked(
750 nsecs_t currentTime, DeviceResetEntry* entry) {
751#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700752 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
753 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754#endif
755
756 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
757 "device was reset");
758 options.deviceId = entry->deviceId;
759 synthesizeCancelationEventsForAllConnectionsLocked(options);
760 return true;
761}
762
763bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
764 DropReason* dropReason, nsecs_t* nextWakeupTime) {
765 // Preprocessing.
766 if (! entry->dispatchInProgress) {
767 if (entry->repeatCount == 0
768 && entry->action == AKEY_EVENT_ACTION_DOWN
769 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
770 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
771 if (mKeyRepeatState.lastKeyEntry
772 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
773 // We have seen two identical key downs in a row which indicates that the device
774 // driver is automatically generating key repeats itself. We take note of the
775 // repeat here, but we disable our own next key repeat timer since it is clear that
776 // we will not need to synthesize key repeats ourselves.
777 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
778 resetKeyRepeatLocked();
779 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
780 } else {
781 // Not a repeat. Save key down state in case we do see a repeat later.
782 resetKeyRepeatLocked();
783 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
784 }
785 mKeyRepeatState.lastKeyEntry = entry;
786 entry->refCount += 1;
787 } else if (! entry->syntheticRepeat) {
788 resetKeyRepeatLocked();
789 }
790
791 if (entry->repeatCount == 1) {
792 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
793 } else {
794 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
795 }
796
797 entry->dispatchInProgress = true;
798
799 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
800 }
801
802 // Handle case where the policy asked us to try again later last time.
803 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
804 if (currentTime < entry->interceptKeyWakeupTime) {
805 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
806 *nextWakeupTime = entry->interceptKeyWakeupTime;
807 }
808 return false; // wait until next wakeup
809 }
810 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
811 entry->interceptKeyWakeupTime = 0;
812 }
813
814 // Give the policy a chance to intercept the key.
815 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
816 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
817 CommandEntry* commandEntry = postCommandLocked(
818 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800819 sp<InputWindowHandle> focusedWindowHandle =
820 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
821 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700822 commandEntry->inputChannel =
823 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 }
825 commandEntry->keyEntry = entry;
826 entry->refCount += 1;
827 return false; // wait for the command to run
828 } else {
829 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
830 }
831 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
832 if (*dropReason == DROP_REASON_NOT_DROPPED) {
833 *dropReason = DROP_REASON_POLICY;
834 }
835 }
836
837 // Clean up if dropping the event.
838 if (*dropReason != DROP_REASON_NOT_DROPPED) {
839 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
840 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
841 return true;
842 }
843
844 // Identify targets.
845 Vector<InputTarget> inputTargets;
846 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
847 entry, inputTargets, nextWakeupTime);
848 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
849 return false;
850 }
851
852 setInjectionResultLocked(entry, injectionResult);
853 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
854 return true;
855 }
856
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800857 // Add monitor channels from event's or focused display.
858 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859
860 // Dispatch the key.
861 dispatchEventLocked(currentTime, entry, inputTargets);
862 return true;
863}
864
865void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
866#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100867 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
868 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800869 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100871 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800873 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874#endif
875}
876
877bool InputDispatcher::dispatchMotionLocked(
878 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
879 // Preprocessing.
880 if (! entry->dispatchInProgress) {
881 entry->dispatchInProgress = true;
882
883 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
884 }
885
886 // Clean up if dropping the event.
887 if (*dropReason != DROP_REASON_NOT_DROPPED) {
888 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
889 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
890 return true;
891 }
892
893 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
894
895 // Identify targets.
896 Vector<InputTarget> inputTargets;
897
898 bool conflictingPointerActions = false;
899 int32_t injectionResult;
900 if (isPointerEvent) {
901 // Pointer event. (eg. touchscreen)
902 injectionResult = findTouchedWindowTargetsLocked(currentTime,
903 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
904 } else {
905 // Non touch event. (eg. trackball)
906 injectionResult = findFocusedWindowTargetsLocked(currentTime,
907 entry, inputTargets, nextWakeupTime);
908 }
909 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
910 return false;
911 }
912
913 setInjectionResultLocked(entry, injectionResult);
914 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100915 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
916 CancelationOptions::Mode mode(isPointerEvent ?
917 CancelationOptions::CANCEL_POINTER_EVENTS :
918 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
919 CancelationOptions options(mode, "input event injection failed");
920 synthesizeCancelationEventsForMonitorsLocked(options);
921 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 return true;
923 }
924
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800925 // Add monitor channels from event's or focused display.
926 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927
928 // Dispatch the motion.
929 if (conflictingPointerActions) {
930 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
931 "conflicting pointer actions");
932 synthesizeCancelationEventsForAllConnectionsLocked(options);
933 }
934 dispatchEventLocked(currentTime, entry, inputTargets);
935 return true;
936}
937
938
939void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
940#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800941 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
942 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100943 "action=0x%x, actionButton=0x%x, flags=0x%x, "
944 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800945 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800947 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100948 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 entry->metaState, entry->buttonState,
950 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800951 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952
953 for (uint32_t i = 0; i < entry->pointerCount; i++) {
954 ALOGD(" Pointer %d: id=%d, toolType=%d, "
955 "x=%f, y=%f, pressure=%f, size=%f, "
956 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800957 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958 i, entry->pointerProperties[i].id,
959 entry->pointerProperties[i].toolType,
960 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
961 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
962 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
963 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
964 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
965 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
966 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
967 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800968 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 }
970#endif
971}
972
973void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
974 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
975#if DEBUG_DISPATCH_CYCLE
976 ALOGD("dispatchEventToCurrentInputTargets");
977#endif
978
979 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
980
981 pokeUserActivityLocked(eventEntry);
982
983 for (size_t i = 0; i < inputTargets.size(); i++) {
984 const InputTarget& inputTarget = inputTargets.itemAt(i);
985
986 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
987 if (connectionIndex >= 0) {
988 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
989 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
990 } else {
991#if DEBUG_FOCUS
992 ALOGD("Dropping event delivery to target with channel '%s' because it "
993 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800994 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995#endif
996 }
997 }
998}
999
1000int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1001 const EventEntry* entry,
1002 const sp<InputApplicationHandle>& applicationHandle,
1003 const sp<InputWindowHandle>& windowHandle,
1004 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001005 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1007#if DEBUG_FOCUS
1008 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1009#endif
1010 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1011 mInputTargetWaitStartTime = currentTime;
1012 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1013 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001014 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 }
1016 } else {
1017 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1018#if DEBUG_FOCUS
1019 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001020 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 reason);
1022#endif
1023 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001024 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001026 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027 timeout = applicationHandle->getDispatchingTimeout(
1028 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1029 } else {
1030 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1031 }
1032
1033 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1034 mInputTargetWaitStartTime = currentTime;
1035 mInputTargetWaitTimeoutTime = currentTime + timeout;
1036 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001037 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038
Yi Kong9b14ac62018-07-17 13:48:38 -07001039 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001040 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 }
Robert Carr740167f2018-10-11 19:03:41 -07001042 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1043 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 }
1045 }
1046 }
1047
1048 if (mInputTargetWaitTimeoutExpired) {
1049 return INPUT_EVENT_INJECTION_TIMED_OUT;
1050 }
1051
1052 if (currentTime >= mInputTargetWaitTimeoutTime) {
1053 onANRLocked(currentTime, applicationHandle, windowHandle,
1054 entry->eventTime, mInputTargetWaitStartTime, reason);
1055
1056 // Force poll loop to wake up immediately on next iteration once we get the
1057 // ANR response back from the policy.
1058 *nextWakeupTime = LONG_LONG_MIN;
1059 return INPUT_EVENT_INJECTION_PENDING;
1060 } else {
1061 // Force poll loop to wake up when timeout is due.
1062 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1063 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1064 }
1065 return INPUT_EVENT_INJECTION_PENDING;
1066 }
1067}
1068
Robert Carr803535b2018-08-02 16:38:15 -07001069void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1070 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1071 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1072 state.removeWindowByToken(token);
1073 }
1074}
1075
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1077 const sp<InputChannel>& inputChannel) {
1078 if (newTimeout > 0) {
1079 // Extend the timeout.
1080 mInputTargetWaitTimeoutTime = now() + newTimeout;
1081 } else {
1082 // Give up.
1083 mInputTargetWaitTimeoutExpired = true;
1084
1085 // Input state will not be realistic. Mark it out of sync.
1086 if (inputChannel.get()) {
1087 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1088 if (connectionIndex >= 0) {
1089 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001090 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001091
Robert Carr803535b2018-08-02 16:38:15 -07001092 if (token != nullptr) {
1093 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 }
1095
1096 if (connection->status == Connection::STATUS_NORMAL) {
1097 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1098 "application not responding");
1099 synthesizeCancelationEventsForConnectionLocked(connection, options);
1100 }
1101 }
1102 }
1103 }
1104}
1105
1106nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1107 nsecs_t currentTime) {
1108 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1109 return currentTime - mInputTargetWaitStartTime;
1110 }
1111 return 0;
1112}
1113
1114void InputDispatcher::resetANRTimeoutsLocked() {
1115#if DEBUG_FOCUS
1116 ALOGD("Resetting ANR timeouts.");
1117#endif
1118
1119 // Reset input target wait timeout.
1120 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001121 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122}
1123
Tiger Huang721e26f2018-07-24 22:26:19 +08001124/**
1125 * Get the display id that the given event should go to. If this event specifies a valid display id,
1126 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1127 * Focused display is the display that the user most recently interacted with.
1128 */
1129int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1130 int32_t displayId;
1131 switch (entry->type) {
1132 case EventEntry::TYPE_KEY: {
1133 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1134 displayId = typedEntry->displayId;
1135 break;
1136 }
1137 case EventEntry::TYPE_MOTION: {
1138 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1139 displayId = typedEntry->displayId;
1140 break;
1141 }
1142 default: {
1143 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1144 return ADISPLAY_ID_NONE;
1145 }
1146 }
1147 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1148}
1149
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1151 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1152 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001153 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154
Tiger Huang721e26f2018-07-24 22:26:19 +08001155 int32_t displayId = getTargetDisplayId(entry);
1156 sp<InputWindowHandle> focusedWindowHandle =
1157 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1158 sp<InputApplicationHandle> focusedApplicationHandle =
1159 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1160
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 // If there is no currently focused window and no focused application
1162 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001163 if (focusedWindowHandle == nullptr) {
1164 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001166 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 "Waiting because no window has focus but there is a "
1168 "focused application that may eventually add a window "
1169 "when it finishes starting up.");
1170 goto Unresponsive;
1171 }
1172
Arthur Hung3b413f22018-10-26 18:05:34 +08001173 ALOGI("Dropping event because there is no focused window or focused application in display "
1174 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1176 goto Failed;
1177 }
1178
1179 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001180 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1182 goto Failed;
1183 }
1184
Jeff Brownffb49772014-10-10 19:01:34 -07001185 // Check whether the window is ready for more input.
1186 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001187 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001188 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001190 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 goto Unresponsive;
1192 }
1193
1194 // Success! Output targets.
1195 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001196 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1198 inputTargets);
1199
1200 // Done.
1201Failed:
1202Unresponsive:
1203 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1204 updateDispatchStatisticsLocked(currentTime, entry,
1205 injectionResult, timeSpentWaitingForApplication);
1206#if DEBUG_FOCUS
1207 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1208 "timeSpentWaitingForApplication=%0.1fms",
1209 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1210#endif
1211 return injectionResult;
1212}
1213
1214int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1215 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1216 bool* outConflictingPointerActions) {
1217 enum InjectionPermission {
1218 INJECTION_PERMISSION_UNKNOWN,
1219 INJECTION_PERMISSION_GRANTED,
1220 INJECTION_PERMISSION_DENIED
1221 };
1222
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 // For security reasons, we defer updating the touch state until we are sure that
1224 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 int32_t displayId = entry->displayId;
1226 int32_t action = entry->action;
1227 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1228
1229 // Update the touch state as needed based on the properties of the touch event.
1230 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1231 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1232 sp<InputWindowHandle> newHoverWindowHandle;
1233
Jeff Brownf086ddb2014-02-11 14:28:48 -08001234 // Copy current touch state into mTempTouchState.
1235 // This state is always reset at the end of this function, so if we don't find state
1236 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001237 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001238 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1239 if (oldStateIndex >= 0) {
1240 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1241 mTempTouchState.copyFrom(*oldState);
1242 }
1243
1244 bool isSplit = mTempTouchState.split;
1245 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1246 && (mTempTouchState.deviceId != entry->deviceId
1247 || mTempTouchState.source != entry->source
1248 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1250 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1251 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1252 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1253 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1254 || isHoverAction);
1255 bool wrongDevice = false;
1256 if (newGesture) {
1257 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001258 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001260 ALOGD("Dropping event because a pointer for a different device is already down "
1261 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001263 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1265 switchedDevice = false;
1266 wrongDevice = true;
1267 goto Failed;
1268 }
1269 mTempTouchState.reset();
1270 mTempTouchState.down = down;
1271 mTempTouchState.deviceId = entry->deviceId;
1272 mTempTouchState.source = entry->source;
1273 mTempTouchState.displayId = displayId;
1274 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001275 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1276#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001277 ALOGI("Dropping move event because a pointer for a different device is already active "
1278 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001279#endif
1280 // TODO: test multiple simultaneous input streams.
1281 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1282 switchedDevice = false;
1283 wrongDevice = true;
1284 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285 }
1286
1287 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1288 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1289
1290 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1291 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1292 getAxisValue(AMOTION_EVENT_AXIS_X));
1293 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1294 getAxisValue(AMOTION_EVENT_AXIS_Y));
1295 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 bool isTouchModal = false;
1297
1298 // Traverse windows from front to back to find touched window and outside targets.
Arthur Hungb92218b2018-08-14 12:00:21 +08001299 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1300 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001302 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1304 if (windowInfo->displayId != displayId) {
1305 continue; // wrong display
1306 }
1307
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 int32_t flags = windowInfo->layoutParamsFlags;
1309 if (windowInfo->visible) {
1310 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1311 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1312 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1313 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001314 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 break; // found touched window, exit window loop
1316 }
1317 }
1318
1319 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1320 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001322 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 }
1324 }
1325 }
1326
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001328 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1330 // New window supports splitting.
1331 isSplit = true;
1332 } else if (isSplit) {
1333 // New window does not support splitting but we have already split events.
1334 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001335 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001336 }
1337
1338 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001339 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001340 // Try to assign the pointer to the first foreground window we find, if there is one.
1341 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001342 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001343 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1344 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001345 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1346 goto Failed;
1347 }
1348 }
1349
1350 // Set target flags.
1351 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1352 if (isSplit) {
1353 targetFlags |= InputTarget::FLAG_SPLIT;
1354 }
1355 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1356 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001357 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1358 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 }
1360
1361 // Update hover state.
1362 if (isHoverAction) {
1363 newHoverWindowHandle = newTouchedWindowHandle;
1364 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1365 newHoverWindowHandle = mLastHoverWindowHandle;
1366 }
1367
1368 // Update the temporary touch state.
1369 BitSet32 pointerIds;
1370 if (isSplit) {
1371 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1372 pointerIds.markBit(pointerId);
1373 }
1374 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1375 } else {
1376 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1377
1378 // If the pointer is not currently down, then ignore the event.
1379 if (! mTempTouchState.down) {
1380#if DEBUG_FOCUS
1381 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001382 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383#endif
1384 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1385 goto Failed;
1386 }
1387
1388 // Check whether touches should slip outside of the current foreground window.
1389 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1390 && entry->pointerCount == 1
1391 && mTempTouchState.isSlippery()) {
1392 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1393 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1394
1395 sp<InputWindowHandle> oldTouchedWindowHandle =
1396 mTempTouchState.getFirstForegroundWindowHandle();
1397 sp<InputWindowHandle> newTouchedWindowHandle =
1398 findTouchedWindowAtLocked(displayId, x, y);
1399 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001400 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001401#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001402 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001403 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001404 newTouchedWindowHandle->getName().c_str(),
1405 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406#endif
1407 // Make a slippery exit from the old window.
1408 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1409 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1410
1411 // Make a slippery entrance into the new window.
1412 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1413 isSplit = true;
1414 }
1415
1416 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1417 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1418 if (isSplit) {
1419 targetFlags |= InputTarget::FLAG_SPLIT;
1420 }
1421 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1422 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1423 }
1424
1425 BitSet32 pointerIds;
1426 if (isSplit) {
1427 pointerIds.markBit(entry->pointerProperties[0].id);
1428 }
1429 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1430 }
1431 }
1432 }
1433
1434 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1435 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001436 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437#if DEBUG_HOVER
1438 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001439 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440#endif
1441 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1442 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1443 }
1444
1445 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001446 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447#if DEBUG_HOVER
1448 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001449 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450#endif
1451 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1452 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1453 }
1454 }
1455
1456 // Check permission to inject into all touched foreground windows and ensure there
1457 // is at least one touched foreground window.
1458 {
1459 bool haveForegroundWindow = false;
1460 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1461 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1462 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1463 haveForegroundWindow = true;
1464 if (! checkInjectionPermission(touchedWindow.windowHandle,
1465 entry->injectionState)) {
1466 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1467 injectionPermission = INJECTION_PERMISSION_DENIED;
1468 goto Failed;
1469 }
1470 }
1471 }
1472 if (! haveForegroundWindow) {
1473#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001474 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1475 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476#endif
1477 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1478 goto Failed;
1479 }
1480
1481 // Permission granted to injection into all touched foreground windows.
1482 injectionPermission = INJECTION_PERMISSION_GRANTED;
1483 }
1484
1485 // Check whether windows listening for outside touches are owned by the same UID. If it is
1486 // set the policy flag that we will not reveal coordinate information to this window.
1487 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1488 sp<InputWindowHandle> foregroundWindowHandle =
1489 mTempTouchState.getFirstForegroundWindowHandle();
1490 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1491 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1492 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1493 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1494 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1495 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1496 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1497 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1498 }
1499 }
1500 }
1501 }
1502
1503 // Ensure all touched foreground windows are ready for new input.
1504 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1505 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1506 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001507 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001508 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001509 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001510 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001512 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 goto Unresponsive;
1514 }
1515 }
1516 }
1517
1518 // If this is the first pointer going down and the touched window has a wallpaper
1519 // then also add the touched wallpaper windows so they are locked in for the duration
1520 // of the touch gesture.
1521 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1522 // engine only supports touch events. We would need to add a mechanism similar
1523 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1524 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1525 sp<InputWindowHandle> foregroundWindowHandle =
1526 mTempTouchState.getFirstForegroundWindowHandle();
1527 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001528 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1529 size_t numWindows = windowHandles.size();
1530 for (size_t i = 0; i < numWindows; i++) {
1531 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 const InputWindowInfo* info = windowHandle->getInfo();
1533 if (info->displayId == displayId
1534 && windowHandle->getInfo()->layoutParamsType
1535 == InputWindowInfo::TYPE_WALLPAPER) {
1536 mTempTouchState.addOrUpdateWindow(windowHandle,
1537 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001538 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 | InputTarget::FLAG_DISPATCH_AS_IS,
1540 BitSet32(0));
1541 }
1542 }
1543 }
1544 }
1545
1546 // Success! Output targets.
1547 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1548
1549 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1550 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1551 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1552 touchedWindow.pointerIds, inputTargets);
1553 }
1554
1555 // Drop the outside or hover touch windows since we will not care about them
1556 // in the next iteration.
1557 mTempTouchState.filterNonAsIsTouchWindows();
1558
1559Failed:
1560 // Check injection permission once and for all.
1561 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001562 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 injectionPermission = INJECTION_PERMISSION_GRANTED;
1564 } else {
1565 injectionPermission = INJECTION_PERMISSION_DENIED;
1566 }
1567 }
1568
1569 // Update final pieces of touch state if the injector had permission.
1570 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1571 if (!wrongDevice) {
1572 if (switchedDevice) {
1573#if DEBUG_FOCUS
1574 ALOGD("Conflicting pointer actions: Switched to a different device.");
1575#endif
1576 *outConflictingPointerActions = true;
1577 }
1578
1579 if (isHoverAction) {
1580 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001581 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582#if DEBUG_FOCUS
1583 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1584#endif
1585 *outConflictingPointerActions = true;
1586 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001587 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1589 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001590 mTempTouchState.deviceId = entry->deviceId;
1591 mTempTouchState.source = entry->source;
1592 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001593 }
1594 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1595 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1596 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001597 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001598 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1599 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001600 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601#if DEBUG_FOCUS
1602 ALOGD("Conflicting pointer actions: Down received while already down.");
1603#endif
1604 *outConflictingPointerActions = true;
1605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1607 // One pointer went up.
1608 if (isSplit) {
1609 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1610 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1611
1612 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1613 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1614 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1615 touchedWindow.pointerIds.clearBit(pointerId);
1616 if (touchedWindow.pointerIds.isEmpty()) {
1617 mTempTouchState.windows.removeAt(i);
1618 continue;
1619 }
1620 }
1621 i += 1;
1622 }
1623 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001624 }
1625
1626 // Save changes unless the action was scroll in which case the temporary touch
1627 // state was only valid for this one action.
1628 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1629 if (mTempTouchState.displayId >= 0) {
1630 if (oldStateIndex >= 0) {
1631 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1632 } else {
1633 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1634 }
1635 } else if (oldStateIndex >= 0) {
1636 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1637 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638 }
1639
1640 // Update hover state.
1641 mLastHoverWindowHandle = newHoverWindowHandle;
1642 }
1643 } else {
1644#if DEBUG_FOCUS
1645 ALOGD("Not updating touch focus because injection was denied.");
1646#endif
1647 }
1648
1649Unresponsive:
1650 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1651 mTempTouchState.reset();
1652
1653 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1654 updateDispatchStatisticsLocked(currentTime, entry,
1655 injectionResult, timeSpentWaitingForApplication);
1656#if DEBUG_FOCUS
1657 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1658 "timeSpentWaitingForApplication=%0.1fms",
1659 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1660#endif
1661 return injectionResult;
1662}
1663
1664void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1665 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1666 inputTargets.push();
1667
1668 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1669 InputTarget& target = inputTargets.editTop();
Robert Carr5c8a0262018-10-03 16:30:44 -07001670 target.inputChannel = getInputChannelLocked(windowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001671 target.flags = targetFlags;
1672 target.xOffset = - windowInfo->frameLeft;
1673 target.yOffset = - windowInfo->frameTop;
1674 target.scaleFactor = windowInfo->scaleFactor;
1675 target.pointerIds = pointerIds;
1676}
1677
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001678void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets,
1679 int32_t displayId) {
1680 std::unordered_map<int32_t, Vector<sp<InputChannel>>>::const_iterator it =
1681 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001683 if (it != mMonitoringChannelsByDisplay.end()) {
1684 const Vector<sp<InputChannel>>& monitoringChannels = it->second;
1685 const size_t numChannels = monitoringChannels.size();
1686 for (size_t i = 0; i < numChannels; i++) {
1687 inputTargets.push();
1688
1689 InputTarget& target = inputTargets.editTop();
1690 target.inputChannel = monitoringChannels[i];
1691 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1692 target.xOffset = 0;
1693 target.yOffset = 0;
1694 target.pointerIds.clear();
1695 target.scaleFactor = 1.0f;
1696 }
1697 } else {
1698 // If there is no monitor channel registered or all monitor channel unregistered,
1699 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001700 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001701 }
1702}
1703
1704bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1705 const InjectionState* injectionState) {
1706 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001707 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001708 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1709 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001710 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1712 "owned by uid %d",
1713 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001714 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715 windowHandle->getInfo()->ownerUid);
1716 } else {
1717 ALOGW("Permission denied: injecting event from pid %d uid %d",
1718 injectionState->injectorPid, injectionState->injectorUid);
1719 }
1720 return false;
1721 }
1722 return true;
1723}
1724
1725bool InputDispatcher::isWindowObscuredAtPointLocked(
1726 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1727 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001728 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1729 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001731 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732 if (otherHandle == windowHandle) {
1733 break;
1734 }
1735
1736 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1737 if (otherInfo->displayId == displayId
1738 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1739 && otherInfo->frameContainsPoint(x, y)) {
1740 return true;
1741 }
1742 }
1743 return false;
1744}
1745
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001746
1747bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1748 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001749 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001750 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hungb92218b2018-08-14 12:00:21 +08001751 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001752 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001753 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001754 if (otherHandle == windowHandle) {
1755 break;
1756 }
1757
1758 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1759 if (otherInfo->displayId == displayId
1760 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1761 && otherInfo->overlaps(windowInfo)) {
1762 return true;
1763 }
1764 }
1765 return false;
1766}
1767
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001768std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001769 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1770 const char* targetType) {
1771 // If the window is paused then keep waiting.
1772 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001773 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001774 }
1775
1776 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001777 ssize_t connectionIndex = getConnectionIndexLocked(
1778 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001779 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001780 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001781 "registered with the input dispatcher. The window may be in the process "
1782 "of being removed.", targetType);
1783 }
1784
1785 // If the connection is dead then keep waiting.
1786 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1787 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001788 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001789 "The window may be in the process of being removed.", targetType,
1790 connection->getStatusLabel());
1791 }
1792
1793 // If the connection is backed up then keep waiting.
1794 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001795 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001796 "Outbound queue length: %d. Wait queue length: %d.",
1797 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1798 }
1799
1800 // Ensure that the dispatch queues aren't too far backed up for this event.
1801 if (eventEntry->type == EventEntry::TYPE_KEY) {
1802 // If the event is a key event, then we must wait for all previous events to
1803 // complete before delivering it because previous events may have the
1804 // side-effect of transferring focus to a different window and we want to
1805 // ensure that the following keys are sent to the new window.
1806 //
1807 // Suppose the user touches a button in a window then immediately presses "A".
1808 // If the button causes a pop-up window to appear then we want to ensure that
1809 // the "A" key is delivered to the new pop-up window. This is because users
1810 // often anticipate pending UI changes when typing on a keyboard.
1811 // To obtain this behavior, we must serialize key events with respect to all
1812 // prior input events.
1813 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001814 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001815 "finished processing all of the input events that were previously "
1816 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1817 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 }
Jeff Brownffb49772014-10-10 19:01:34 -07001819 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001820 // Touch events can always be sent to a window immediately because the user intended
1821 // to touch whatever was visible at the time. Even if focus changes or a new
1822 // window appears moments later, the touch event was meant to be delivered to
1823 // whatever window happened to be on screen at the time.
1824 //
1825 // Generic motion events, such as trackball or joystick events are a little trickier.
1826 // Like key events, generic motion events are delivered to the focused window.
1827 // Unlike key events, generic motion events don't tend to transfer focus to other
1828 // windows and it is not important for them to be serialized. So we prefer to deliver
1829 // generic motion events as soon as possible to improve efficiency and reduce lag
1830 // through batching.
1831 //
1832 // The one case where we pause input event delivery is when the wait queue is piling
1833 // up with lots of events because the application is not responding.
1834 // This condition ensures that ANRs are detected reliably.
1835 if (!connection->waitQueue.isEmpty()
1836 && currentTime >= connection->waitQueue.head->deliveryTime
1837 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001838 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001839 "finished processing certain input events that were delivered to it over "
1840 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1841 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1842 connection->waitQueue.count(),
1843 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 }
1845 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001846 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847}
1848
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001849std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850 const sp<InputApplicationHandle>& applicationHandle,
1851 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001852 if (applicationHandle != nullptr) {
1853 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001854 std::string label(applicationHandle->getName());
1855 label += " - ";
1856 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 return label;
1858 } else {
1859 return applicationHandle->getName();
1860 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001861 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862 return windowHandle->getName();
1863 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001864 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 }
1866}
1867
1868void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001869 int32_t displayId = getTargetDisplayId(eventEntry);
1870 sp<InputWindowHandle> focusedWindowHandle =
1871 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1872 if (focusedWindowHandle != nullptr) {
1873 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1875#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001876 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877#endif
1878 return;
1879 }
1880 }
1881
1882 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1883 switch (eventEntry->type) {
1884 case EventEntry::TYPE_MOTION: {
1885 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1886 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1887 return;
1888 }
1889
1890 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1891 eventType = USER_ACTIVITY_EVENT_TOUCH;
1892 }
1893 break;
1894 }
1895 case EventEntry::TYPE_KEY: {
1896 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1897 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1898 return;
1899 }
1900 eventType = USER_ACTIVITY_EVENT_BUTTON;
1901 break;
1902 }
1903 }
1904
1905 CommandEntry* commandEntry = postCommandLocked(
1906 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1907 commandEntry->eventTime = eventEntry->eventTime;
1908 commandEntry->userActivityEventType = eventType;
1909}
1910
1911void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1912 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1913#if DEBUG_DISPATCH_CYCLE
1914 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1915 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1916 "pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001917 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 inputTarget->xOffset, inputTarget->yOffset,
1919 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1920#endif
1921
1922 // Skip this event if the connection status is not normal.
1923 // We don't want to enqueue additional outbound events if the connection is broken.
1924 if (connection->status != Connection::STATUS_NORMAL) {
1925#if DEBUG_DISPATCH_CYCLE
1926 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001927 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928#endif
1929 return;
1930 }
1931
1932 // Split a motion event if needed.
1933 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1934 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1935
1936 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1937 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1938 MotionEntry* splitMotionEntry = splitMotionEvent(
1939 originalMotionEntry, inputTarget->pointerIds);
1940 if (!splitMotionEntry) {
1941 return; // split event was dropped
1942 }
1943#if DEBUG_FOCUS
1944 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001945 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001946 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1947#endif
1948 enqueueDispatchEntriesLocked(currentTime, connection,
1949 splitMotionEntry, inputTarget);
1950 splitMotionEntry->release();
1951 return;
1952 }
1953 }
1954
1955 // Not splitting. Enqueue dispatch entries for the event as is.
1956 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1957}
1958
1959void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1960 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1961 bool wasEmpty = connection->outboundQueue.isEmpty();
1962
1963 // Enqueue dispatch entries for the requested modes.
1964 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1965 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1966 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1967 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1968 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1969 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1970 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1971 InputTarget::FLAG_DISPATCH_AS_IS);
1972 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1973 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1974 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1975 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1976
1977 // If the outbound queue was previously empty, start the dispatch cycle going.
1978 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1979 startDispatchCycleLocked(currentTime, connection);
1980 }
1981}
1982
1983void InputDispatcher::enqueueDispatchEntryLocked(
1984 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1985 int32_t dispatchMode) {
1986 int32_t inputTargetFlags = inputTarget->flags;
1987 if (!(inputTargetFlags & dispatchMode)) {
1988 return;
1989 }
1990 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1991
1992 // This is a new event.
1993 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1994 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1995 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1996 inputTarget->scaleFactor);
1997
1998 // Apply target flags and update the connection's input state.
1999 switch (eventEntry->type) {
2000 case EventEntry::TYPE_KEY: {
2001 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2002 dispatchEntry->resolvedAction = keyEntry->action;
2003 dispatchEntry->resolvedFlags = keyEntry->flags;
2004
2005 if (!connection->inputState.trackKey(keyEntry,
2006 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2007#if DEBUG_DISPATCH_CYCLE
2008 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002009 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010#endif
2011 delete dispatchEntry;
2012 return; // skip the inconsistent event
2013 }
2014 break;
2015 }
2016
2017 case EventEntry::TYPE_MOTION: {
2018 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2019 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2020 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2021 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2022 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2023 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2024 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2025 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2026 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2027 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2028 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2029 } else {
2030 dispatchEntry->resolvedAction = motionEntry->action;
2031 }
2032 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2033 && !connection->inputState.isHovering(
2034 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2035#if DEBUG_DISPATCH_CYCLE
2036 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002037 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038#endif
2039 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2040 }
2041
2042 dispatchEntry->resolvedFlags = motionEntry->flags;
2043 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2044 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2045 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002046 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2047 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049
2050 if (!connection->inputState.trackMotion(motionEntry,
2051 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2052#if DEBUG_DISPATCH_CYCLE
2053 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002054 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055#endif
2056 delete dispatchEntry;
2057 return; // skip the inconsistent event
2058 }
2059 break;
2060 }
2061 }
2062
2063 // Remember that we are waiting for this dispatch to complete.
2064 if (dispatchEntry->hasForegroundTarget()) {
2065 incrementPendingForegroundDispatchesLocked(eventEntry);
2066 }
2067
2068 // Enqueue the dispatch entry.
2069 connection->outboundQueue.enqueueAtTail(dispatchEntry);
2070 traceOutboundQueueLengthLocked(connection);
2071}
2072
2073void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2074 const sp<Connection>& connection) {
2075#if DEBUG_DISPATCH_CYCLE
2076 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002077 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078#endif
2079
2080 while (connection->status == Connection::STATUS_NORMAL
2081 && !connection->outboundQueue.isEmpty()) {
2082 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2083 dispatchEntry->deliveryTime = currentTime;
2084
2085 // Publish the event.
2086 status_t status;
2087 EventEntry* eventEntry = dispatchEntry->eventEntry;
2088 switch (eventEntry->type) {
2089 case EventEntry::TYPE_KEY: {
2090 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2091
2092 // Publish the key event.
2093 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002094 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2096 keyEntry->keyCode, keyEntry->scanCode,
2097 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2098 keyEntry->eventTime);
2099 break;
2100 }
2101
2102 case EventEntry::TYPE_MOTION: {
2103 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2104
2105 PointerCoords scaledCoords[MAX_POINTERS];
2106 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2107
2108 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002109 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2111 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002112 float scaleFactor = dispatchEntry->scaleFactor;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 xOffset = dispatchEntry->xOffset * scaleFactor;
2114 yOffset = dispatchEntry->yOffset * scaleFactor;
2115 if (scaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002116 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 scaledCoords[i] = motionEntry->pointerCoords[i];
2118 scaledCoords[i].scale(scaleFactor);
2119 }
2120 usingCoords = scaledCoords;
2121 }
2122 } else {
2123 xOffset = 0.0f;
2124 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125
2126 // We don't want the dispatch target to know.
2127 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002128 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 scaledCoords[i].clear();
2130 }
2131 usingCoords = scaledCoords;
2132 }
2133 }
2134
2135 // Publish the motion event.
2136 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002137 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002138 dispatchEntry->resolvedAction, motionEntry->actionButton,
2139 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2140 motionEntry->metaState, motionEntry->buttonState,
2141 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 motionEntry->downTime, motionEntry->eventTime,
2143 motionEntry->pointerCount, motionEntry->pointerProperties,
2144 usingCoords);
2145 break;
2146 }
2147
2148 default:
2149 ALOG_ASSERT(false);
2150 return;
2151 }
2152
2153 // Check the result.
2154 if (status) {
2155 if (status == WOULD_BLOCK) {
2156 if (connection->waitQueue.isEmpty()) {
2157 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2158 "This is unexpected because the wait queue is empty, so the pipe "
2159 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002160 "event to it, status=%d", connection->getInputChannelName().c_str(),
2161 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2163 } else {
2164 // Pipe is full and we are waiting for the app to finish process some events
2165 // before sending more events to it.
2166#if DEBUG_DISPATCH_CYCLE
2167 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2168 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002169 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170#endif
2171 connection->inputPublisherBlocked = true;
2172 }
2173 } else {
2174 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002175 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002176 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2177 }
2178 return;
2179 }
2180
2181 // Re-enqueue the event on the wait queue.
2182 connection->outboundQueue.dequeue(dispatchEntry);
2183 traceOutboundQueueLengthLocked(connection);
2184 connection->waitQueue.enqueueAtTail(dispatchEntry);
2185 traceWaitQueueLengthLocked(connection);
2186 }
2187}
2188
2189void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2190 const sp<Connection>& connection, uint32_t seq, bool handled) {
2191#if DEBUG_DISPATCH_CYCLE
2192 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002193 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194#endif
2195
2196 connection->inputPublisherBlocked = false;
2197
2198 if (connection->status == Connection::STATUS_BROKEN
2199 || connection->status == Connection::STATUS_ZOMBIE) {
2200 return;
2201 }
2202
2203 // Notify other system components and prepare to start the next dispatch cycle.
2204 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2205}
2206
2207void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2208 const sp<Connection>& connection, bool notify) {
2209#if DEBUG_DISPATCH_CYCLE
2210 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002211 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212#endif
2213
2214 // Clear the dispatch queues.
2215 drainDispatchQueueLocked(&connection->outboundQueue);
2216 traceOutboundQueueLengthLocked(connection);
2217 drainDispatchQueueLocked(&connection->waitQueue);
2218 traceWaitQueueLengthLocked(connection);
2219
2220 // The connection appears to be unrecoverably broken.
2221 // Ignore already broken or zombie connections.
2222 if (connection->status == Connection::STATUS_NORMAL) {
2223 connection->status = Connection::STATUS_BROKEN;
2224
2225 if (notify) {
2226 // Notify other system components.
2227 onDispatchCycleBrokenLocked(currentTime, connection);
2228 }
2229 }
2230}
2231
2232void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2233 while (!queue->isEmpty()) {
2234 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2235 releaseDispatchEntryLocked(dispatchEntry);
2236 }
2237}
2238
2239void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2240 if (dispatchEntry->hasForegroundTarget()) {
2241 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2242 }
2243 delete dispatchEntry;
2244}
2245
2246int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2247 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2248
2249 { // acquire lock
2250 AutoMutex _l(d->mLock);
2251
2252 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2253 if (connectionIndex < 0) {
2254 ALOGE("Received spurious receive callback for unknown input channel. "
2255 "fd=%d, events=0x%x", fd, events);
2256 return 0; // remove the callback
2257 }
2258
2259 bool notify;
2260 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2261 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2262 if (!(events & ALOOPER_EVENT_INPUT)) {
2263 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002264 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 return 1;
2266 }
2267
2268 nsecs_t currentTime = now();
2269 bool gotOne = false;
2270 status_t status;
2271 for (;;) {
2272 uint32_t seq;
2273 bool handled;
2274 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2275 if (status) {
2276 break;
2277 }
2278 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2279 gotOne = true;
2280 }
2281 if (gotOne) {
2282 d->runCommandsLockedInterruptible();
2283 if (status == WOULD_BLOCK) {
2284 return 1;
2285 }
2286 }
2287
2288 notify = status != DEAD_OBJECT || !connection->monitor;
2289 if (notify) {
2290 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002291 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 }
2293 } else {
2294 // Monitor channels are never explicitly unregistered.
2295 // We do it automatically when the remote endpoint is closed so don't warn
2296 // about them.
2297 notify = !connection->monitor;
2298 if (notify) {
2299 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002300 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
2302 }
2303
2304 // Unregister the channel.
2305 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2306 return 0; // remove the callback
2307 } // release lock
2308}
2309
2310void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2311 const CancelationOptions& options) {
2312 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2313 synthesizeCancelationEventsForConnectionLocked(
2314 mConnectionsByFd.valueAt(i), options);
2315 }
2316}
2317
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002318void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2319 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002320 for (auto& it : mMonitoringChannelsByDisplay) {
2321 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
2322 const size_t numChannels = monitoringChannels.size();
2323 for (size_t i = 0; i < numChannels; i++) {
2324 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2325 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002326 }
2327}
2328
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2330 const sp<InputChannel>& channel, const CancelationOptions& options) {
2331 ssize_t index = getConnectionIndexLocked(channel);
2332 if (index >= 0) {
2333 synthesizeCancelationEventsForConnectionLocked(
2334 mConnectionsByFd.valueAt(index), options);
2335 }
2336}
2337
2338void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2339 const sp<Connection>& connection, const CancelationOptions& options) {
2340 if (connection->status == Connection::STATUS_BROKEN) {
2341 return;
2342 }
2343
2344 nsecs_t currentTime = now();
2345
2346 Vector<EventEntry*> cancelationEvents;
2347 connection->inputState.synthesizeCancelationEvents(currentTime,
2348 cancelationEvents, options);
2349
2350 if (!cancelationEvents.isEmpty()) {
2351#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002352 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002354 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 options.reason, options.mode);
2356#endif
2357 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2358 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2359 switch (cancelationEventEntry->type) {
2360 case EventEntry::TYPE_KEY:
2361 logOutboundKeyDetailsLocked("cancel - ",
2362 static_cast<KeyEntry*>(cancelationEventEntry));
2363 break;
2364 case EventEntry::TYPE_MOTION:
2365 logOutboundMotionDetailsLocked("cancel - ",
2366 static_cast<MotionEntry*>(cancelationEventEntry));
2367 break;
2368 }
2369
2370 InputTarget target;
2371 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07002372 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2374 target.xOffset = -windowInfo->frameLeft;
2375 target.yOffset = -windowInfo->frameTop;
2376 target.scaleFactor = windowInfo->scaleFactor;
2377 } else {
2378 target.xOffset = 0;
2379 target.yOffset = 0;
2380 target.scaleFactor = 1.0f;
2381 }
2382 target.inputChannel = connection->inputChannel;
2383 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2384
2385 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2386 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2387
2388 cancelationEventEntry->release();
2389 }
2390
2391 startDispatchCycleLocked(currentTime, connection);
2392 }
2393}
2394
2395InputDispatcher::MotionEntry*
2396InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2397 ALOG_ASSERT(pointerIds.value != 0);
2398
2399 uint32_t splitPointerIndexMap[MAX_POINTERS];
2400 PointerProperties splitPointerProperties[MAX_POINTERS];
2401 PointerCoords splitPointerCoords[MAX_POINTERS];
2402
2403 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2404 uint32_t splitPointerCount = 0;
2405
2406 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2407 originalPointerIndex++) {
2408 const PointerProperties& pointerProperties =
2409 originalMotionEntry->pointerProperties[originalPointerIndex];
2410 uint32_t pointerId = uint32_t(pointerProperties.id);
2411 if (pointerIds.hasBit(pointerId)) {
2412 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2413 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2414 splitPointerCoords[splitPointerCount].copyFrom(
2415 originalMotionEntry->pointerCoords[originalPointerIndex]);
2416 splitPointerCount += 1;
2417 }
2418 }
2419
2420 if (splitPointerCount != pointerIds.count()) {
2421 // This is bad. We are missing some of the pointers that we expected to deliver.
2422 // Most likely this indicates that we received an ACTION_MOVE events that has
2423 // different pointer ids than we expected based on the previous ACTION_DOWN
2424 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2425 // in this way.
2426 ALOGW("Dropping split motion event because the pointer count is %d but "
2427 "we expected there to be %d pointers. This probably means we received "
2428 "a broken sequence of pointer ids from the input device.",
2429 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002430 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431 }
2432
2433 int32_t action = originalMotionEntry->action;
2434 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2435 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2436 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2437 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2438 const PointerProperties& pointerProperties =
2439 originalMotionEntry->pointerProperties[originalPointerIndex];
2440 uint32_t pointerId = uint32_t(pointerProperties.id);
2441 if (pointerIds.hasBit(pointerId)) {
2442 if (pointerIds.count() == 1) {
2443 // The first/last pointer went down/up.
2444 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2445 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2446 } else {
2447 // A secondary pointer went down/up.
2448 uint32_t splitPointerIndex = 0;
2449 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2450 splitPointerIndex += 1;
2451 }
2452 action = maskedAction | (splitPointerIndex
2453 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2454 }
2455 } else {
2456 // An unrelated pointer changed.
2457 action = AMOTION_EVENT_ACTION_MOVE;
2458 }
2459 }
2460
2461 MotionEntry* splitMotionEntry = new MotionEntry(
2462 originalMotionEntry->eventTime,
2463 originalMotionEntry->deviceId,
2464 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002465 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 originalMotionEntry->policyFlags,
2467 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002468 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 originalMotionEntry->flags,
2470 originalMotionEntry->metaState,
2471 originalMotionEntry->buttonState,
2472 originalMotionEntry->edgeFlags,
2473 originalMotionEntry->xPrecision,
2474 originalMotionEntry->yPrecision,
2475 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002476 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477
2478 if (originalMotionEntry->injectionState) {
2479 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2480 splitMotionEntry->injectionState->refCount += 1;
2481 }
2482
2483 return splitMotionEntry;
2484}
2485
2486void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2487#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002488 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489#endif
2490
2491 bool needWake;
2492 { // acquire lock
2493 AutoMutex _l(mLock);
2494
2495 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2496 needWake = enqueueInboundEventLocked(newEntry);
2497 } // release lock
2498
2499 if (needWake) {
2500 mLooper->wake();
2501 }
2502}
2503
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002504/**
2505 * If one of the meta shortcuts is detected, process them here:
2506 * Meta + Backspace -> generate BACK
2507 * Meta + Enter -> generate HOME
2508 * This will potentially overwrite keyCode and metaState.
2509 */
2510void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2511 int32_t& keyCode, int32_t& metaState) {
2512 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2513 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2514 if (keyCode == AKEYCODE_DEL) {
2515 newKeyCode = AKEYCODE_BACK;
2516 } else if (keyCode == AKEYCODE_ENTER) {
2517 newKeyCode = AKEYCODE_HOME;
2518 }
2519 if (newKeyCode != AKEYCODE_UNKNOWN) {
2520 AutoMutex _l(mLock);
2521 struct KeyReplacement replacement = {keyCode, deviceId};
2522 mReplacedKeys.add(replacement, newKeyCode);
2523 keyCode = newKeyCode;
2524 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2525 }
2526 } else if (action == AKEY_EVENT_ACTION_UP) {
2527 // In order to maintain a consistent stream of up and down events, check to see if the key
2528 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2529 // even if the modifier was released between the down and the up events.
2530 AutoMutex _l(mLock);
2531 struct KeyReplacement replacement = {keyCode, deviceId};
2532 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2533 if (index >= 0) {
2534 keyCode = mReplacedKeys.valueAt(index);
2535 mReplacedKeys.removeItemsAt(index);
2536 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2537 }
2538 }
2539}
2540
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2542#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002543 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002544 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002545 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002546 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002548 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549#endif
2550 if (!validateKeyEvent(args->action)) {
2551 return;
2552 }
2553
2554 uint32_t policyFlags = args->policyFlags;
2555 int32_t flags = args->flags;
2556 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002557 // InputDispatcher tracks and generates key repeats on behalf of
2558 // whatever notifies it, so repeatCount should always be set to 0
2559 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002560 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2561 policyFlags |= POLICY_FLAG_VIRTUAL;
2562 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2563 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564 if (policyFlags & POLICY_FLAG_FUNCTION) {
2565 metaState |= AMETA_FUNCTION_ON;
2566 }
2567
2568 policyFlags |= POLICY_FLAG_TRUSTED;
2569
Michael Wright78f24442014-08-06 15:55:28 -07002570 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002571 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002572
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002574 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002575 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576 args->downTime, args->eventTime);
2577
Michael Wright2b3c3302018-03-02 17:19:13 +00002578 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002580 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2581 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2582 std::to_string(t.duration().count()).c_str());
2583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585 bool needWake;
2586 { // acquire lock
2587 mLock.lock();
2588
2589 if (shouldSendKeyToInputFilterLocked(args)) {
2590 mLock.unlock();
2591
2592 policyFlags |= POLICY_FLAG_FILTERED;
2593 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2594 return; // event was consumed by the filter
2595 }
2596
2597 mLock.lock();
2598 }
2599
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 KeyEntry* newEntry = new KeyEntry(args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002601 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002602 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 metaState, repeatCount, args->downTime);
2604
2605 needWake = enqueueInboundEventLocked(newEntry);
2606 mLock.unlock();
2607 } // release lock
2608
2609 if (needWake) {
2610 mLooper->wake();
2611 }
2612}
2613
2614bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2615 return mInputFilterEnabled;
2616}
2617
2618void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2619#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002620 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2621 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002622 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002623 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2624 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002625 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002626 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627 for (uint32_t i = 0; i < args->pointerCount; i++) {
2628 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2629 "x=%f, y=%f, pressure=%f, size=%f, "
2630 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2631 "orientation=%f",
2632 i, args->pointerProperties[i].id,
2633 args->pointerProperties[i].toolType,
2634 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2635 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2636 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2637 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2638 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2639 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2640 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2641 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2642 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2643 }
2644#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002645 if (!validateMotionEvent(args->action, args->actionButton,
2646 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 return;
2648 }
2649
2650 uint32_t policyFlags = args->policyFlags;
2651 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002652
2653 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002655 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2656 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2657 std::to_string(t.duration().count()).c_str());
2658 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659
2660 bool needWake;
2661 { // acquire lock
2662 mLock.lock();
2663
2664 if (shouldSendMotionToInputFilterLocked(args)) {
2665 mLock.unlock();
2666
2667 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002668 event.initialize(args->deviceId, args->source, args->displayId,
2669 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002670 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2671 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672 args->downTime, args->eventTime,
2673 args->pointerCount, args->pointerProperties, args->pointerCoords);
2674
2675 policyFlags |= POLICY_FLAG_FILTERED;
2676 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2677 return; // event was consumed by the filter
2678 }
2679
2680 mLock.lock();
2681 }
2682
2683 // Just enqueue a new motion event.
2684 MotionEntry* newEntry = new MotionEntry(args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002685 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002686 args->action, args->actionButton, args->flags,
2687 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002689 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690
2691 needWake = enqueueInboundEventLocked(newEntry);
2692 mLock.unlock();
2693 } // release lock
2694
2695 if (needWake) {
2696 mLooper->wake();
2697 }
2698}
2699
2700bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2701 // TODO: support sending secondary display events to input filter
2702 return mInputFilterEnabled && isMainDisplay(args->displayId);
2703}
2704
2705void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2706#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002707 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2708 "switchMask=0x%08x",
2709 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710#endif
2711
2712 uint32_t policyFlags = args->policyFlags;
2713 policyFlags |= POLICY_FLAG_TRUSTED;
2714 mPolicy->notifySwitch(args->eventTime,
2715 args->switchValues, args->switchMask, policyFlags);
2716}
2717
2718void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2719#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002720 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721 args->eventTime, args->deviceId);
2722#endif
2723
2724 bool needWake;
2725 { // acquire lock
2726 AutoMutex _l(mLock);
2727
2728 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2729 needWake = enqueueInboundEventLocked(newEntry);
2730 } // release lock
2731
2732 if (needWake) {
2733 mLooper->wake();
2734 }
2735}
2736
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002737int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2739 uint32_t policyFlags) {
2740#if DEBUG_INBOUND_EVENT_DETAILS
2741 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002742 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2743 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744#endif
2745
2746 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2747
2748 policyFlags |= POLICY_FLAG_INJECTED;
2749 if (hasInjectionPermission(injectorPid, injectorUid)) {
2750 policyFlags |= POLICY_FLAG_TRUSTED;
2751 }
2752
2753 EventEntry* firstInjectedEntry;
2754 EventEntry* lastInjectedEntry;
2755 switch (event->getType()) {
2756 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002757 KeyEvent keyEvent;
2758 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2759 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760 if (! validateKeyEvent(action)) {
2761 return INPUT_EVENT_INJECTION_FAILED;
2762 }
2763
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002764 int32_t flags = keyEvent.getFlags();
2765 int32_t keyCode = keyEvent.getKeyCode();
2766 int32_t metaState = keyEvent.getMetaState();
2767 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2768 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002769 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002770 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002771 keyEvent.getDownTime(), keyEvent.getEventTime());
2772
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2774 policyFlags |= POLICY_FLAG_VIRTUAL;
2775 }
2776
2777 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002778 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002779 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002780 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2781 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2782 std::to_string(t.duration().count()).c_str());
2783 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784 }
2785
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786 mLock.lock();
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002787 firstInjectedEntry = new KeyEntry(keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002788 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002790 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2791 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 lastInjectedEntry = firstInjectedEntry;
2793 break;
2794 }
2795
2796 case AINPUT_EVENT_TYPE_MOTION: {
2797 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002798 int32_t action = motionEvent->getAction();
2799 size_t pointerCount = motionEvent->getPointerCount();
2800 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002801 int32_t actionButton = motionEvent->getActionButton();
2802 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 return INPUT_EVENT_INJECTION_FAILED;
2804 }
2805
2806 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2807 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002808 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002810 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2811 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2812 std::to_string(t.duration().count()).c_str());
2813 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814 }
2815
2816 mLock.lock();
2817 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2818 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2819 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002820 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2821 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002822 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 motionEvent->getMetaState(), motionEvent->getButtonState(),
2824 motionEvent->getEdgeFlags(),
2825 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002826 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002827 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2828 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 lastInjectedEntry = firstInjectedEntry;
2830 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2831 sampleEventTimes += 1;
2832 samplePointerCoords += pointerCount;
2833 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002834 motionEvent->getDeviceId(), motionEvent->getSource(),
2835 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002836 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 motionEvent->getMetaState(), motionEvent->getButtonState(),
2838 motionEvent->getEdgeFlags(),
2839 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002840 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002841 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2842 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 lastInjectedEntry->next = nextInjectedEntry;
2844 lastInjectedEntry = nextInjectedEntry;
2845 }
2846 break;
2847 }
2848
2849 default:
2850 ALOGW("Cannot inject event of type %d", event->getType());
2851 return INPUT_EVENT_INJECTION_FAILED;
2852 }
2853
2854 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2855 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2856 injectionState->injectionIsAsync = true;
2857 }
2858
2859 injectionState->refCount += 1;
2860 lastInjectedEntry->injectionState = injectionState;
2861
2862 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002863 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 EventEntry* nextEntry = entry->next;
2865 needWake |= enqueueInboundEventLocked(entry);
2866 entry = nextEntry;
2867 }
2868
2869 mLock.unlock();
2870
2871 if (needWake) {
2872 mLooper->wake();
2873 }
2874
2875 int32_t injectionResult;
2876 { // acquire lock
2877 AutoMutex _l(mLock);
2878
2879 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2880 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2881 } else {
2882 for (;;) {
2883 injectionResult = injectionState->injectionResult;
2884 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2885 break;
2886 }
2887
2888 nsecs_t remainingTimeout = endTime - now();
2889 if (remainingTimeout <= 0) {
2890#if DEBUG_INJECTION
2891 ALOGD("injectInputEvent - Timed out waiting for injection result "
2892 "to become available.");
2893#endif
2894 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2895 break;
2896 }
2897
2898 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2899 }
2900
2901 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2902 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2903 while (injectionState->pendingForegroundDispatches != 0) {
2904#if DEBUG_INJECTION
2905 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2906 injectionState->pendingForegroundDispatches);
2907#endif
2908 nsecs_t remainingTimeout = endTime - now();
2909 if (remainingTimeout <= 0) {
2910#if DEBUG_INJECTION
2911 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2912 "dispatches to finish.");
2913#endif
2914 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2915 break;
2916 }
2917
2918 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2919 }
2920 }
2921 }
2922
2923 injectionState->release();
2924 } // release lock
2925
2926#if DEBUG_INJECTION
2927 ALOGD("injectInputEvent - Finished with result %d. "
2928 "injectorPid=%d, injectorUid=%d",
2929 injectionResult, injectorPid, injectorUid);
2930#endif
2931
2932 return injectionResult;
2933}
2934
2935bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2936 return injectorUid == 0
2937 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2938}
2939
2940void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2941 InjectionState* injectionState = entry->injectionState;
2942 if (injectionState) {
2943#if DEBUG_INJECTION
2944 ALOGD("Setting input event injection result to %d. "
2945 "injectorPid=%d, injectorUid=%d",
2946 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2947#endif
2948
2949 if (injectionState->injectionIsAsync
2950 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2951 // Log the outcome since the injector did not wait for the injection result.
2952 switch (injectionResult) {
2953 case INPUT_EVENT_INJECTION_SUCCEEDED:
2954 ALOGV("Asynchronous input event injection succeeded.");
2955 break;
2956 case INPUT_EVENT_INJECTION_FAILED:
2957 ALOGW("Asynchronous input event injection failed.");
2958 break;
2959 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2960 ALOGW("Asynchronous input event injection permission denied.");
2961 break;
2962 case INPUT_EVENT_INJECTION_TIMED_OUT:
2963 ALOGW("Asynchronous input event injection timed out.");
2964 break;
2965 }
2966 }
2967
2968 injectionState->injectionResult = injectionResult;
2969 mInjectionResultAvailableCondition.broadcast();
2970 }
2971}
2972
2973void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2974 InjectionState* injectionState = entry->injectionState;
2975 if (injectionState) {
2976 injectionState->pendingForegroundDispatches += 1;
2977 }
2978}
2979
2980void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2981 InjectionState* injectionState = entry->injectionState;
2982 if (injectionState) {
2983 injectionState->pendingForegroundDispatches -= 1;
2984
2985 if (injectionState->pendingForegroundDispatches == 0) {
2986 mInjectionSyncFinishedCondition.broadcast();
2987 }
2988 }
2989}
2990
Arthur Hungb92218b2018-08-14 12:00:21 +08002991Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
2992 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
2993 mWindowHandlesByDisplay.find(displayId);
2994 if(it != mWindowHandlesByDisplay.end()) {
2995 return it->second;
2996 }
2997
2998 // Return an empty one if nothing found.
2999 return Vector<sp<InputWindowHandle>>();
3000}
3001
Michael Wrightd02c5b62014-02-10 15:10:22 -08003002sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3003 const sp<InputChannel>& inputChannel) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003004 for (auto& it : mWindowHandlesByDisplay) {
3005 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3006 size_t numWindows = windowHandles.size();
3007 for (size_t i = 0; i < numWindows; i++) {
3008 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
Robert Carr5c8a0262018-10-03 16:30:44 -07003009 if (windowHandle->getToken() == inputChannel->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003010 return windowHandle;
3011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012 }
3013 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003014 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015}
3016
3017bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003018 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003019 for (auto& it : mWindowHandlesByDisplay) {
3020 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3021 size_t numWindows = windowHandles.size();
3022 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003023 if (windowHandles.itemAt(i)->getToken()
3024 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003025 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003026 ALOGE("Found window %s in display %" PRId32
3027 ", but it should belong to display %" PRId32,
3028 windowHandle->getName().c_str(), it.first,
3029 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003030 }
3031 return true;
3032 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033 }
3034 }
3035 return false;
3036}
3037
Robert Carr5c8a0262018-10-03 16:30:44 -07003038sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3039 size_t count = mInputChannelsByToken.count(token);
3040 if (count == 0) {
3041 return nullptr;
3042 }
3043 return mInputChannelsByToken.at(token);
3044}
3045
Arthur Hungb92218b2018-08-14 12:00:21 +08003046/**
3047 * Called from InputManagerService, update window handle list by displayId that can receive input.
3048 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3049 * If set an empty list, remove all handles from the specific display.
3050 * For focused handle, check if need to change and send a cancel event to previous one.
3051 * For removed handle, check if need to send a cancel event if already in touch.
3052 */
3053void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3054 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003056 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057#endif
3058 { // acquire lock
3059 AutoMutex _l(mLock);
3060
Arthur Hungb92218b2018-08-14 12:00:21 +08003061 // Copy old handles for release if they are no longer present.
3062 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063
Tiger Huang721e26f2018-07-24 22:26:19 +08003064 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003065 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003066
3067 if (inputWindowHandles.isEmpty()) {
3068 // Remove all handles on a display if there are no windows left.
3069 mWindowHandlesByDisplay.erase(displayId);
3070 } else {
3071 size_t numWindows = inputWindowHandles.size();
3072 for (size_t i = 0; i < numWindows; i++) {
3073 const sp<InputWindowHandle>& windowHandle = inputWindowHandles.itemAt(i);
Robert Carr5c8a0262018-10-03 16:30:44 -07003074 if (!windowHandle->updateInfo() || getInputChannelLocked(windowHandle->getToken()) == nullptr) {
3075 ALOGE("Window handle %s has no registered input channel",
3076 windowHandle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003077 continue;
3078 }
3079
3080 if (windowHandle->getInfo()->displayId != displayId) {
3081 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3082 windowHandle->getName().c_str(), displayId,
3083 windowHandle->getInfo()->displayId);
3084 continue;
3085 }
3086
3087 if (windowHandle->getInfo()->hasFocus) {
3088 newFocusedWindowHandle = windowHandle;
3089 }
3090 if (windowHandle == mLastHoverWindowHandle) {
3091 foundHoveredWindow = true;
3092 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003093 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003094
3095 // Insert or replace
3096 mWindowHandlesByDisplay[displayId] = inputWindowHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097 }
3098
3099 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003100 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 }
3102
Tiger Huang721e26f2018-07-24 22:26:19 +08003103 sp<InputWindowHandle> oldFocusedWindowHandle =
3104 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3105
3106 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3107 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003109 ALOGD("Focus left window: %s in display %" PRId32,
3110 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003112 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3113 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003114 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3116 "focus left window");
3117 synthesizeCancelationEventsForInputChannelLocked(
3118 focusedInputChannel, options);
3119 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003120 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003121 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003122 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003123#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003124 ALOGD("Focus entered window: %s in display %" PRId32,
3125 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003127 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003129 }
3130
Arthur Hungb92218b2018-08-14 12:00:21 +08003131 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3132 if (stateIndex >= 0) {
3133 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003134 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003135 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003136 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003137#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003138 ALOGD("Touched window was removed: %s in display %" PRId32,
3139 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003141 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003142 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003143 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003144 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3145 "touched window was removed");
3146 synthesizeCancelationEventsForInputChannelLocked(
3147 touchedInputChannel, options);
3148 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003149 state.windows.removeAt(i);
3150 } else {
3151 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 }
3154 }
3155
3156 // Release information for windows that are no longer present.
3157 // This ensures that unused input channels are released promptly.
3158 // Otherwise, they might stick around until the window handle is destroyed
3159 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003160 size_t numWindows = oldWindowHandles.size();
3161 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003163 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003165 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003167 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168 }
3169 }
3170 } // release lock
3171
3172 // Wake up poll loop since it may need to make new input dispatching choices.
3173 mLooper->wake();
3174}
3175
3176void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003177 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003179 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180#endif
3181 { // acquire lock
3182 AutoMutex _l(mLock);
3183
Tiger Huang721e26f2018-07-24 22:26:19 +08003184 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3185 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003186 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003187 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3188 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003190 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003192 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003193 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003194 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003196 oldFocusedApplicationHandle->releaseInfo();
3197 oldFocusedApplicationHandle.clear();
3198 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 }
3200
3201#if DEBUG_FOCUS
3202 //logDispatchStateLocked();
3203#endif
3204 } // release lock
3205
3206 // Wake up poll loop since it may need to make new input dispatching choices.
3207 mLooper->wake();
3208}
3209
Tiger Huang721e26f2018-07-24 22:26:19 +08003210/**
3211 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3212 * the display not specified.
3213 *
3214 * We track any unreleased events for each window. If a window loses the ability to receive the
3215 * released event, we will send a cancel event to it. So when the focused display is changed, we
3216 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3217 * display. The display-specified events won't be affected.
3218 */
3219void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3220#if DEBUG_FOCUS
3221 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3222#endif
3223 { // acquire lock
3224 AutoMutex _l(mLock);
3225
3226 if (mFocusedDisplayId != displayId) {
3227 sp<InputWindowHandle> oldFocusedWindowHandle =
3228 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3229 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003230 sp<InputChannel> inputChannel =
3231 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003232 if (inputChannel != nullptr) {
3233 CancelationOptions options(
3234 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3235 "The display which contains this window no longer has focus.");
3236 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3237 }
3238 }
3239 mFocusedDisplayId = displayId;
3240
3241 // Sanity check
3242 sp<InputWindowHandle> newFocusedWindowHandle =
3243 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3244 if (newFocusedWindowHandle == nullptr) {
3245 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3246 if (!mFocusedWindowHandlesByDisplay.empty()) {
3247 ALOGE("But another display has a focused window:");
3248 for (auto& it : mFocusedWindowHandlesByDisplay) {
3249 const int32_t displayId = it.first;
3250 const sp<InputWindowHandle>& windowHandle = it.second;
3251 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3252 displayId, windowHandle->getName().c_str());
3253 }
3254 }
3255 }
3256 }
3257
3258#if DEBUG_FOCUS
3259 logDispatchStateLocked();
3260#endif
3261 } // release lock
3262
3263 // Wake up poll loop since it may need to make new input dispatching choices.
3264 mLooper->wake();
3265}
3266
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3268#if DEBUG_FOCUS
3269 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3270#endif
3271
3272 bool changed;
3273 { // acquire lock
3274 AutoMutex _l(mLock);
3275
3276 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3277 if (mDispatchFrozen && !frozen) {
3278 resetANRTimeoutsLocked();
3279 }
3280
3281 if (mDispatchEnabled && !enabled) {
3282 resetAndDropEverythingLocked("dispatcher is being disabled");
3283 }
3284
3285 mDispatchEnabled = enabled;
3286 mDispatchFrozen = frozen;
3287 changed = true;
3288 } else {
3289 changed = false;
3290 }
3291
3292#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003293 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294#endif
3295 } // release lock
3296
3297 if (changed) {
3298 // Wake up poll loop since it may need to make new input dispatching choices.
3299 mLooper->wake();
3300 }
3301}
3302
3303void InputDispatcher::setInputFilterEnabled(bool enabled) {
3304#if DEBUG_FOCUS
3305 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3306#endif
3307
3308 { // acquire lock
3309 AutoMutex _l(mLock);
3310
3311 if (mInputFilterEnabled == enabled) {
3312 return;
3313 }
3314
3315 mInputFilterEnabled = enabled;
3316 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3317 } // release lock
3318
3319 // Wake up poll loop since there might be work to do to drop everything.
3320 mLooper->wake();
3321}
3322
3323bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3324 const sp<InputChannel>& toChannel) {
3325#if DEBUG_FOCUS
3326 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003327 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328#endif
3329 { // acquire lock
3330 AutoMutex _l(mLock);
3331
3332 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3333 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07003334 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335#if DEBUG_FOCUS
3336 ALOGD("Cannot transfer focus because from or to window not found.");
3337#endif
3338 return false;
3339 }
3340 if (fromWindowHandle == toWindowHandle) {
3341#if DEBUG_FOCUS
3342 ALOGD("Trivial transfer to same window.");
3343#endif
3344 return true;
3345 }
3346 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3347#if DEBUG_FOCUS
3348 ALOGD("Cannot transfer focus because windows are on different displays.");
3349#endif
3350 return false;
3351 }
3352
3353 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003354 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3355 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3356 for (size_t i = 0; i < state.windows.size(); i++) {
3357 const TouchedWindow& touchedWindow = state.windows[i];
3358 if (touchedWindow.windowHandle == fromWindowHandle) {
3359 int32_t oldTargetFlags = touchedWindow.targetFlags;
3360 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361
Jeff Brownf086ddb2014-02-11 14:28:48 -08003362 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363
Jeff Brownf086ddb2014-02-11 14:28:48 -08003364 int32_t newTargetFlags = oldTargetFlags
3365 & (InputTarget::FLAG_FOREGROUND
3366 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3367 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368
Jeff Brownf086ddb2014-02-11 14:28:48 -08003369 found = true;
3370 goto Found;
3371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372 }
3373 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003374Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375
3376 if (! found) {
3377#if DEBUG_FOCUS
3378 ALOGD("Focus transfer failed because from window did not have focus.");
3379#endif
3380 return false;
3381 }
3382
3383 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3384 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3385 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3386 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3387 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3388
3389 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3390 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3391 "transferring touch focus from this window to another window");
3392 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3393 }
3394
3395#if DEBUG_FOCUS
3396 logDispatchStateLocked();
3397#endif
3398 } // release lock
3399
3400 // Wake up poll loop since it may need to make new input dispatching choices.
3401 mLooper->wake();
3402 return true;
3403}
3404
3405void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3406#if DEBUG_FOCUS
3407 ALOGD("Resetting and dropping all events (%s).", reason);
3408#endif
3409
3410 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3411 synthesizeCancelationEventsForAllConnectionsLocked(options);
3412
3413 resetKeyRepeatLocked();
3414 releasePendingEventLocked();
3415 drainInboundQueueLocked();
3416 resetANRTimeoutsLocked();
3417
Jeff Brownf086ddb2014-02-11 14:28:48 -08003418 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003420 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421}
3422
3423void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003424 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 dumpDispatchStateLocked(dump);
3426
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003427 std::istringstream stream(dump);
3428 std::string line;
3429
3430 while (std::getline(stream, line, '\n')) {
3431 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 }
3433}
3434
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003435void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3436 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3437 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003438 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439
Tiger Huang721e26f2018-07-24 22:26:19 +08003440 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3441 dump += StringPrintf(INDENT "FocusedApplications:\n");
3442 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3443 const int32_t displayId = it.first;
3444 const sp<InputApplicationHandle>& applicationHandle = it.second;
3445 dump += StringPrintf(
3446 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3447 displayId,
3448 applicationHandle->getName().c_str(),
3449 applicationHandle->getDispatchingTimeout(
3450 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003453 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003455
3456 if (!mFocusedWindowHandlesByDisplay.empty()) {
3457 dump += StringPrintf(INDENT "FocusedWindows:\n");
3458 for (auto& it : mFocusedWindowHandlesByDisplay) {
3459 const int32_t displayId = it.first;
3460 const sp<InputWindowHandle>& windowHandle = it.second;
3461 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3462 displayId, windowHandle->getName().c_str());
3463 }
3464 } else {
3465 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003467
Jeff Brownf086ddb2014-02-11 14:28:48 -08003468 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003469 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003470 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3471 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003472 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003473 state.displayId, toString(state.down), toString(state.split),
3474 state.deviceId, state.source);
3475 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003476 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003477 for (size_t i = 0; i < state.windows.size(); i++) {
3478 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003479 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3480 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003481 touchedWindow.pointerIds.value,
3482 touchedWindow.targetFlags);
3483 }
3484 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003485 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487 }
3488 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003489 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 }
3491
Arthur Hungb92218b2018-08-14 12:00:21 +08003492 if (!mWindowHandlesByDisplay.empty()) {
3493 for (auto& it : mWindowHandlesByDisplay) {
3494 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003495 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003496 if (!windowHandles.isEmpty()) {
3497 dump += INDENT2 "Windows:\n";
3498 for (size_t i = 0; i < windowHandles.size(); i++) {
3499 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3500 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501
Arthur Hungb92218b2018-08-14 12:00:21 +08003502 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3503 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3504 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3505 "frame=[%d,%d][%d,%d], scale=%f, "
3506 "touchableRegion=",
3507 i, windowInfo->name.c_str(), windowInfo->displayId,
3508 toString(windowInfo->paused),
3509 toString(windowInfo->hasFocus),
3510 toString(windowInfo->hasWallpaper),
3511 toString(windowInfo->visible),
3512 toString(windowInfo->canReceiveKeys),
3513 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3514 windowInfo->layer,
3515 windowInfo->frameLeft, windowInfo->frameTop,
3516 windowInfo->frameRight, windowInfo->frameBottom,
3517 windowInfo->scaleFactor);
3518 dumpRegion(dump, windowInfo->touchableRegion);
3519 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3520 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3521 windowInfo->ownerPid, windowInfo->ownerUid,
3522 windowInfo->dispatchingTimeout / 1000000.0);
3523 }
3524 } else {
3525 dump += INDENT2 "Windows: <none>\n";
3526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 }
3528 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003529 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530 }
3531
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003532 if (!mMonitoringChannelsByDisplay.empty()) {
3533 for (auto& it : mMonitoringChannelsByDisplay) {
3534 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003535 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003536 const size_t numChannels = monitoringChannels.size();
3537 for (size_t i = 0; i < numChannels; i++) {
3538 const sp<InputChannel>& channel = monitoringChannels[i];
3539 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3540 }
3541 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003543 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544 }
3545
3546 nsecs_t currentTime = now();
3547
3548 // Dump recently dispatched or dropped events from oldest to newest.
3549 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003550 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003552 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003554 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555 (currentTime - entry->eventTime) * 0.000001f);
3556 }
3557 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003558 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 }
3560
3561 // Dump event currently being dispatched.
3562 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003563 dump += INDENT "PendingEvent:\n";
3564 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003566 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3568 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003569 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570 }
3571
3572 // Dump inbound events from oldest to newest.
3573 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003574 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003576 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003578 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579 (currentTime - entry->eventTime) * 0.000001f);
3580 }
3581 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003582 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 }
3584
Michael Wright78f24442014-08-06 15:55:28 -07003585 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003586 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003587 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3588 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3589 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003590 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003591 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3592 }
3593 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003594 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003595 }
3596
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003598 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003599 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3600 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003601 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003603 i, connection->getInputChannelName().c_str(),
3604 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 connection->getStatusLabel(), toString(connection->monitor),
3606 toString(connection->inputPublisherBlocked));
3607
3608 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003609 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 connection->outboundQueue.count());
3611 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3612 entry = entry->next) {
3613 dump.append(INDENT4);
3614 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003615 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 entry->targetFlags, entry->resolvedAction,
3617 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3618 }
3619 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003620 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 }
3622
3623 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003624 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625 connection->waitQueue.count());
3626 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3627 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003628 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003630 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 "age=%0.1fms, wait=%0.1fms\n",
3632 entry->targetFlags, entry->resolvedAction,
3633 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3634 (currentTime - entry->deliveryTime) * 0.000001f);
3635 }
3636 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003637 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 }
3639 }
3640 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003641 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 }
3643
3644 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003645 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 (mAppSwitchDueTime - now()) / 1000000.0);
3647 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003648 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 }
3650
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003651 dump += INDENT "Configuration:\n";
3652 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003654 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655 mConfig.keyRepeatTimeout * 0.000001f);
3656}
3657
Robert Carr803535b2018-08-02 16:38:15 -07003658status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003660 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3661 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662#endif
3663
3664 { // acquire lock
3665 AutoMutex _l(mLock);
3666
Robert Carr4e670e52018-08-15 13:26:12 -07003667 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3668 // treat inputChannel as monitor channel for displayId.
3669 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3670 if (monitor) {
3671 inputChannel->setToken(new BBinder());
3672 }
3673
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 if (getConnectionIndexLocked(inputChannel) >= 0) {
3675 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003676 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 return BAD_VALUE;
3678 }
3679
Robert Carr803535b2018-08-02 16:38:15 -07003680 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681
3682 int fd = inputChannel->getFd();
3683 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003684 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003686 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003688 Vector<sp<InputChannel>>& monitoringChannels =
3689 mMonitoringChannelsByDisplay[displayId];
3690 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 }
3692
3693 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3694 } // release lock
3695
3696 // Wake the looper because some connections have changed.
3697 mLooper->wake();
3698 return OK;
3699}
3700
3701status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3702#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003703 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704#endif
3705
3706 { // acquire lock
3707 AutoMutex _l(mLock);
3708
3709 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3710 if (status) {
3711 return status;
3712 }
3713 } // release lock
3714
3715 // Wake the poll loop because removing the connection may have changed the current
3716 // synchronization state.
3717 mLooper->wake();
3718 return OK;
3719}
3720
3721status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3722 bool notify) {
3723 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3724 if (connectionIndex < 0) {
3725 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003726 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 return BAD_VALUE;
3728 }
3729
3730 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3731 mConnectionsByFd.removeItemsAt(connectionIndex);
3732
Robert Carr5c8a0262018-10-03 16:30:44 -07003733 mInputChannelsByToken.erase(inputChannel->getToken());
3734
Michael Wrightd02c5b62014-02-10 15:10:22 -08003735 if (connection->monitor) {
3736 removeMonitorChannelLocked(inputChannel);
3737 }
3738
3739 mLooper->removeFd(inputChannel->getFd());
3740
3741 nsecs_t currentTime = now();
3742 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3743
3744 connection->status = Connection::STATUS_ZOMBIE;
3745 return OK;
3746}
3747
3748void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003749 for (auto it = mMonitoringChannelsByDisplay.begin();
3750 it != mMonitoringChannelsByDisplay.end(); ) {
3751 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3752 const size_t numChannels = monitoringChannels.size();
3753 for (size_t i = 0; i < numChannels; i++) {
3754 if (monitoringChannels[i] == inputChannel) {
3755 monitoringChannels.removeAt(i);
3756 break;
3757 }
3758 }
3759 if (monitoringChannels.empty()) {
3760 it = mMonitoringChannelsByDisplay.erase(it);
3761 } else {
3762 ++it;
3763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 }
3765}
3766
3767ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003768 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003769 return -1;
3770 }
3771
Robert Carr4e670e52018-08-15 13:26:12 -07003772 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3773 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3774 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3775 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 }
3777 }
Robert Carr4e670e52018-08-15 13:26:12 -07003778
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779 return -1;
3780}
3781
3782void InputDispatcher::onDispatchCycleFinishedLocked(
3783 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3784 CommandEntry* commandEntry = postCommandLocked(
3785 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3786 commandEntry->connection = connection;
3787 commandEntry->eventTime = currentTime;
3788 commandEntry->seq = seq;
3789 commandEntry->handled = handled;
3790}
3791
3792void InputDispatcher::onDispatchCycleBrokenLocked(
3793 nsecs_t currentTime, const sp<Connection>& connection) {
3794 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003795 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796
3797 CommandEntry* commandEntry = postCommandLocked(
3798 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3799 commandEntry->connection = connection;
3800}
3801
3802void InputDispatcher::onANRLocked(
3803 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3804 const sp<InputWindowHandle>& windowHandle,
3805 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3806 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3807 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3808 ALOGI("Application is not responding: %s. "
3809 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003810 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 dispatchLatency, waitDuration, reason);
3812
3813 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003814 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 struct tm tm;
3816 localtime_r(&t, &tm);
3817 char timestr[64];
3818 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3819 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003820 mLastANRState += INDENT "ANR:\n";
3821 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3822 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3823 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3824 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3825 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3826 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 dumpDispatchStateLocked(mLastANRState);
3828
3829 CommandEntry* commandEntry = postCommandLocked(
3830 & InputDispatcher::doNotifyANRLockedInterruptible);
3831 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003832 commandEntry->inputChannel = windowHandle != nullptr ?
3833 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003834 commandEntry->reason = reason;
3835}
3836
3837void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3838 CommandEntry* commandEntry) {
3839 mLock.unlock();
3840
3841 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3842
3843 mLock.lock();
3844}
3845
3846void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3847 CommandEntry* commandEntry) {
3848 sp<Connection> connection = commandEntry->connection;
3849
3850 if (connection->status != Connection::STATUS_ZOMBIE) {
3851 mLock.unlock();
3852
Robert Carr803535b2018-08-02 16:38:15 -07003853 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854
3855 mLock.lock();
3856 }
3857}
3858
3859void InputDispatcher::doNotifyANRLockedInterruptible(
3860 CommandEntry* commandEntry) {
3861 mLock.unlock();
3862
3863 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003864 commandEntry->inputApplicationHandle,
3865 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866 commandEntry->reason);
3867
3868 mLock.lock();
3869
3870 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003871 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003872}
3873
3874void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3875 CommandEntry* commandEntry) {
3876 KeyEntry* entry = commandEntry->keyEntry;
3877
3878 KeyEvent event;
3879 initializeKeyEvent(&event, entry);
3880
3881 mLock.unlock();
3882
Michael Wright2b3c3302018-03-02 17:19:13 +00003883 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003884 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3885 commandEntry->inputChannel->getToken() : nullptr;
3886 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003888 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3889 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3890 std::to_string(t.duration().count()).c_str());
3891 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892
3893 mLock.lock();
3894
3895 if (delay < 0) {
3896 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3897 } else if (!delay) {
3898 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3899 } else {
3900 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3901 entry->interceptKeyWakeupTime = now() + delay;
3902 }
3903 entry->release();
3904}
3905
3906void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3907 CommandEntry* commandEntry) {
3908 sp<Connection> connection = commandEntry->connection;
3909 nsecs_t finishTime = commandEntry->eventTime;
3910 uint32_t seq = commandEntry->seq;
3911 bool handled = commandEntry->handled;
3912
3913 // Handle post-event policy actions.
3914 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3915 if (dispatchEntry) {
3916 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3917 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003918 std::string msg =
3919 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003920 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003922 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 }
3924
3925 bool restartEvent;
3926 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3927 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3928 restartEvent = afterKeyEventLockedInterruptible(connection,
3929 dispatchEntry, keyEntry, handled);
3930 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3931 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3932 restartEvent = afterMotionEventLockedInterruptible(connection,
3933 dispatchEntry, motionEntry, handled);
3934 } else {
3935 restartEvent = false;
3936 }
3937
3938 // Dequeue the event and start the next cycle.
3939 // Note that because the lock might have been released, it is possible that the
3940 // contents of the wait queue to have been drained, so we need to double-check
3941 // a few things.
3942 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3943 connection->waitQueue.dequeue(dispatchEntry);
3944 traceWaitQueueLengthLocked(connection);
3945 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3946 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3947 traceOutboundQueueLengthLocked(connection);
3948 } else {
3949 releaseDispatchEntryLocked(dispatchEntry);
3950 }
3951 }
3952
3953 // Start the next dispatch cycle for this connection.
3954 startDispatchCycleLocked(now(), connection);
3955 }
3956}
3957
3958bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3959 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3960 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3961 // Get the fallback key state.
3962 // Clear it out after dispatching the UP.
3963 int32_t originalKeyCode = keyEntry->keyCode;
3964 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3965 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3966 connection->inputState.removeFallbackKey(originalKeyCode);
3967 }
3968
3969 if (handled || !dispatchEntry->hasForegroundTarget()) {
3970 // If the application handles the original key for which we previously
3971 // generated a fallback or if the window is not a foreground window,
3972 // then cancel the associated fallback key, if any.
3973 if (fallbackKeyCode != -1) {
3974 // Dispatch the unhandled key to the policy with the cancel flag.
3975#if DEBUG_OUTBOUND_EVENT_DETAILS
3976 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3977 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3978 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3979 keyEntry->policyFlags);
3980#endif
3981 KeyEvent event;
3982 initializeKeyEvent(&event, keyEntry);
3983 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3984
3985 mLock.unlock();
3986
Robert Carr803535b2018-08-02 16:38:15 -07003987 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 &event, keyEntry->policyFlags, &event);
3989
3990 mLock.lock();
3991
3992 // Cancel the fallback key.
3993 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3994 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3995 "application handled the original non-fallback key "
3996 "or is no longer a foreground target, "
3997 "canceling previously dispatched fallback key");
3998 options.keyCode = fallbackKeyCode;
3999 synthesizeCancelationEventsForConnectionLocked(connection, options);
4000 }
4001 connection->inputState.removeFallbackKey(originalKeyCode);
4002 }
4003 } else {
4004 // If the application did not handle a non-fallback key, first check
4005 // that we are in a good state to perform unhandled key event processing
4006 // Then ask the policy what to do with it.
4007 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4008 && keyEntry->repeatCount == 0;
4009 if (fallbackKeyCode == -1 && !initialDown) {
4010#if DEBUG_OUTBOUND_EVENT_DETAILS
4011 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4012 "since this is not an initial down. "
4013 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4014 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4015 keyEntry->policyFlags);
4016#endif
4017 return false;
4018 }
4019
4020 // Dispatch the unhandled key to the policy.
4021#if DEBUG_OUTBOUND_EVENT_DETAILS
4022 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4023 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4024 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4025 keyEntry->policyFlags);
4026#endif
4027 KeyEvent event;
4028 initializeKeyEvent(&event, keyEntry);
4029
4030 mLock.unlock();
4031
Robert Carr803535b2018-08-02 16:38:15 -07004032 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004033 &event, keyEntry->policyFlags, &event);
4034
4035 mLock.lock();
4036
4037 if (connection->status != Connection::STATUS_NORMAL) {
4038 connection->inputState.removeFallbackKey(originalKeyCode);
4039 return false;
4040 }
4041
4042 // Latch the fallback keycode for this key on an initial down.
4043 // The fallback keycode cannot change at any other point in the lifecycle.
4044 if (initialDown) {
4045 if (fallback) {
4046 fallbackKeyCode = event.getKeyCode();
4047 } else {
4048 fallbackKeyCode = AKEYCODE_UNKNOWN;
4049 }
4050 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4051 }
4052
4053 ALOG_ASSERT(fallbackKeyCode != -1);
4054
4055 // Cancel the fallback key if the policy decides not to send it anymore.
4056 // We will continue to dispatch the key to the policy but we will no
4057 // longer dispatch a fallback key to the application.
4058 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4059 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4060#if DEBUG_OUTBOUND_EVENT_DETAILS
4061 if (fallback) {
4062 ALOGD("Unhandled key event: Policy requested to send key %d"
4063 "as a fallback for %d, but on the DOWN it had requested "
4064 "to send %d instead. Fallback canceled.",
4065 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4066 } else {
4067 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4068 "but on the DOWN it had requested to send %d. "
4069 "Fallback canceled.",
4070 originalKeyCode, fallbackKeyCode);
4071 }
4072#endif
4073
4074 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4075 "canceling fallback, policy no longer desires it");
4076 options.keyCode = fallbackKeyCode;
4077 synthesizeCancelationEventsForConnectionLocked(connection, options);
4078
4079 fallback = false;
4080 fallbackKeyCode = AKEYCODE_UNKNOWN;
4081 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4082 connection->inputState.setFallbackKey(originalKeyCode,
4083 fallbackKeyCode);
4084 }
4085 }
4086
4087#if DEBUG_OUTBOUND_EVENT_DETAILS
4088 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004089 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4091 connection->inputState.getFallbackKeys();
4092 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004093 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094 fallbackKeys.valueAt(i));
4095 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07004096 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004097 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 }
4099#endif
4100
4101 if (fallback) {
4102 // Restart the dispatch cycle using the fallback key.
4103 keyEntry->eventTime = event.getEventTime();
4104 keyEntry->deviceId = event.getDeviceId();
4105 keyEntry->source = event.getSource();
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004106 keyEntry->displayId = event.getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4108 keyEntry->keyCode = fallbackKeyCode;
4109 keyEntry->scanCode = event.getScanCode();
4110 keyEntry->metaState = event.getMetaState();
4111 keyEntry->repeatCount = event.getRepeatCount();
4112 keyEntry->downTime = event.getDownTime();
4113 keyEntry->syntheticRepeat = false;
4114
4115#if DEBUG_OUTBOUND_EVENT_DETAILS
4116 ALOGD("Unhandled key event: Dispatching fallback key. "
4117 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4118 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4119#endif
4120 return true; // restart the event
4121 } else {
4122#if DEBUG_OUTBOUND_EVENT_DETAILS
4123 ALOGD("Unhandled key event: No fallback key.");
4124#endif
4125 }
4126 }
4127 }
4128 return false;
4129}
4130
4131bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4132 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4133 return false;
4134}
4135
4136void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4137 mLock.unlock();
4138
4139 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4140
4141 mLock.lock();
4142}
4143
4144void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004145 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4147 entry->downTime, entry->eventTime);
4148}
4149
4150void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4151 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4152 // TODO Write some statistics about how long we spend waiting.
4153}
4154
4155void InputDispatcher::traceInboundQueueLengthLocked() {
4156 if (ATRACE_ENABLED()) {
4157 ATRACE_INT("iq", mInboundQueue.count());
4158 }
4159}
4160
4161void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4162 if (ATRACE_ENABLED()) {
4163 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004164 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 ATRACE_INT(counterName, connection->outboundQueue.count());
4166 }
4167}
4168
4169void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4170 if (ATRACE_ENABLED()) {
4171 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004172 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 ATRACE_INT(counterName, connection->waitQueue.count());
4174 }
4175}
4176
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004177void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 AutoMutex _l(mLock);
4179
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004180 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 dumpDispatchStateLocked(dump);
4182
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004183 if (!mLastANRState.empty()) {
4184 dump += "\nInput Dispatcher State at time of last ANR:\n";
4185 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 }
4187}
4188
4189void InputDispatcher::monitor() {
4190 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4191 mLock.lock();
4192 mLooper->wake();
4193 mDispatcherIsAliveCondition.wait(mLock);
4194 mLock.unlock();
4195}
4196
4197
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198// --- InputDispatcher::InjectionState ---
4199
4200InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4201 refCount(1),
4202 injectorPid(injectorPid), injectorUid(injectorUid),
4203 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4204 pendingForegroundDispatches(0) {
4205}
4206
4207InputDispatcher::InjectionState::~InjectionState() {
4208}
4209
4210void InputDispatcher::InjectionState::release() {
4211 refCount -= 1;
4212 if (refCount == 0) {
4213 delete this;
4214 } else {
4215 ALOG_ASSERT(refCount > 0);
4216 }
4217}
4218
4219
4220// --- InputDispatcher::EventEntry ---
4221
4222InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4223 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
Yi Kong9b14ac62018-07-17 13:48:38 -07004224 injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225}
4226
4227InputDispatcher::EventEntry::~EventEntry() {
4228 releaseInjectionState();
4229}
4230
4231void InputDispatcher::EventEntry::release() {
4232 refCount -= 1;
4233 if (refCount == 0) {
4234 delete this;
4235 } else {
4236 ALOG_ASSERT(refCount > 0);
4237 }
4238}
4239
4240void InputDispatcher::EventEntry::releaseInjectionState() {
4241 if (injectionState) {
4242 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004243 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 }
4245}
4246
4247
4248// --- InputDispatcher::ConfigurationChangedEntry ---
4249
4250InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4251 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4252}
4253
4254InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4255}
4256
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004257void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4258 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259}
4260
4261
4262// --- InputDispatcher::DeviceResetEntry ---
4263
4264InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4265 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4266 deviceId(deviceId) {
4267}
4268
4269InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4270}
4271
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004272void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4273 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 deviceId, policyFlags);
4275}
4276
4277
4278// --- InputDispatcher::KeyEntry ---
4279
4280InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004281 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4283 int32_t repeatCount, nsecs_t downTime) :
4284 EventEntry(TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004285 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4287 repeatCount(repeatCount), downTime(downTime),
4288 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4289 interceptKeyWakeupTime(0) {
4290}
4291
4292InputDispatcher::KeyEntry::~KeyEntry() {
4293}
4294
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004295void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004296 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4298 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004299 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004300 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301}
4302
4303void InputDispatcher::KeyEntry::recycle() {
4304 releaseInjectionState();
4305
4306 dispatchInProgress = false;
4307 syntheticRepeat = false;
4308 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4309 interceptKeyWakeupTime = 0;
4310}
4311
4312
4313// --- InputDispatcher::MotionEntry ---
4314
Michael Wright7b159c92015-05-14 14:48:03 +01004315InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004316 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4317 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004318 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4319 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004320 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004321 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4322 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4324 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004325 deviceId(deviceId), source(source), displayId(displayId), action(action),
4326 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004327 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004328 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 for (uint32_t i = 0; i < pointerCount; i++) {
4330 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4331 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004332 if (xOffset || yOffset) {
4333 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4334 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 }
4336}
4337
4338InputDispatcher::MotionEntry::~MotionEntry() {
4339}
4340
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004341void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004342 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004343 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004344 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004345 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4346 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4347
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 for (uint32_t i = 0; i < pointerCount; i++) {
4349 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004350 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004352 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353 pointerCoords[i].getX(), pointerCoords[i].getY());
4354 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004355 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356}
4357
4358
4359// --- InputDispatcher::DispatchEntry ---
4360
4361volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4362
4363InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4364 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4365 seq(nextSeq()),
4366 eventEntry(eventEntry), targetFlags(targetFlags),
4367 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4368 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4369 eventEntry->refCount += 1;
4370}
4371
4372InputDispatcher::DispatchEntry::~DispatchEntry() {
4373 eventEntry->release();
4374}
4375
4376uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4377 // Sequence number 0 is reserved and will never be returned.
4378 uint32_t seq;
4379 do {
4380 seq = android_atomic_inc(&sNextSeqAtomic);
4381 } while (!seq);
4382 return seq;
4383}
4384
4385
4386// --- InputDispatcher::InputState ---
4387
4388InputDispatcher::InputState::InputState() {
4389}
4390
4391InputDispatcher::InputState::~InputState() {
4392}
4393
4394bool InputDispatcher::InputState::isNeutral() const {
4395 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4396}
4397
4398bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4399 int32_t displayId) const {
4400 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4401 const MotionMemento& memento = mMotionMementos.itemAt(i);
4402 if (memento.deviceId == deviceId
4403 && memento.source == source
4404 && memento.displayId == displayId
4405 && memento.hovering) {
4406 return true;
4407 }
4408 }
4409 return false;
4410}
4411
4412bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4413 int32_t action, int32_t flags) {
4414 switch (action) {
4415 case AKEY_EVENT_ACTION_UP: {
4416 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4417 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4418 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4419 mFallbackKeys.removeItemsAt(i);
4420 } else {
4421 i += 1;
4422 }
4423 }
4424 }
4425 ssize_t index = findKeyMemento(entry);
4426 if (index >= 0) {
4427 mKeyMementos.removeAt(index);
4428 return true;
4429 }
4430 /* FIXME: We can't just drop the key up event because that prevents creating
4431 * popup windows that are automatically shown when a key is held and then
4432 * dismissed when the key is released. The problem is that the popup will
4433 * not have received the original key down, so the key up will be considered
4434 * to be inconsistent with its observed state. We could perhaps handle this
4435 * by synthesizing a key down but that will cause other problems.
4436 *
4437 * So for now, allow inconsistent key up events to be dispatched.
4438 *
4439#if DEBUG_OUTBOUND_EVENT_DETAILS
4440 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4441 "keyCode=%d, scanCode=%d",
4442 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4443#endif
4444 return false;
4445 */
4446 return true;
4447 }
4448
4449 case AKEY_EVENT_ACTION_DOWN: {
4450 ssize_t index = findKeyMemento(entry);
4451 if (index >= 0) {
4452 mKeyMementos.removeAt(index);
4453 }
4454 addKeyMemento(entry, flags);
4455 return true;
4456 }
4457
4458 default:
4459 return true;
4460 }
4461}
4462
4463bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4464 int32_t action, int32_t flags) {
4465 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4466 switch (actionMasked) {
4467 case AMOTION_EVENT_ACTION_UP:
4468 case AMOTION_EVENT_ACTION_CANCEL: {
4469 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4470 if (index >= 0) {
4471 mMotionMementos.removeAt(index);
4472 return true;
4473 }
4474#if DEBUG_OUTBOUND_EVENT_DETAILS
4475 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004476 "displayId=%" PRId32 ", actionMasked=%d",
4477 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478#endif
4479 return false;
4480 }
4481
4482 case AMOTION_EVENT_ACTION_DOWN: {
4483 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4484 if (index >= 0) {
4485 mMotionMementos.removeAt(index);
4486 }
4487 addMotionMemento(entry, flags, false /*hovering*/);
4488 return true;
4489 }
4490
4491 case AMOTION_EVENT_ACTION_POINTER_UP:
4492 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4493 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004494 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4495 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4496 // generate cancellation events for these since they're based in relative rather than
4497 // absolute units.
4498 return true;
4499 }
4500
Michael Wrightd02c5b62014-02-10 15:10:22 -08004501 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004502
4503 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4504 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4505 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4506 // other value and we need to track the motion so we can send cancellation events for
4507 // anything generating fallback events (e.g. DPad keys for joystick movements).
4508 if (index >= 0) {
4509 if (entry->pointerCoords[0].isEmpty()) {
4510 mMotionMementos.removeAt(index);
4511 } else {
4512 MotionMemento& memento = mMotionMementos.editItemAt(index);
4513 memento.setPointers(entry);
4514 }
4515 } else if (!entry->pointerCoords[0].isEmpty()) {
4516 addMotionMemento(entry, flags, false /*hovering*/);
4517 }
4518
4519 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4520 return true;
4521 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522 if (index >= 0) {
4523 MotionMemento& memento = mMotionMementos.editItemAt(index);
4524 memento.setPointers(entry);
4525 return true;
4526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004527#if DEBUG_OUTBOUND_EVENT_DETAILS
4528 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004529 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4530 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004531#endif
4532 return false;
4533 }
4534
4535 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4536 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4537 if (index >= 0) {
4538 mMotionMementos.removeAt(index);
4539 return true;
4540 }
4541#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004542 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4543 "displayId=%" PRId32,
4544 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545#endif
4546 return false;
4547 }
4548
4549 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4550 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4551 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4552 if (index >= 0) {
4553 mMotionMementos.removeAt(index);
4554 }
4555 addMotionMemento(entry, flags, true /*hovering*/);
4556 return true;
4557 }
4558
4559 default:
4560 return true;
4561 }
4562}
4563
4564ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4565 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4566 const KeyMemento& memento = mKeyMementos.itemAt(i);
4567 if (memento.deviceId == entry->deviceId
4568 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004569 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 && memento.keyCode == entry->keyCode
4571 && memento.scanCode == entry->scanCode) {
4572 return i;
4573 }
4574 }
4575 return -1;
4576}
4577
4578ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4579 bool hovering) const {
4580 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4581 const MotionMemento& memento = mMotionMementos.itemAt(i);
4582 if (memento.deviceId == entry->deviceId
4583 && memento.source == entry->source
4584 && memento.displayId == entry->displayId
4585 && memento.hovering == hovering) {
4586 return i;
4587 }
4588 }
4589 return -1;
4590}
4591
4592void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4593 mKeyMementos.push();
4594 KeyMemento& memento = mKeyMementos.editTop();
4595 memento.deviceId = entry->deviceId;
4596 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004597 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598 memento.keyCode = entry->keyCode;
4599 memento.scanCode = entry->scanCode;
4600 memento.metaState = entry->metaState;
4601 memento.flags = flags;
4602 memento.downTime = entry->downTime;
4603 memento.policyFlags = entry->policyFlags;
4604}
4605
4606void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4607 int32_t flags, bool hovering) {
4608 mMotionMementos.push();
4609 MotionMemento& memento = mMotionMementos.editTop();
4610 memento.deviceId = entry->deviceId;
4611 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004612 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613 memento.flags = flags;
4614 memento.xPrecision = entry->xPrecision;
4615 memento.yPrecision = entry->yPrecision;
4616 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617 memento.setPointers(entry);
4618 memento.hovering = hovering;
4619 memento.policyFlags = entry->policyFlags;
4620}
4621
4622void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4623 pointerCount = entry->pointerCount;
4624 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4625 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4626 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4627 }
4628}
4629
4630void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4631 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4632 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4633 const KeyMemento& memento = mKeyMementos.itemAt(i);
4634 if (shouldCancelKey(memento, options)) {
4635 outEvents.push(new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004636 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4638 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4639 }
4640 }
4641
4642 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4643 const MotionMemento& memento = mMotionMementos.itemAt(i);
4644 if (shouldCancelMotion(memento, options)) {
4645 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004646 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647 memento.hovering
4648 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4649 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004650 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004652 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4653 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654 }
4655 }
4656}
4657
4658void InputDispatcher::InputState::clear() {
4659 mKeyMementos.clear();
4660 mMotionMementos.clear();
4661 mFallbackKeys.clear();
4662}
4663
4664void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4665 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4666 const MotionMemento& memento = mMotionMementos.itemAt(i);
4667 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4668 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4669 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4670 if (memento.deviceId == otherMemento.deviceId
4671 && memento.source == otherMemento.source
4672 && memento.displayId == otherMemento.displayId) {
4673 other.mMotionMementos.removeAt(j);
4674 } else {
4675 j += 1;
4676 }
4677 }
4678 other.mMotionMementos.push(memento);
4679 }
4680 }
4681}
4682
4683int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4684 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4685 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4686}
4687
4688void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4689 int32_t fallbackKeyCode) {
4690 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4691 if (index >= 0) {
4692 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4693 } else {
4694 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4695 }
4696}
4697
4698void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4699 mFallbackKeys.removeItem(originalKeyCode);
4700}
4701
4702bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4703 const CancelationOptions& options) {
4704 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4705 return false;
4706 }
4707
4708 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4709 return false;
4710 }
4711
4712 switch (options.mode) {
4713 case CancelationOptions::CANCEL_ALL_EVENTS:
4714 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4715 return true;
4716 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4717 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004718 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4719 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004720 default:
4721 return false;
4722 }
4723}
4724
4725bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4726 const CancelationOptions& options) {
4727 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4728 return false;
4729 }
4730
4731 switch (options.mode) {
4732 case CancelationOptions::CANCEL_ALL_EVENTS:
4733 return true;
4734 case CancelationOptions::CANCEL_POINTER_EVENTS:
4735 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4736 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4737 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004738 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4739 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 default:
4741 return false;
4742 }
4743}
4744
4745
4746// --- InputDispatcher::Connection ---
4747
Robert Carr803535b2018-08-02 16:38:15 -07004748InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4749 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750 monitor(monitor),
4751 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4752}
4753
4754InputDispatcher::Connection::~Connection() {
4755}
4756
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004757const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004758 if (inputChannel != nullptr) {
4759 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 }
4761 if (monitor) {
4762 return "monitor";
4763 }
4764 return "?";
4765}
4766
4767const char* InputDispatcher::Connection::getStatusLabel() const {
4768 switch (status) {
4769 case STATUS_NORMAL:
4770 return "NORMAL";
4771
4772 case STATUS_BROKEN:
4773 return "BROKEN";
4774
4775 case STATUS_ZOMBIE:
4776 return "ZOMBIE";
4777
4778 default:
4779 return "UNKNOWN";
4780 }
4781}
4782
4783InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004784 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 if (entry->seq == seq) {
4786 return entry;
4787 }
4788 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004789 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790}
4791
4792
4793// --- InputDispatcher::CommandEntry ---
4794
4795InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004796 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 seq(0), handled(false) {
4798}
4799
4800InputDispatcher::CommandEntry::~CommandEntry() {
4801}
4802
4803
4804// --- InputDispatcher::TouchState ---
4805
4806InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004807 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808}
4809
4810InputDispatcher::TouchState::~TouchState() {
4811}
4812
4813void InputDispatcher::TouchState::reset() {
4814 down = false;
4815 split = false;
4816 deviceId = -1;
4817 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004818 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 windows.clear();
4820}
4821
4822void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4823 down = other.down;
4824 split = other.split;
4825 deviceId = other.deviceId;
4826 source = other.source;
4827 displayId = other.displayId;
4828 windows = other.windows;
4829}
4830
4831void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4832 int32_t targetFlags, BitSet32 pointerIds) {
4833 if (targetFlags & InputTarget::FLAG_SPLIT) {
4834 split = true;
4835 }
4836
4837 for (size_t i = 0; i < windows.size(); i++) {
4838 TouchedWindow& touchedWindow = windows.editItemAt(i);
4839 if (touchedWindow.windowHandle == windowHandle) {
4840 touchedWindow.targetFlags |= targetFlags;
4841 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4842 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4843 }
4844 touchedWindow.pointerIds.value |= pointerIds.value;
4845 return;
4846 }
4847 }
4848
4849 windows.push();
4850
4851 TouchedWindow& touchedWindow = windows.editTop();
4852 touchedWindow.windowHandle = windowHandle;
4853 touchedWindow.targetFlags = targetFlags;
4854 touchedWindow.pointerIds = pointerIds;
4855}
4856
4857void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4858 for (size_t i = 0; i < windows.size(); i++) {
4859 if (windows.itemAt(i).windowHandle == windowHandle) {
4860 windows.removeAt(i);
4861 return;
4862 }
4863 }
4864}
4865
Robert Carr803535b2018-08-02 16:38:15 -07004866void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4867 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004868 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004869 windows.removeAt(i);
4870 return;
4871 }
4872 }
4873}
4874
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4876 for (size_t i = 0 ; i < windows.size(); ) {
4877 TouchedWindow& window = windows.editItemAt(i);
4878 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4879 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4880 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4881 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4882 i += 1;
4883 } else {
4884 windows.removeAt(i);
4885 }
4886 }
4887}
4888
4889sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4890 for (size_t i = 0; i < windows.size(); i++) {
4891 const TouchedWindow& window = windows.itemAt(i);
4892 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4893 return window.windowHandle;
4894 }
4895 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004896 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897}
4898
4899bool InputDispatcher::TouchState::isSlippery() const {
4900 // Must have exactly one foreground window.
4901 bool haveSlipperyForegroundWindow = false;
4902 for (size_t i = 0; i < windows.size(); i++) {
4903 const TouchedWindow& window = windows.itemAt(i);
4904 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4905 if (haveSlipperyForegroundWindow
4906 || !(window.windowHandle->getInfo()->layoutParamsFlags
4907 & InputWindowInfo::FLAG_SLIPPERY)) {
4908 return false;
4909 }
4910 haveSlipperyForegroundWindow = true;
4911 }
4912 }
4913 return haveSlipperyForegroundWindow;
4914}
4915
4916
4917// --- InputDispatcherThread ---
4918
4919InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4920 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4921}
4922
4923InputDispatcherThread::~InputDispatcherThread() {
4924}
4925
4926bool InputDispatcherThread::threadLoop() {
4927 mDispatcher->dispatchOnce();
4928 return true;
4929}
4930
4931} // namespace android