blob: 93a8ac0fff7b4096e4b08532a0b4a8f9a0838525 [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 }
Robert Carrf759f162018-11-13 12:57:11 -08003129
3130 if (mFocusedDisplayId == displayId) {
3131 onFocusChangedLocked(newFocusedWindowHandle);
3132 }
3133
Michael Wrightd02c5b62014-02-10 15:10:22 -08003134 }
3135
Arthur Hungb92218b2018-08-14 12:00:21 +08003136 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3137 if (stateIndex >= 0) {
3138 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003139 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003140 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003141 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003143 ALOGD("Touched window was removed: %s in display %" PRId32,
3144 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003146 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003147 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003148 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003149 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3150 "touched window was removed");
3151 synthesizeCancelationEventsForInputChannelLocked(
3152 touchedInputChannel, options);
3153 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003154 state.windows.removeAt(i);
3155 } else {
3156 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 }
3159 }
3160
3161 // Release information for windows that are no longer present.
3162 // This ensures that unused input channels are released promptly.
3163 // Otherwise, they might stick around until the window handle is destroyed
3164 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003165 size_t numWindows = oldWindowHandles.size();
3166 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003168 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003170 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003172 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173 }
3174 }
3175 } // release lock
3176
3177 // Wake up poll loop since it may need to make new input dispatching choices.
3178 mLooper->wake();
3179}
3180
3181void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003182 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003184 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185#endif
3186 { // acquire lock
3187 AutoMutex _l(mLock);
3188
Tiger Huang721e26f2018-07-24 22:26:19 +08003189 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3190 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003191 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003192 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3193 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003195 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003197 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003199 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003201 oldFocusedApplicationHandle->releaseInfo();
3202 oldFocusedApplicationHandle.clear();
3203 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 }
3205
3206#if DEBUG_FOCUS
3207 //logDispatchStateLocked();
3208#endif
3209 } // release lock
3210
3211 // Wake up poll loop since it may need to make new input dispatching choices.
3212 mLooper->wake();
3213}
3214
Tiger Huang721e26f2018-07-24 22:26:19 +08003215/**
3216 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3217 * the display not specified.
3218 *
3219 * We track any unreleased events for each window. If a window loses the ability to receive the
3220 * released event, we will send a cancel event to it. So when the focused display is changed, we
3221 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3222 * display. The display-specified events won't be affected.
3223 */
3224void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3225#if DEBUG_FOCUS
3226 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3227#endif
3228 { // acquire lock
3229 AutoMutex _l(mLock);
3230
3231 if (mFocusedDisplayId != displayId) {
3232 sp<InputWindowHandle> oldFocusedWindowHandle =
3233 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3234 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003235 sp<InputChannel> inputChannel =
3236 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003237 if (inputChannel != nullptr) {
3238 CancelationOptions options(
3239 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3240 "The display which contains this window no longer has focus.");
3241 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3242 }
3243 }
3244 mFocusedDisplayId = displayId;
3245
3246 // Sanity check
3247 sp<InputWindowHandle> newFocusedWindowHandle =
3248 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Robert Carrf759f162018-11-13 12:57:11 -08003249 onFocusChangedLocked(newFocusedWindowHandle);
3250
Tiger Huang721e26f2018-07-24 22:26:19 +08003251 if (newFocusedWindowHandle == nullptr) {
3252 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3253 if (!mFocusedWindowHandlesByDisplay.empty()) {
3254 ALOGE("But another display has a focused window:");
3255 for (auto& it : mFocusedWindowHandlesByDisplay) {
3256 const int32_t displayId = it.first;
3257 const sp<InputWindowHandle>& windowHandle = it.second;
3258 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3259 displayId, windowHandle->getName().c_str());
3260 }
3261 }
3262 }
3263 }
3264
3265#if DEBUG_FOCUS
3266 logDispatchStateLocked();
3267#endif
3268 } // release lock
3269
3270 // Wake up poll loop since it may need to make new input dispatching choices.
3271 mLooper->wake();
3272}
3273
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3275#if DEBUG_FOCUS
3276 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3277#endif
3278
3279 bool changed;
3280 { // acquire lock
3281 AutoMutex _l(mLock);
3282
3283 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3284 if (mDispatchFrozen && !frozen) {
3285 resetANRTimeoutsLocked();
3286 }
3287
3288 if (mDispatchEnabled && !enabled) {
3289 resetAndDropEverythingLocked("dispatcher is being disabled");
3290 }
3291
3292 mDispatchEnabled = enabled;
3293 mDispatchFrozen = frozen;
3294 changed = true;
3295 } else {
3296 changed = false;
3297 }
3298
3299#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003300 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301#endif
3302 } // release lock
3303
3304 if (changed) {
3305 // Wake up poll loop since it may need to make new input dispatching choices.
3306 mLooper->wake();
3307 }
3308}
3309
3310void InputDispatcher::setInputFilterEnabled(bool enabled) {
3311#if DEBUG_FOCUS
3312 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3313#endif
3314
3315 { // acquire lock
3316 AutoMutex _l(mLock);
3317
3318 if (mInputFilterEnabled == enabled) {
3319 return;
3320 }
3321
3322 mInputFilterEnabled = enabled;
3323 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3324 } // release lock
3325
3326 // Wake up poll loop since there might be work to do to drop everything.
3327 mLooper->wake();
3328}
3329
3330bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3331 const sp<InputChannel>& toChannel) {
3332#if DEBUG_FOCUS
3333 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003334 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335#endif
3336 { // acquire lock
3337 AutoMutex _l(mLock);
3338
3339 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3340 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07003341 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342#if DEBUG_FOCUS
3343 ALOGD("Cannot transfer focus because from or to window not found.");
3344#endif
3345 return false;
3346 }
3347 if (fromWindowHandle == toWindowHandle) {
3348#if DEBUG_FOCUS
3349 ALOGD("Trivial transfer to same window.");
3350#endif
3351 return true;
3352 }
3353 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3354#if DEBUG_FOCUS
3355 ALOGD("Cannot transfer focus because windows are on different displays.");
3356#endif
3357 return false;
3358 }
3359
3360 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003361 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3362 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3363 for (size_t i = 0; i < state.windows.size(); i++) {
3364 const TouchedWindow& touchedWindow = state.windows[i];
3365 if (touchedWindow.windowHandle == fromWindowHandle) {
3366 int32_t oldTargetFlags = touchedWindow.targetFlags;
3367 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368
Jeff Brownf086ddb2014-02-11 14:28:48 -08003369 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370
Jeff Brownf086ddb2014-02-11 14:28:48 -08003371 int32_t newTargetFlags = oldTargetFlags
3372 & (InputTarget::FLAG_FOREGROUND
3373 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3374 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003375
Jeff Brownf086ddb2014-02-11 14:28:48 -08003376 found = true;
3377 goto Found;
3378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 }
3380 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003381Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382
3383 if (! found) {
3384#if DEBUG_FOCUS
3385 ALOGD("Focus transfer failed because from window did not have focus.");
3386#endif
3387 return false;
3388 }
3389
3390 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3391 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3392 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3393 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3394 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3395
3396 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3397 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3398 "transferring touch focus from this window to another window");
3399 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3400 }
3401
3402#if DEBUG_FOCUS
3403 logDispatchStateLocked();
3404#endif
3405 } // release lock
3406
3407 // Wake up poll loop since it may need to make new input dispatching choices.
3408 mLooper->wake();
3409 return true;
3410}
3411
3412void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3413#if DEBUG_FOCUS
3414 ALOGD("Resetting and dropping all events (%s).", reason);
3415#endif
3416
3417 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3418 synthesizeCancelationEventsForAllConnectionsLocked(options);
3419
3420 resetKeyRepeatLocked();
3421 releasePendingEventLocked();
3422 drainInboundQueueLocked();
3423 resetANRTimeoutsLocked();
3424
Jeff Brownf086ddb2014-02-11 14:28:48 -08003425 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003427 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428}
3429
3430void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003431 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 dumpDispatchStateLocked(dump);
3433
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003434 std::istringstream stream(dump);
3435 std::string line;
3436
3437 while (std::getline(stream, line, '\n')) {
3438 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439 }
3440}
3441
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003442void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3443 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3444 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003445 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446
Tiger Huang721e26f2018-07-24 22:26:19 +08003447 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3448 dump += StringPrintf(INDENT "FocusedApplications:\n");
3449 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3450 const int32_t displayId = it.first;
3451 const sp<InputApplicationHandle>& applicationHandle = it.second;
3452 dump += StringPrintf(
3453 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3454 displayId,
3455 applicationHandle->getName().c_str(),
3456 applicationHandle->getDispatchingTimeout(
3457 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3458 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003460 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003462
3463 if (!mFocusedWindowHandlesByDisplay.empty()) {
3464 dump += StringPrintf(INDENT "FocusedWindows:\n");
3465 for (auto& it : mFocusedWindowHandlesByDisplay) {
3466 const int32_t displayId = it.first;
3467 const sp<InputWindowHandle>& windowHandle = it.second;
3468 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3469 displayId, windowHandle->getName().c_str());
3470 }
3471 } else {
3472 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474
Jeff Brownf086ddb2014-02-11 14:28:48 -08003475 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003476 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003477 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3478 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003479 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003480 state.displayId, toString(state.down), toString(state.split),
3481 state.deviceId, state.source);
3482 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003483 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003484 for (size_t i = 0; i < state.windows.size(); i++) {
3485 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003486 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3487 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003488 touchedWindow.pointerIds.value,
3489 touchedWindow.targetFlags);
3490 }
3491 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003492 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494 }
3495 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003496 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003497 }
3498
Arthur Hungb92218b2018-08-14 12:00:21 +08003499 if (!mWindowHandlesByDisplay.empty()) {
3500 for (auto& it : mWindowHandlesByDisplay) {
3501 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003502 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003503 if (!windowHandles.isEmpty()) {
3504 dump += INDENT2 "Windows:\n";
3505 for (size_t i = 0; i < windowHandles.size(); i++) {
3506 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3507 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508
Arthur Hungb92218b2018-08-14 12:00:21 +08003509 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3510 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3511 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3512 "frame=[%d,%d][%d,%d], scale=%f, "
3513 "touchableRegion=",
3514 i, windowInfo->name.c_str(), windowInfo->displayId,
3515 toString(windowInfo->paused),
3516 toString(windowInfo->hasFocus),
3517 toString(windowInfo->hasWallpaper),
3518 toString(windowInfo->visible),
3519 toString(windowInfo->canReceiveKeys),
3520 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3521 windowInfo->layer,
3522 windowInfo->frameLeft, windowInfo->frameTop,
3523 windowInfo->frameRight, windowInfo->frameBottom,
3524 windowInfo->scaleFactor);
3525 dumpRegion(dump, windowInfo->touchableRegion);
3526 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3527 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3528 windowInfo->ownerPid, windowInfo->ownerUid,
3529 windowInfo->dispatchingTimeout / 1000000.0);
3530 }
3531 } else {
3532 dump += INDENT2 "Windows: <none>\n";
3533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 }
3535 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003536 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 }
3538
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003539 if (!mMonitoringChannelsByDisplay.empty()) {
3540 for (auto& it : mMonitoringChannelsByDisplay) {
3541 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003542 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003543 const size_t numChannels = monitoringChannels.size();
3544 for (size_t i = 0; i < numChannels; i++) {
3545 const sp<InputChannel>& channel = monitoringChannels[i];
3546 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3547 }
3548 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003550 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 }
3552
3553 nsecs_t currentTime = now();
3554
3555 // Dump recently dispatched or dropped events from oldest to newest.
3556 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003557 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003559 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003561 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562 (currentTime - entry->eventTime) * 0.000001f);
3563 }
3564 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003565 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566 }
3567
3568 // Dump event currently being dispatched.
3569 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003570 dump += INDENT "PendingEvent:\n";
3571 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003573 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3575 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003576 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577 }
3578
3579 // Dump inbound events from oldest to newest.
3580 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003581 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003583 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003585 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 (currentTime - entry->eventTime) * 0.000001f);
3587 }
3588 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003589 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590 }
3591
Michael Wright78f24442014-08-06 15:55:28 -07003592 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003593 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003594 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3595 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3596 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003597 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003598 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3599 }
3600 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003601 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003602 }
3603
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003605 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3607 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003608 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003610 i, connection->getInputChannelName().c_str(),
3611 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 connection->getStatusLabel(), toString(connection->monitor),
3613 toString(connection->inputPublisherBlocked));
3614
3615 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003616 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 connection->outboundQueue.count());
3618 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3619 entry = entry->next) {
3620 dump.append(INDENT4);
3621 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003622 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 entry->targetFlags, entry->resolvedAction,
3624 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3625 }
3626 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003627 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 }
3629
3630 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003631 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 connection->waitQueue.count());
3633 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3634 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003635 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003637 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 "age=%0.1fms, wait=%0.1fms\n",
3639 entry->targetFlags, entry->resolvedAction,
3640 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3641 (currentTime - entry->deliveryTime) * 0.000001f);
3642 }
3643 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003644 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 }
3646 }
3647 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003648 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 }
3650
3651 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003652 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 (mAppSwitchDueTime - now()) / 1000000.0);
3654 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003655 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656 }
3657
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003658 dump += INDENT "Configuration:\n";
3659 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003661 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 mConfig.keyRepeatTimeout * 0.000001f);
3663}
3664
Robert Carr803535b2018-08-02 16:38:15 -07003665status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003667 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3668 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669#endif
3670
3671 { // acquire lock
3672 AutoMutex _l(mLock);
3673
Robert Carr4e670e52018-08-15 13:26:12 -07003674 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3675 // treat inputChannel as monitor channel for displayId.
3676 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3677 if (monitor) {
3678 inputChannel->setToken(new BBinder());
3679 }
3680
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 if (getConnectionIndexLocked(inputChannel) >= 0) {
3682 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003683 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 return BAD_VALUE;
3685 }
3686
Robert Carr803535b2018-08-02 16:38:15 -07003687 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688
3689 int fd = inputChannel->getFd();
3690 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003691 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003693 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003695 Vector<sp<InputChannel>>& monitoringChannels =
3696 mMonitoringChannelsByDisplay[displayId];
3697 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 }
3699
3700 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3701 } // release lock
3702
3703 // Wake the looper because some connections have changed.
3704 mLooper->wake();
3705 return OK;
3706}
3707
3708status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3709#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003710 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711#endif
3712
3713 { // acquire lock
3714 AutoMutex _l(mLock);
3715
3716 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3717 if (status) {
3718 return status;
3719 }
3720 } // release lock
3721
3722 // Wake the poll loop because removing the connection may have changed the current
3723 // synchronization state.
3724 mLooper->wake();
3725 return OK;
3726}
3727
3728status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3729 bool notify) {
3730 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3731 if (connectionIndex < 0) {
3732 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003733 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 return BAD_VALUE;
3735 }
3736
3737 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3738 mConnectionsByFd.removeItemsAt(connectionIndex);
3739
Robert Carr5c8a0262018-10-03 16:30:44 -07003740 mInputChannelsByToken.erase(inputChannel->getToken());
3741
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 if (connection->monitor) {
3743 removeMonitorChannelLocked(inputChannel);
3744 }
3745
3746 mLooper->removeFd(inputChannel->getFd());
3747
3748 nsecs_t currentTime = now();
3749 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3750
3751 connection->status = Connection::STATUS_ZOMBIE;
3752 return OK;
3753}
3754
3755void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003756 for (auto it = mMonitoringChannelsByDisplay.begin();
3757 it != mMonitoringChannelsByDisplay.end(); ) {
3758 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3759 const size_t numChannels = monitoringChannels.size();
3760 for (size_t i = 0; i < numChannels; i++) {
3761 if (monitoringChannels[i] == inputChannel) {
3762 monitoringChannels.removeAt(i);
3763 break;
3764 }
3765 }
3766 if (monitoringChannels.empty()) {
3767 it = mMonitoringChannelsByDisplay.erase(it);
3768 } else {
3769 ++it;
3770 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 }
3772}
3773
3774ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003775 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003776 return -1;
3777 }
3778
Robert Carr4e670e52018-08-15 13:26:12 -07003779 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3780 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3781 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3782 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 }
3784 }
Robert Carr4e670e52018-08-15 13:26:12 -07003785
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 return -1;
3787}
3788
3789void InputDispatcher::onDispatchCycleFinishedLocked(
3790 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3791 CommandEntry* commandEntry = postCommandLocked(
3792 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3793 commandEntry->connection = connection;
3794 commandEntry->eventTime = currentTime;
3795 commandEntry->seq = seq;
3796 commandEntry->handled = handled;
3797}
3798
3799void InputDispatcher::onDispatchCycleBrokenLocked(
3800 nsecs_t currentTime, const sp<Connection>& connection) {
3801 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003802 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803
3804 CommandEntry* commandEntry = postCommandLocked(
3805 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3806 commandEntry->connection = connection;
3807}
3808
Robert Carrf759f162018-11-13 12:57:11 -08003809void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& newFocus) {
3810 sp<IBinder> token = newFocus != nullptr ? newFocus->getToken() : nullptr;
3811 CommandEntry* commandEntry = postCommandLocked(
3812 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
3813 commandEntry->token = token;
3814}
3815
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816void InputDispatcher::onANRLocked(
3817 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3818 const sp<InputWindowHandle>& windowHandle,
3819 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3820 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3821 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3822 ALOGI("Application is not responding: %s. "
3823 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003824 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003825 dispatchLatency, waitDuration, reason);
3826
3827 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003828 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829 struct tm tm;
3830 localtime_r(&t, &tm);
3831 char timestr[64];
3832 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3833 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003834 mLastANRState += INDENT "ANR:\n";
3835 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3836 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3837 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3838 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3839 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3840 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 dumpDispatchStateLocked(mLastANRState);
3842
3843 CommandEntry* commandEntry = postCommandLocked(
3844 & InputDispatcher::doNotifyANRLockedInterruptible);
3845 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003846 commandEntry->inputChannel = windowHandle != nullptr ?
3847 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 commandEntry->reason = reason;
3849}
3850
3851void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3852 CommandEntry* commandEntry) {
3853 mLock.unlock();
3854
3855 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3856
3857 mLock.lock();
3858}
3859
3860void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3861 CommandEntry* commandEntry) {
3862 sp<Connection> connection = commandEntry->connection;
3863
3864 if (connection->status != Connection::STATUS_ZOMBIE) {
3865 mLock.unlock();
3866
Robert Carr803535b2018-08-02 16:38:15 -07003867 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868
3869 mLock.lock();
3870 }
3871}
3872
Robert Carrf759f162018-11-13 12:57:11 -08003873void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3874 CommandEntry* commandEntry) {
3875 sp<IBinder> token = commandEntry->token;
3876 mLock.unlock();
3877 mPolicy->notifyFocusChanged(token);
3878 mLock.lock();
3879}
3880
Michael Wrightd02c5b62014-02-10 15:10:22 -08003881void InputDispatcher::doNotifyANRLockedInterruptible(
3882 CommandEntry* commandEntry) {
3883 mLock.unlock();
3884
3885 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003886 commandEntry->inputApplicationHandle,
3887 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888 commandEntry->reason);
3889
3890 mLock.lock();
3891
3892 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003893 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894}
3895
3896void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3897 CommandEntry* commandEntry) {
3898 KeyEntry* entry = commandEntry->keyEntry;
3899
3900 KeyEvent event;
3901 initializeKeyEvent(&event, entry);
3902
3903 mLock.unlock();
3904
Michael Wright2b3c3302018-03-02 17:19:13 +00003905 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003906 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3907 commandEntry->inputChannel->getToken() : nullptr;
3908 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003910 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3911 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3912 std::to_string(t.duration().count()).c_str());
3913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914
3915 mLock.lock();
3916
3917 if (delay < 0) {
3918 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3919 } else if (!delay) {
3920 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3921 } else {
3922 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3923 entry->interceptKeyWakeupTime = now() + delay;
3924 }
3925 entry->release();
3926}
3927
3928void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3929 CommandEntry* commandEntry) {
3930 sp<Connection> connection = commandEntry->connection;
3931 nsecs_t finishTime = commandEntry->eventTime;
3932 uint32_t seq = commandEntry->seq;
3933 bool handled = commandEntry->handled;
3934
3935 // Handle post-event policy actions.
3936 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3937 if (dispatchEntry) {
3938 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3939 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003940 std::string msg =
3941 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003942 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003944 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945 }
3946
3947 bool restartEvent;
3948 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3949 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3950 restartEvent = afterKeyEventLockedInterruptible(connection,
3951 dispatchEntry, keyEntry, handled);
3952 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3953 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3954 restartEvent = afterMotionEventLockedInterruptible(connection,
3955 dispatchEntry, motionEntry, handled);
3956 } else {
3957 restartEvent = false;
3958 }
3959
3960 // Dequeue the event and start the next cycle.
3961 // Note that because the lock might have been released, it is possible that the
3962 // contents of the wait queue to have been drained, so we need to double-check
3963 // a few things.
3964 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3965 connection->waitQueue.dequeue(dispatchEntry);
3966 traceWaitQueueLengthLocked(connection);
3967 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3968 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3969 traceOutboundQueueLengthLocked(connection);
3970 } else {
3971 releaseDispatchEntryLocked(dispatchEntry);
3972 }
3973 }
3974
3975 // Start the next dispatch cycle for this connection.
3976 startDispatchCycleLocked(now(), connection);
3977 }
3978}
3979
3980bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3981 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3982 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3983 // Get the fallback key state.
3984 // Clear it out after dispatching the UP.
3985 int32_t originalKeyCode = keyEntry->keyCode;
3986 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3987 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3988 connection->inputState.removeFallbackKey(originalKeyCode);
3989 }
3990
3991 if (handled || !dispatchEntry->hasForegroundTarget()) {
3992 // If the application handles the original key for which we previously
3993 // generated a fallback or if the window is not a foreground window,
3994 // then cancel the associated fallback key, if any.
3995 if (fallbackKeyCode != -1) {
3996 // Dispatch the unhandled key to the policy with the cancel flag.
3997#if DEBUG_OUTBOUND_EVENT_DETAILS
3998 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3999 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4000 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4001 keyEntry->policyFlags);
4002#endif
4003 KeyEvent event;
4004 initializeKeyEvent(&event, keyEntry);
4005 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
4006
4007 mLock.unlock();
4008
Robert Carr803535b2018-08-02 16:38:15 -07004009 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004010 &event, keyEntry->policyFlags, &event);
4011
4012 mLock.lock();
4013
4014 // Cancel the fallback key.
4015 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
4016 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4017 "application handled the original non-fallback key "
4018 "or is no longer a foreground target, "
4019 "canceling previously dispatched fallback key");
4020 options.keyCode = fallbackKeyCode;
4021 synthesizeCancelationEventsForConnectionLocked(connection, options);
4022 }
4023 connection->inputState.removeFallbackKey(originalKeyCode);
4024 }
4025 } else {
4026 // If the application did not handle a non-fallback key, first check
4027 // that we are in a good state to perform unhandled key event processing
4028 // Then ask the policy what to do with it.
4029 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4030 && keyEntry->repeatCount == 0;
4031 if (fallbackKeyCode == -1 && !initialDown) {
4032#if DEBUG_OUTBOUND_EVENT_DETAILS
4033 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4034 "since this is not an initial down. "
4035 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4036 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4037 keyEntry->policyFlags);
4038#endif
4039 return false;
4040 }
4041
4042 // Dispatch the unhandled key to the policy.
4043#if DEBUG_OUTBOUND_EVENT_DETAILS
4044 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4045 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4046 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4047 keyEntry->policyFlags);
4048#endif
4049 KeyEvent event;
4050 initializeKeyEvent(&event, keyEntry);
4051
4052 mLock.unlock();
4053
Robert Carr803535b2018-08-02 16:38:15 -07004054 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004055 &event, keyEntry->policyFlags, &event);
4056
4057 mLock.lock();
4058
4059 if (connection->status != Connection::STATUS_NORMAL) {
4060 connection->inputState.removeFallbackKey(originalKeyCode);
4061 return false;
4062 }
4063
4064 // Latch the fallback keycode for this key on an initial down.
4065 // The fallback keycode cannot change at any other point in the lifecycle.
4066 if (initialDown) {
4067 if (fallback) {
4068 fallbackKeyCode = event.getKeyCode();
4069 } else {
4070 fallbackKeyCode = AKEYCODE_UNKNOWN;
4071 }
4072 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4073 }
4074
4075 ALOG_ASSERT(fallbackKeyCode != -1);
4076
4077 // Cancel the fallback key if the policy decides not to send it anymore.
4078 // We will continue to dispatch the key to the policy but we will no
4079 // longer dispatch a fallback key to the application.
4080 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4081 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4082#if DEBUG_OUTBOUND_EVENT_DETAILS
4083 if (fallback) {
4084 ALOGD("Unhandled key event: Policy requested to send key %d"
4085 "as a fallback for %d, but on the DOWN it had requested "
4086 "to send %d instead. Fallback canceled.",
4087 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4088 } else {
4089 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4090 "but on the DOWN it had requested to send %d. "
4091 "Fallback canceled.",
4092 originalKeyCode, fallbackKeyCode);
4093 }
4094#endif
4095
4096 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4097 "canceling fallback, policy no longer desires it");
4098 options.keyCode = fallbackKeyCode;
4099 synthesizeCancelationEventsForConnectionLocked(connection, options);
4100
4101 fallback = false;
4102 fallbackKeyCode = AKEYCODE_UNKNOWN;
4103 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4104 connection->inputState.setFallbackKey(originalKeyCode,
4105 fallbackKeyCode);
4106 }
4107 }
4108
4109#if DEBUG_OUTBOUND_EVENT_DETAILS
4110 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004111 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4113 connection->inputState.getFallbackKeys();
4114 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004115 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004116 fallbackKeys.valueAt(i));
4117 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07004118 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004119 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 }
4121#endif
4122
4123 if (fallback) {
4124 // Restart the dispatch cycle using the fallback key.
4125 keyEntry->eventTime = event.getEventTime();
4126 keyEntry->deviceId = event.getDeviceId();
4127 keyEntry->source = event.getSource();
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004128 keyEntry->displayId = event.getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4130 keyEntry->keyCode = fallbackKeyCode;
4131 keyEntry->scanCode = event.getScanCode();
4132 keyEntry->metaState = event.getMetaState();
4133 keyEntry->repeatCount = event.getRepeatCount();
4134 keyEntry->downTime = event.getDownTime();
4135 keyEntry->syntheticRepeat = false;
4136
4137#if DEBUG_OUTBOUND_EVENT_DETAILS
4138 ALOGD("Unhandled key event: Dispatching fallback key. "
4139 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4140 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4141#endif
4142 return true; // restart the event
4143 } else {
4144#if DEBUG_OUTBOUND_EVENT_DETAILS
4145 ALOGD("Unhandled key event: No fallback key.");
4146#endif
4147 }
4148 }
4149 }
4150 return false;
4151}
4152
4153bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4154 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4155 return false;
4156}
4157
4158void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4159 mLock.unlock();
4160
4161 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4162
4163 mLock.lock();
4164}
4165
4166void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004167 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4169 entry->downTime, entry->eventTime);
4170}
4171
4172void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4173 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4174 // TODO Write some statistics about how long we spend waiting.
4175}
4176
4177void InputDispatcher::traceInboundQueueLengthLocked() {
4178 if (ATRACE_ENABLED()) {
4179 ATRACE_INT("iq", mInboundQueue.count());
4180 }
4181}
4182
4183void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4184 if (ATRACE_ENABLED()) {
4185 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004186 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 ATRACE_INT(counterName, connection->outboundQueue.count());
4188 }
4189}
4190
4191void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4192 if (ATRACE_ENABLED()) {
4193 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004194 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 ATRACE_INT(counterName, connection->waitQueue.count());
4196 }
4197}
4198
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004199void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 AutoMutex _l(mLock);
4201
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004202 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 dumpDispatchStateLocked(dump);
4204
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004205 if (!mLastANRState.empty()) {
4206 dump += "\nInput Dispatcher State at time of last ANR:\n";
4207 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 }
4209}
4210
4211void InputDispatcher::monitor() {
4212 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4213 mLock.lock();
4214 mLooper->wake();
4215 mDispatcherIsAliveCondition.wait(mLock);
4216 mLock.unlock();
4217}
4218
4219
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220// --- InputDispatcher::InjectionState ---
4221
4222InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4223 refCount(1),
4224 injectorPid(injectorPid), injectorUid(injectorUid),
4225 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4226 pendingForegroundDispatches(0) {
4227}
4228
4229InputDispatcher::InjectionState::~InjectionState() {
4230}
4231
4232void InputDispatcher::InjectionState::release() {
4233 refCount -= 1;
4234 if (refCount == 0) {
4235 delete this;
4236 } else {
4237 ALOG_ASSERT(refCount > 0);
4238 }
4239}
4240
4241
4242// --- InputDispatcher::EventEntry ---
4243
4244InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4245 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
Yi Kong9b14ac62018-07-17 13:48:38 -07004246 injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247}
4248
4249InputDispatcher::EventEntry::~EventEntry() {
4250 releaseInjectionState();
4251}
4252
4253void InputDispatcher::EventEntry::release() {
4254 refCount -= 1;
4255 if (refCount == 0) {
4256 delete this;
4257 } else {
4258 ALOG_ASSERT(refCount > 0);
4259 }
4260}
4261
4262void InputDispatcher::EventEntry::releaseInjectionState() {
4263 if (injectionState) {
4264 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004265 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 }
4267}
4268
4269
4270// --- InputDispatcher::ConfigurationChangedEntry ---
4271
4272InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4273 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4274}
4275
4276InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4277}
4278
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004279void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4280 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281}
4282
4283
4284// --- InputDispatcher::DeviceResetEntry ---
4285
4286InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4287 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4288 deviceId(deviceId) {
4289}
4290
4291InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4292}
4293
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004294void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4295 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 deviceId, policyFlags);
4297}
4298
4299
4300// --- InputDispatcher::KeyEntry ---
4301
4302InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004303 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4305 int32_t repeatCount, nsecs_t downTime) :
4306 EventEntry(TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004307 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4309 repeatCount(repeatCount), downTime(downTime),
4310 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4311 interceptKeyWakeupTime(0) {
4312}
4313
4314InputDispatcher::KeyEntry::~KeyEntry() {
4315}
4316
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004317void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004318 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4320 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004321 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004322 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323}
4324
4325void InputDispatcher::KeyEntry::recycle() {
4326 releaseInjectionState();
4327
4328 dispatchInProgress = false;
4329 syntheticRepeat = false;
4330 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4331 interceptKeyWakeupTime = 0;
4332}
4333
4334
4335// --- InputDispatcher::MotionEntry ---
4336
Michael Wright7b159c92015-05-14 14:48:03 +01004337InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004338 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4339 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004340 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4341 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004342 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004343 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4344 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4346 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004347 deviceId(deviceId), source(source), displayId(displayId), action(action),
4348 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004349 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004350 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 for (uint32_t i = 0; i < pointerCount; i++) {
4352 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4353 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004354 if (xOffset || yOffset) {
4355 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 }
4358}
4359
4360InputDispatcher::MotionEntry::~MotionEntry() {
4361}
4362
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004363void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004364 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004365 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004366 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004367 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4368 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4369
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370 for (uint32_t i = 0; i < pointerCount; i++) {
4371 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004372 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004374 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 pointerCoords[i].getX(), pointerCoords[i].getY());
4376 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004377 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378}
4379
4380
4381// --- InputDispatcher::DispatchEntry ---
4382
4383volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4384
4385InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4386 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4387 seq(nextSeq()),
4388 eventEntry(eventEntry), targetFlags(targetFlags),
4389 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4390 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4391 eventEntry->refCount += 1;
4392}
4393
4394InputDispatcher::DispatchEntry::~DispatchEntry() {
4395 eventEntry->release();
4396}
4397
4398uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4399 // Sequence number 0 is reserved and will never be returned.
4400 uint32_t seq;
4401 do {
4402 seq = android_atomic_inc(&sNextSeqAtomic);
4403 } while (!seq);
4404 return seq;
4405}
4406
4407
4408// --- InputDispatcher::InputState ---
4409
4410InputDispatcher::InputState::InputState() {
4411}
4412
4413InputDispatcher::InputState::~InputState() {
4414}
4415
4416bool InputDispatcher::InputState::isNeutral() const {
4417 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4418}
4419
4420bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4421 int32_t displayId) const {
4422 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4423 const MotionMemento& memento = mMotionMementos.itemAt(i);
4424 if (memento.deviceId == deviceId
4425 && memento.source == source
4426 && memento.displayId == displayId
4427 && memento.hovering) {
4428 return true;
4429 }
4430 }
4431 return false;
4432}
4433
4434bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4435 int32_t action, int32_t flags) {
4436 switch (action) {
4437 case AKEY_EVENT_ACTION_UP: {
4438 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4439 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4440 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4441 mFallbackKeys.removeItemsAt(i);
4442 } else {
4443 i += 1;
4444 }
4445 }
4446 }
4447 ssize_t index = findKeyMemento(entry);
4448 if (index >= 0) {
4449 mKeyMementos.removeAt(index);
4450 return true;
4451 }
4452 /* FIXME: We can't just drop the key up event because that prevents creating
4453 * popup windows that are automatically shown when a key is held and then
4454 * dismissed when the key is released. The problem is that the popup will
4455 * not have received the original key down, so the key up will be considered
4456 * to be inconsistent with its observed state. We could perhaps handle this
4457 * by synthesizing a key down but that will cause other problems.
4458 *
4459 * So for now, allow inconsistent key up events to be dispatched.
4460 *
4461#if DEBUG_OUTBOUND_EVENT_DETAILS
4462 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4463 "keyCode=%d, scanCode=%d",
4464 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4465#endif
4466 return false;
4467 */
4468 return true;
4469 }
4470
4471 case AKEY_EVENT_ACTION_DOWN: {
4472 ssize_t index = findKeyMemento(entry);
4473 if (index >= 0) {
4474 mKeyMementos.removeAt(index);
4475 }
4476 addKeyMemento(entry, flags);
4477 return true;
4478 }
4479
4480 default:
4481 return true;
4482 }
4483}
4484
4485bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4486 int32_t action, int32_t flags) {
4487 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4488 switch (actionMasked) {
4489 case AMOTION_EVENT_ACTION_UP:
4490 case AMOTION_EVENT_ACTION_CANCEL: {
4491 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4492 if (index >= 0) {
4493 mMotionMementos.removeAt(index);
4494 return true;
4495 }
4496#if DEBUG_OUTBOUND_EVENT_DETAILS
4497 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004498 "displayId=%" PRId32 ", actionMasked=%d",
4499 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500#endif
4501 return false;
4502 }
4503
4504 case AMOTION_EVENT_ACTION_DOWN: {
4505 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4506 if (index >= 0) {
4507 mMotionMementos.removeAt(index);
4508 }
4509 addMotionMemento(entry, flags, false /*hovering*/);
4510 return true;
4511 }
4512
4513 case AMOTION_EVENT_ACTION_POINTER_UP:
4514 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4515 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004516 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4517 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4518 // generate cancellation events for these since they're based in relative rather than
4519 // absolute units.
4520 return true;
4521 }
4522
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004524
4525 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4526 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4527 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4528 // other value and we need to track the motion so we can send cancellation events for
4529 // anything generating fallback events (e.g. DPad keys for joystick movements).
4530 if (index >= 0) {
4531 if (entry->pointerCoords[0].isEmpty()) {
4532 mMotionMementos.removeAt(index);
4533 } else {
4534 MotionMemento& memento = mMotionMementos.editItemAt(index);
4535 memento.setPointers(entry);
4536 }
4537 } else if (!entry->pointerCoords[0].isEmpty()) {
4538 addMotionMemento(entry, flags, false /*hovering*/);
4539 }
4540
4541 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4542 return true;
4543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544 if (index >= 0) {
4545 MotionMemento& memento = mMotionMementos.editItemAt(index);
4546 memento.setPointers(entry);
4547 return true;
4548 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549#if DEBUG_OUTBOUND_EVENT_DETAILS
4550 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004551 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4552 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553#endif
4554 return false;
4555 }
4556
4557 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4558 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4559 if (index >= 0) {
4560 mMotionMementos.removeAt(index);
4561 return true;
4562 }
4563#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004564 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4565 "displayId=%" PRId32,
4566 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004567#endif
4568 return false;
4569 }
4570
4571 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4572 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4573 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4574 if (index >= 0) {
4575 mMotionMementos.removeAt(index);
4576 }
4577 addMotionMemento(entry, flags, true /*hovering*/);
4578 return true;
4579 }
4580
4581 default:
4582 return true;
4583 }
4584}
4585
4586ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4587 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4588 const KeyMemento& memento = mKeyMementos.itemAt(i);
4589 if (memento.deviceId == entry->deviceId
4590 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004591 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592 && memento.keyCode == entry->keyCode
4593 && memento.scanCode == entry->scanCode) {
4594 return i;
4595 }
4596 }
4597 return -1;
4598}
4599
4600ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4601 bool hovering) const {
4602 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4603 const MotionMemento& memento = mMotionMementos.itemAt(i);
4604 if (memento.deviceId == entry->deviceId
4605 && memento.source == entry->source
4606 && memento.displayId == entry->displayId
4607 && memento.hovering == hovering) {
4608 return i;
4609 }
4610 }
4611 return -1;
4612}
4613
4614void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4615 mKeyMementos.push();
4616 KeyMemento& memento = mKeyMementos.editTop();
4617 memento.deviceId = entry->deviceId;
4618 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004619 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620 memento.keyCode = entry->keyCode;
4621 memento.scanCode = entry->scanCode;
4622 memento.metaState = entry->metaState;
4623 memento.flags = flags;
4624 memento.downTime = entry->downTime;
4625 memento.policyFlags = entry->policyFlags;
4626}
4627
4628void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4629 int32_t flags, bool hovering) {
4630 mMotionMementos.push();
4631 MotionMemento& memento = mMotionMementos.editTop();
4632 memento.deviceId = entry->deviceId;
4633 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004634 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 memento.flags = flags;
4636 memento.xPrecision = entry->xPrecision;
4637 memento.yPrecision = entry->yPrecision;
4638 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639 memento.setPointers(entry);
4640 memento.hovering = hovering;
4641 memento.policyFlags = entry->policyFlags;
4642}
4643
4644void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4645 pointerCount = entry->pointerCount;
4646 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4647 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4648 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4649 }
4650}
4651
4652void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4653 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4654 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4655 const KeyMemento& memento = mKeyMementos.itemAt(i);
4656 if (shouldCancelKey(memento, options)) {
4657 outEvents.push(new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004658 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4660 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4661 }
4662 }
4663
4664 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4665 const MotionMemento& memento = mMotionMementos.itemAt(i);
4666 if (shouldCancelMotion(memento, options)) {
4667 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004668 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669 memento.hovering
4670 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4671 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004672 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004674 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4675 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676 }
4677 }
4678}
4679
4680void InputDispatcher::InputState::clear() {
4681 mKeyMementos.clear();
4682 mMotionMementos.clear();
4683 mFallbackKeys.clear();
4684}
4685
4686void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4687 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4688 const MotionMemento& memento = mMotionMementos.itemAt(i);
4689 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4690 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4691 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4692 if (memento.deviceId == otherMemento.deviceId
4693 && memento.source == otherMemento.source
4694 && memento.displayId == otherMemento.displayId) {
4695 other.mMotionMementos.removeAt(j);
4696 } else {
4697 j += 1;
4698 }
4699 }
4700 other.mMotionMementos.push(memento);
4701 }
4702 }
4703}
4704
4705int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4706 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4707 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4708}
4709
4710void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4711 int32_t fallbackKeyCode) {
4712 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4713 if (index >= 0) {
4714 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4715 } else {
4716 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4717 }
4718}
4719
4720void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4721 mFallbackKeys.removeItem(originalKeyCode);
4722}
4723
4724bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4725 const CancelationOptions& options) {
4726 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4727 return false;
4728 }
4729
4730 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4731 return false;
4732 }
4733
4734 switch (options.mode) {
4735 case CancelationOptions::CANCEL_ALL_EVENTS:
4736 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4737 return true;
4738 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4739 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004740 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4741 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742 default:
4743 return false;
4744 }
4745}
4746
4747bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4748 const CancelationOptions& options) {
4749 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4750 return false;
4751 }
4752
4753 switch (options.mode) {
4754 case CancelationOptions::CANCEL_ALL_EVENTS:
4755 return true;
4756 case CancelationOptions::CANCEL_POINTER_EVENTS:
4757 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4758 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4759 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004760 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4761 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762 default:
4763 return false;
4764 }
4765}
4766
4767
4768// --- InputDispatcher::Connection ---
4769
Robert Carr803535b2018-08-02 16:38:15 -07004770InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4771 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 monitor(monitor),
4773 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4774}
4775
4776InputDispatcher::Connection::~Connection() {
4777}
4778
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004779const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004780 if (inputChannel != nullptr) {
4781 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 }
4783 if (monitor) {
4784 return "monitor";
4785 }
4786 return "?";
4787}
4788
4789const char* InputDispatcher::Connection::getStatusLabel() const {
4790 switch (status) {
4791 case STATUS_NORMAL:
4792 return "NORMAL";
4793
4794 case STATUS_BROKEN:
4795 return "BROKEN";
4796
4797 case STATUS_ZOMBIE:
4798 return "ZOMBIE";
4799
4800 default:
4801 return "UNKNOWN";
4802 }
4803}
4804
4805InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004806 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807 if (entry->seq == seq) {
4808 return entry;
4809 }
4810 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004811 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812}
4813
4814
4815// --- InputDispatcher::CommandEntry ---
4816
4817InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004818 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 seq(0), handled(false) {
4820}
4821
4822InputDispatcher::CommandEntry::~CommandEntry() {
4823}
4824
4825
4826// --- InputDispatcher::TouchState ---
4827
4828InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004829 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830}
4831
4832InputDispatcher::TouchState::~TouchState() {
4833}
4834
4835void InputDispatcher::TouchState::reset() {
4836 down = false;
4837 split = false;
4838 deviceId = -1;
4839 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004840 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 windows.clear();
4842}
4843
4844void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4845 down = other.down;
4846 split = other.split;
4847 deviceId = other.deviceId;
4848 source = other.source;
4849 displayId = other.displayId;
4850 windows = other.windows;
4851}
4852
4853void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4854 int32_t targetFlags, BitSet32 pointerIds) {
4855 if (targetFlags & InputTarget::FLAG_SPLIT) {
4856 split = true;
4857 }
4858
4859 for (size_t i = 0; i < windows.size(); i++) {
4860 TouchedWindow& touchedWindow = windows.editItemAt(i);
4861 if (touchedWindow.windowHandle == windowHandle) {
4862 touchedWindow.targetFlags |= targetFlags;
4863 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4864 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4865 }
4866 touchedWindow.pointerIds.value |= pointerIds.value;
4867 return;
4868 }
4869 }
4870
4871 windows.push();
4872
4873 TouchedWindow& touchedWindow = windows.editTop();
4874 touchedWindow.windowHandle = windowHandle;
4875 touchedWindow.targetFlags = targetFlags;
4876 touchedWindow.pointerIds = pointerIds;
4877}
4878
4879void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4880 for (size_t i = 0; i < windows.size(); i++) {
4881 if (windows.itemAt(i).windowHandle == windowHandle) {
4882 windows.removeAt(i);
4883 return;
4884 }
4885 }
4886}
4887
Robert Carr803535b2018-08-02 16:38:15 -07004888void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4889 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004890 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004891 windows.removeAt(i);
4892 return;
4893 }
4894 }
4895}
4896
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4898 for (size_t i = 0 ; i < windows.size(); ) {
4899 TouchedWindow& window = windows.editItemAt(i);
4900 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4901 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4902 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4903 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4904 i += 1;
4905 } else {
4906 windows.removeAt(i);
4907 }
4908 }
4909}
4910
4911sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4912 for (size_t i = 0; i < windows.size(); i++) {
4913 const TouchedWindow& window = windows.itemAt(i);
4914 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4915 return window.windowHandle;
4916 }
4917 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004918 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919}
4920
4921bool InputDispatcher::TouchState::isSlippery() const {
4922 // Must have exactly one foreground window.
4923 bool haveSlipperyForegroundWindow = false;
4924 for (size_t i = 0; i < windows.size(); i++) {
4925 const TouchedWindow& window = windows.itemAt(i);
4926 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4927 if (haveSlipperyForegroundWindow
4928 || !(window.windowHandle->getInfo()->layoutParamsFlags
4929 & InputWindowInfo::FLAG_SLIPPERY)) {
4930 return false;
4931 }
4932 haveSlipperyForegroundWindow = true;
4933 }
4934 }
4935 return haveSlipperyForegroundWindow;
4936}
4937
4938
4939// --- InputDispatcherThread ---
4940
4941InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4942 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4943}
4944
4945InputDispatcherThread::~InputDispatcherThread() {
4946}
4947
4948bool InputDispatcherThread::threadLoop() {
4949 mDispatcher->dispatchOnce();
4950 return true;
4951}
4952
4953} // namespace android