blob: ac17dcaa7f64ddb423f15dc0f5773551ec612063 [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) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001666 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1667 if (inputChannel == nullptr) {
1668 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1669 return;
1670 }
1671
Michael Wrightd02c5b62014-02-10 15:10:22 -08001672 inputTargets.push();
1673
1674 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1675 InputTarget& target = inputTargets.editTop();
Arthur Hungceeb5d72018-12-05 16:14:18 +08001676 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677 target.flags = targetFlags;
1678 target.xOffset = - windowInfo->frameLeft;
1679 target.yOffset = - windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001680 target.globalScaleFactor = windowInfo->globalScaleFactor;
1681 target.windowXScale = windowInfo->windowXScale;
1682 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 target.pointerIds = pointerIds;
1684}
1685
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001686void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets,
1687 int32_t displayId) {
1688 std::unordered_map<int32_t, Vector<sp<InputChannel>>>::const_iterator it =
1689 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001690
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001691 if (it != mMonitoringChannelsByDisplay.end()) {
1692 const Vector<sp<InputChannel>>& monitoringChannels = it->second;
1693 const size_t numChannels = monitoringChannels.size();
1694 for (size_t i = 0; i < numChannels; i++) {
1695 inputTargets.push();
1696
1697 InputTarget& target = inputTargets.editTop();
1698 target.inputChannel = monitoringChannels[i];
1699 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1700 target.xOffset = 0;
1701 target.yOffset = 0;
1702 target.pointerIds.clear();
Robert Carre07e1032018-11-26 12:55:53 -08001703 target.globalScaleFactor = 1.0f;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001704 }
1705 } else {
1706 // If there is no monitor channel registered or all monitor channel unregistered,
1707 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001708 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 }
1710}
1711
1712bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1713 const InjectionState* injectionState) {
1714 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001715 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001716 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1717 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001718 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1720 "owned by uid %d",
1721 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001722 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001723 windowHandle->getInfo()->ownerUid);
1724 } else {
1725 ALOGW("Permission denied: injecting event from pid %d uid %d",
1726 injectionState->injectorPid, injectionState->injectorUid);
1727 }
1728 return false;
1729 }
1730 return true;
1731}
1732
1733bool InputDispatcher::isWindowObscuredAtPointLocked(
1734 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1735 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001736 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1737 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001738 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001739 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740 if (otherHandle == windowHandle) {
1741 break;
1742 }
1743
1744 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1745 if (otherInfo->displayId == displayId
1746 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1747 && otherInfo->frameContainsPoint(x, y)) {
1748 return true;
1749 }
1750 }
1751 return false;
1752}
1753
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001754
1755bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1756 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001757 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001758 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hungb92218b2018-08-14 12:00:21 +08001759 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001760 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001761 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001762 if (otherHandle == windowHandle) {
1763 break;
1764 }
1765
1766 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1767 if (otherInfo->displayId == displayId
1768 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1769 && otherInfo->overlaps(windowInfo)) {
1770 return true;
1771 }
1772 }
1773 return false;
1774}
1775
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001776std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001777 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1778 const char* targetType) {
1779 // If the window is paused then keep waiting.
1780 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001781 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001782 }
1783
1784 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001785 ssize_t connectionIndex = getConnectionIndexLocked(
1786 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001787 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001788 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001789 "registered with the input dispatcher. The window may be in the process "
1790 "of being removed.", targetType);
1791 }
1792
1793 // If the connection is dead then keep waiting.
1794 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1795 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001796 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001797 "The window may be in the process of being removed.", targetType,
1798 connection->getStatusLabel());
1799 }
1800
1801 // If the connection is backed up then keep waiting.
1802 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001803 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001804 "Outbound queue length: %d. Wait queue length: %d.",
1805 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1806 }
1807
1808 // Ensure that the dispatch queues aren't too far backed up for this event.
1809 if (eventEntry->type == EventEntry::TYPE_KEY) {
1810 // If the event is a key event, then we must wait for all previous events to
1811 // complete before delivering it because previous events may have the
1812 // side-effect of transferring focus to a different window and we want to
1813 // ensure that the following keys are sent to the new window.
1814 //
1815 // Suppose the user touches a button in a window then immediately presses "A".
1816 // If the button causes a pop-up window to appear then we want to ensure that
1817 // the "A" key is delivered to the new pop-up window. This is because users
1818 // often anticipate pending UI changes when typing on a keyboard.
1819 // To obtain this behavior, we must serialize key events with respect to all
1820 // prior input events.
1821 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001822 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001823 "finished processing all of the input events that were previously "
1824 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1825 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001826 }
Jeff Brownffb49772014-10-10 19:01:34 -07001827 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001828 // Touch events can always be sent to a window immediately because the user intended
1829 // to touch whatever was visible at the time. Even if focus changes or a new
1830 // window appears moments later, the touch event was meant to be delivered to
1831 // whatever window happened to be on screen at the time.
1832 //
1833 // Generic motion events, such as trackball or joystick events are a little trickier.
1834 // Like key events, generic motion events are delivered to the focused window.
1835 // Unlike key events, generic motion events don't tend to transfer focus to other
1836 // windows and it is not important for them to be serialized. So we prefer to deliver
1837 // generic motion events as soon as possible to improve efficiency and reduce lag
1838 // through batching.
1839 //
1840 // The one case where we pause input event delivery is when the wait queue is piling
1841 // up with lots of events because the application is not responding.
1842 // This condition ensures that ANRs are detected reliably.
1843 if (!connection->waitQueue.isEmpty()
1844 && currentTime >= connection->waitQueue.head->deliveryTime
1845 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001846 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001847 "finished processing certain input events that were delivered to it over "
1848 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1849 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1850 connection->waitQueue.count(),
1851 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 }
1853 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001854 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855}
1856
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001857std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 const sp<InputApplicationHandle>& applicationHandle,
1859 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001860 if (applicationHandle != nullptr) {
1861 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001862 std::string label(applicationHandle->getName());
1863 label += " - ";
1864 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 return label;
1866 } else {
1867 return applicationHandle->getName();
1868 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001869 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 return windowHandle->getName();
1871 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001872 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 }
1874}
1875
1876void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001877 int32_t displayId = getTargetDisplayId(eventEntry);
1878 sp<InputWindowHandle> focusedWindowHandle =
1879 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1880 if (focusedWindowHandle != nullptr) {
1881 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1883#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001884 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885#endif
1886 return;
1887 }
1888 }
1889
1890 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1891 switch (eventEntry->type) {
1892 case EventEntry::TYPE_MOTION: {
1893 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1894 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1895 return;
1896 }
1897
1898 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1899 eventType = USER_ACTIVITY_EVENT_TOUCH;
1900 }
1901 break;
1902 }
1903 case EventEntry::TYPE_KEY: {
1904 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1905 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1906 return;
1907 }
1908 eventType = USER_ACTIVITY_EVENT_BUTTON;
1909 break;
1910 }
1911 }
1912
1913 CommandEntry* commandEntry = postCommandLocked(
1914 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1915 commandEntry->eventTime = eventEntry->eventTime;
1916 commandEntry->userActivityEventType = eventType;
1917}
1918
1919void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1920 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1921#if DEBUG_DISPATCH_CYCLE
1922 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Robert Carre07e1032018-11-26 12:55:53 -08001923 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1924 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001925 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001927 inputTarget->globalScaleFactor,
1928 inputTarget->windowXScale, inputTarget->windowYScale,
1929 inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930#endif
1931
1932 // Skip this event if the connection status is not normal.
1933 // We don't want to enqueue additional outbound events if the connection is broken.
1934 if (connection->status != Connection::STATUS_NORMAL) {
1935#if DEBUG_DISPATCH_CYCLE
1936 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001937 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938#endif
1939 return;
1940 }
1941
1942 // Split a motion event if needed.
1943 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1944 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1945
1946 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1947 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1948 MotionEntry* splitMotionEntry = splitMotionEvent(
1949 originalMotionEntry, inputTarget->pointerIds);
1950 if (!splitMotionEntry) {
1951 return; // split event was dropped
1952 }
1953#if DEBUG_FOCUS
1954 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001955 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001956 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1957#endif
1958 enqueueDispatchEntriesLocked(currentTime, connection,
1959 splitMotionEntry, inputTarget);
1960 splitMotionEntry->release();
1961 return;
1962 }
1963 }
1964
1965 // Not splitting. Enqueue dispatch entries for the event as is.
1966 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1967}
1968
1969void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1970 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1971 bool wasEmpty = connection->outboundQueue.isEmpty();
1972
1973 // Enqueue dispatch entries for the requested modes.
1974 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1975 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1976 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1977 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1978 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1979 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1980 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1981 InputTarget::FLAG_DISPATCH_AS_IS);
1982 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1983 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1984 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1985 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1986
1987 // If the outbound queue was previously empty, start the dispatch cycle going.
1988 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1989 startDispatchCycleLocked(currentTime, connection);
1990 }
1991}
1992
1993void InputDispatcher::enqueueDispatchEntryLocked(
1994 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1995 int32_t dispatchMode) {
1996 int32_t inputTargetFlags = inputTarget->flags;
1997 if (!(inputTargetFlags & dispatchMode)) {
1998 return;
1999 }
2000 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2001
2002 // This is a new event.
2003 // Enqueue a new dispatch entry onto the outbound queue for this connection.
2004 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
2005 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08002006 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2007 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008
2009 // Apply target flags and update the connection's input state.
2010 switch (eventEntry->type) {
2011 case EventEntry::TYPE_KEY: {
2012 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2013 dispatchEntry->resolvedAction = keyEntry->action;
2014 dispatchEntry->resolvedFlags = keyEntry->flags;
2015
2016 if (!connection->inputState.trackKey(keyEntry,
2017 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2018#if DEBUG_DISPATCH_CYCLE
2019 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002020 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021#endif
2022 delete dispatchEntry;
2023 return; // skip the inconsistent event
2024 }
2025 break;
2026 }
2027
2028 case EventEntry::TYPE_MOTION: {
2029 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2030 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2031 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2032 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2033 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2034 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2035 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2036 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2037 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2038 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2039 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2040 } else {
2041 dispatchEntry->resolvedAction = motionEntry->action;
2042 }
2043 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2044 && !connection->inputState.isHovering(
2045 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2046#if DEBUG_DISPATCH_CYCLE
2047 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002048 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049#endif
2050 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2051 }
2052
2053 dispatchEntry->resolvedFlags = motionEntry->flags;
2054 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2055 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2056 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002057 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2058 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060
2061 if (!connection->inputState.trackMotion(motionEntry,
2062 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2063#if DEBUG_DISPATCH_CYCLE
2064 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002065 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066#endif
2067 delete dispatchEntry;
2068 return; // skip the inconsistent event
2069 }
2070 break;
2071 }
2072 }
2073
2074 // Remember that we are waiting for this dispatch to complete.
2075 if (dispatchEntry->hasForegroundTarget()) {
2076 incrementPendingForegroundDispatchesLocked(eventEntry);
2077 }
2078
2079 // Enqueue the dispatch entry.
2080 connection->outboundQueue.enqueueAtTail(dispatchEntry);
2081 traceOutboundQueueLengthLocked(connection);
2082}
2083
2084void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2085 const sp<Connection>& connection) {
2086#if DEBUG_DISPATCH_CYCLE
2087 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002088 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089#endif
2090
2091 while (connection->status == Connection::STATUS_NORMAL
2092 && !connection->outboundQueue.isEmpty()) {
2093 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2094 dispatchEntry->deliveryTime = currentTime;
2095
2096 // Publish the event.
2097 status_t status;
2098 EventEntry* eventEntry = dispatchEntry->eventEntry;
2099 switch (eventEntry->type) {
2100 case EventEntry::TYPE_KEY: {
2101 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2102
2103 // Publish the key event.
2104 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002105 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2107 keyEntry->keyCode, keyEntry->scanCode,
2108 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2109 keyEntry->eventTime);
2110 break;
2111 }
2112
2113 case EventEntry::TYPE_MOTION: {
2114 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2115
2116 PointerCoords scaledCoords[MAX_POINTERS];
2117 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2118
2119 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002120 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2122 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002123 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2124 float wxs = dispatchEntry->windowXScale;
2125 float wys = dispatchEntry->windowYScale;
2126 xOffset = dispatchEntry->xOffset * wxs;
2127 yOffset = dispatchEntry->yOffset * wys;
2128 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002129 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002131 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 }
2133 usingCoords = scaledCoords;
2134 }
2135 } else {
2136 xOffset = 0.0f;
2137 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138
2139 // We don't want the dispatch target to know.
2140 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002141 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 scaledCoords[i].clear();
2143 }
2144 usingCoords = scaledCoords;
2145 }
2146 }
2147
2148 // Publish the motion event.
2149 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002150 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002151 dispatchEntry->resolvedAction, motionEntry->actionButton,
2152 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2153 motionEntry->metaState, motionEntry->buttonState,
2154 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 motionEntry->downTime, motionEntry->eventTime,
2156 motionEntry->pointerCount, motionEntry->pointerProperties,
2157 usingCoords);
2158 break;
2159 }
2160
2161 default:
2162 ALOG_ASSERT(false);
2163 return;
2164 }
2165
2166 // Check the result.
2167 if (status) {
2168 if (status == WOULD_BLOCK) {
2169 if (connection->waitQueue.isEmpty()) {
2170 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2171 "This is unexpected because the wait queue is empty, so the pipe "
2172 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002173 "event to it, status=%d", connection->getInputChannelName().c_str(),
2174 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2176 } else {
2177 // Pipe is full and we are waiting for the app to finish process some events
2178 // before sending more events to it.
2179#if DEBUG_DISPATCH_CYCLE
2180 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2181 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002182 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183#endif
2184 connection->inputPublisherBlocked = true;
2185 }
2186 } else {
2187 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002188 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2190 }
2191 return;
2192 }
2193
2194 // Re-enqueue the event on the wait queue.
2195 connection->outboundQueue.dequeue(dispatchEntry);
2196 traceOutboundQueueLengthLocked(connection);
2197 connection->waitQueue.enqueueAtTail(dispatchEntry);
2198 traceWaitQueueLengthLocked(connection);
2199 }
2200}
2201
2202void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2203 const sp<Connection>& connection, uint32_t seq, bool handled) {
2204#if DEBUG_DISPATCH_CYCLE
2205 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002206 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207#endif
2208
2209 connection->inputPublisherBlocked = false;
2210
2211 if (connection->status == Connection::STATUS_BROKEN
2212 || connection->status == Connection::STATUS_ZOMBIE) {
2213 return;
2214 }
2215
2216 // Notify other system components and prepare to start the next dispatch cycle.
2217 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2218}
2219
2220void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2221 const sp<Connection>& connection, bool notify) {
2222#if DEBUG_DISPATCH_CYCLE
2223 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002224 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225#endif
2226
2227 // Clear the dispatch queues.
2228 drainDispatchQueueLocked(&connection->outboundQueue);
2229 traceOutboundQueueLengthLocked(connection);
2230 drainDispatchQueueLocked(&connection->waitQueue);
2231 traceWaitQueueLengthLocked(connection);
2232
2233 // The connection appears to be unrecoverably broken.
2234 // Ignore already broken or zombie connections.
2235 if (connection->status == Connection::STATUS_NORMAL) {
2236 connection->status = Connection::STATUS_BROKEN;
2237
2238 if (notify) {
2239 // Notify other system components.
2240 onDispatchCycleBrokenLocked(currentTime, connection);
2241 }
2242 }
2243}
2244
2245void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2246 while (!queue->isEmpty()) {
2247 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2248 releaseDispatchEntryLocked(dispatchEntry);
2249 }
2250}
2251
2252void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2253 if (dispatchEntry->hasForegroundTarget()) {
2254 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2255 }
2256 delete dispatchEntry;
2257}
2258
2259int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2260 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2261
2262 { // acquire lock
2263 AutoMutex _l(d->mLock);
2264
2265 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2266 if (connectionIndex < 0) {
2267 ALOGE("Received spurious receive callback for unknown input channel. "
2268 "fd=%d, events=0x%x", fd, events);
2269 return 0; // remove the callback
2270 }
2271
2272 bool notify;
2273 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2274 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2275 if (!(events & ALOOPER_EVENT_INPUT)) {
2276 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002277 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002278 return 1;
2279 }
2280
2281 nsecs_t currentTime = now();
2282 bool gotOne = false;
2283 status_t status;
2284 for (;;) {
2285 uint32_t seq;
2286 bool handled;
2287 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2288 if (status) {
2289 break;
2290 }
2291 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2292 gotOne = true;
2293 }
2294 if (gotOne) {
2295 d->runCommandsLockedInterruptible();
2296 if (status == WOULD_BLOCK) {
2297 return 1;
2298 }
2299 }
2300
2301 notify = status != DEAD_OBJECT || !connection->monitor;
2302 if (notify) {
2303 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002304 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
2306 } else {
2307 // Monitor channels are never explicitly unregistered.
2308 // We do it automatically when the remote endpoint is closed so don't warn
2309 // about them.
2310 notify = !connection->monitor;
2311 if (notify) {
2312 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002313 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 }
2315 }
2316
2317 // Unregister the channel.
2318 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2319 return 0; // remove the callback
2320 } // release lock
2321}
2322
2323void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2324 const CancelationOptions& options) {
2325 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2326 synthesizeCancelationEventsForConnectionLocked(
2327 mConnectionsByFd.valueAt(i), options);
2328 }
2329}
2330
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002331void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2332 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002333 for (auto& it : mMonitoringChannelsByDisplay) {
2334 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
2335 const size_t numChannels = monitoringChannels.size();
2336 for (size_t i = 0; i < numChannels; i++) {
2337 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2338 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002339 }
2340}
2341
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2343 const sp<InputChannel>& channel, const CancelationOptions& options) {
2344 ssize_t index = getConnectionIndexLocked(channel);
2345 if (index >= 0) {
2346 synthesizeCancelationEventsForConnectionLocked(
2347 mConnectionsByFd.valueAt(index), options);
2348 }
2349}
2350
2351void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2352 const sp<Connection>& connection, const CancelationOptions& options) {
2353 if (connection->status == Connection::STATUS_BROKEN) {
2354 return;
2355 }
2356
2357 nsecs_t currentTime = now();
2358
2359 Vector<EventEntry*> cancelationEvents;
2360 connection->inputState.synthesizeCancelationEvents(currentTime,
2361 cancelationEvents, options);
2362
2363 if (!cancelationEvents.isEmpty()) {
2364#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002365 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002367 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002368 options.reason, options.mode);
2369#endif
2370 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2371 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2372 switch (cancelationEventEntry->type) {
2373 case EventEntry::TYPE_KEY:
2374 logOutboundKeyDetailsLocked("cancel - ",
2375 static_cast<KeyEntry*>(cancelationEventEntry));
2376 break;
2377 case EventEntry::TYPE_MOTION:
2378 logOutboundMotionDetailsLocked("cancel - ",
2379 static_cast<MotionEntry*>(cancelationEventEntry));
2380 break;
2381 }
2382
2383 InputTarget target;
2384 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07002385 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2387 target.xOffset = -windowInfo->frameLeft;
2388 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002389 target.globalScaleFactor = windowInfo->globalScaleFactor;
2390 target.windowXScale = windowInfo->windowXScale;
2391 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 } else {
2393 target.xOffset = 0;
2394 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002395 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 }
2397 target.inputChannel = connection->inputChannel;
2398 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2399
2400 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2401 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2402
2403 cancelationEventEntry->release();
2404 }
2405
2406 startDispatchCycleLocked(currentTime, connection);
2407 }
2408}
2409
2410InputDispatcher::MotionEntry*
2411InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2412 ALOG_ASSERT(pointerIds.value != 0);
2413
2414 uint32_t splitPointerIndexMap[MAX_POINTERS];
2415 PointerProperties splitPointerProperties[MAX_POINTERS];
2416 PointerCoords splitPointerCoords[MAX_POINTERS];
2417
2418 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2419 uint32_t splitPointerCount = 0;
2420
2421 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2422 originalPointerIndex++) {
2423 const PointerProperties& pointerProperties =
2424 originalMotionEntry->pointerProperties[originalPointerIndex];
2425 uint32_t pointerId = uint32_t(pointerProperties.id);
2426 if (pointerIds.hasBit(pointerId)) {
2427 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2428 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2429 splitPointerCoords[splitPointerCount].copyFrom(
2430 originalMotionEntry->pointerCoords[originalPointerIndex]);
2431 splitPointerCount += 1;
2432 }
2433 }
2434
2435 if (splitPointerCount != pointerIds.count()) {
2436 // This is bad. We are missing some of the pointers that we expected to deliver.
2437 // Most likely this indicates that we received an ACTION_MOVE events that has
2438 // different pointer ids than we expected based on the previous ACTION_DOWN
2439 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2440 // in this way.
2441 ALOGW("Dropping split motion event because the pointer count is %d but "
2442 "we expected there to be %d pointers. This probably means we received "
2443 "a broken sequence of pointer ids from the input device.",
2444 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002445 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446 }
2447
2448 int32_t action = originalMotionEntry->action;
2449 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2450 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2451 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2452 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2453 const PointerProperties& pointerProperties =
2454 originalMotionEntry->pointerProperties[originalPointerIndex];
2455 uint32_t pointerId = uint32_t(pointerProperties.id);
2456 if (pointerIds.hasBit(pointerId)) {
2457 if (pointerIds.count() == 1) {
2458 // The first/last pointer went down/up.
2459 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2460 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2461 } else {
2462 // A secondary pointer went down/up.
2463 uint32_t splitPointerIndex = 0;
2464 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2465 splitPointerIndex += 1;
2466 }
2467 action = maskedAction | (splitPointerIndex
2468 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2469 }
2470 } else {
2471 // An unrelated pointer changed.
2472 action = AMOTION_EVENT_ACTION_MOVE;
2473 }
2474 }
2475
2476 MotionEntry* splitMotionEntry = new MotionEntry(
2477 originalMotionEntry->eventTime,
2478 originalMotionEntry->deviceId,
2479 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002480 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481 originalMotionEntry->policyFlags,
2482 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002483 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 originalMotionEntry->flags,
2485 originalMotionEntry->metaState,
2486 originalMotionEntry->buttonState,
2487 originalMotionEntry->edgeFlags,
2488 originalMotionEntry->xPrecision,
2489 originalMotionEntry->yPrecision,
2490 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002491 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492
2493 if (originalMotionEntry->injectionState) {
2494 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2495 splitMotionEntry->injectionState->refCount += 1;
2496 }
2497
2498 return splitMotionEntry;
2499}
2500
2501void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2502#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002503 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504#endif
2505
2506 bool needWake;
2507 { // acquire lock
2508 AutoMutex _l(mLock);
2509
2510 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2511 needWake = enqueueInboundEventLocked(newEntry);
2512 } // release lock
2513
2514 if (needWake) {
2515 mLooper->wake();
2516 }
2517}
2518
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002519/**
2520 * If one of the meta shortcuts is detected, process them here:
2521 * Meta + Backspace -> generate BACK
2522 * Meta + Enter -> generate HOME
2523 * This will potentially overwrite keyCode and metaState.
2524 */
2525void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2526 int32_t& keyCode, int32_t& metaState) {
2527 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2528 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2529 if (keyCode == AKEYCODE_DEL) {
2530 newKeyCode = AKEYCODE_BACK;
2531 } else if (keyCode == AKEYCODE_ENTER) {
2532 newKeyCode = AKEYCODE_HOME;
2533 }
2534 if (newKeyCode != AKEYCODE_UNKNOWN) {
2535 AutoMutex _l(mLock);
2536 struct KeyReplacement replacement = {keyCode, deviceId};
2537 mReplacedKeys.add(replacement, newKeyCode);
2538 keyCode = newKeyCode;
2539 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2540 }
2541 } else if (action == AKEY_EVENT_ACTION_UP) {
2542 // In order to maintain a consistent stream of up and down events, check to see if the key
2543 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2544 // even if the modifier was released between the down and the up events.
2545 AutoMutex _l(mLock);
2546 struct KeyReplacement replacement = {keyCode, deviceId};
2547 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2548 if (index >= 0) {
2549 keyCode = mReplacedKeys.valueAt(index);
2550 mReplacedKeys.removeItemsAt(index);
2551 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2552 }
2553 }
2554}
2555
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2557#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002558 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002559 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002560 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002561 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002563 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564#endif
2565 if (!validateKeyEvent(args->action)) {
2566 return;
2567 }
2568
2569 uint32_t policyFlags = args->policyFlags;
2570 int32_t flags = args->flags;
2571 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002572 // InputDispatcher tracks and generates key repeats on behalf of
2573 // whatever notifies it, so repeatCount should always be set to 0
2574 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2576 policyFlags |= POLICY_FLAG_VIRTUAL;
2577 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002579 if (policyFlags & POLICY_FLAG_FUNCTION) {
2580 metaState |= AMETA_FUNCTION_ON;
2581 }
2582
2583 policyFlags |= POLICY_FLAG_TRUSTED;
2584
Michael Wright78f24442014-08-06 15:55:28 -07002585 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002586 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002587
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002589 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002590 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002591 args->downTime, args->eventTime);
2592
Michael Wright2b3c3302018-03-02 17:19:13 +00002593 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002594 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002595 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2596 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2597 std::to_string(t.duration().count()).c_str());
2598 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 bool needWake;
2601 { // acquire lock
2602 mLock.lock();
2603
2604 if (shouldSendKeyToInputFilterLocked(args)) {
2605 mLock.unlock();
2606
2607 policyFlags |= POLICY_FLAG_FILTERED;
2608 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2609 return; // event was consumed by the filter
2610 }
2611
2612 mLock.lock();
2613 }
2614
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 KeyEntry* newEntry = new KeyEntry(args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002616 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002617 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 metaState, repeatCount, args->downTime);
2619
2620 needWake = enqueueInboundEventLocked(newEntry);
2621 mLock.unlock();
2622 } // release lock
2623
2624 if (needWake) {
2625 mLooper->wake();
2626 }
2627}
2628
2629bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2630 return mInputFilterEnabled;
2631}
2632
2633void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2634#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002635 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2636 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002637 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002638 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2639 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002640 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002641 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 for (uint32_t i = 0; i < args->pointerCount; i++) {
2643 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2644 "x=%f, y=%f, pressure=%f, size=%f, "
2645 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2646 "orientation=%f",
2647 i, args->pointerProperties[i].id,
2648 args->pointerProperties[i].toolType,
2649 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2650 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2651 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2652 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2653 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2654 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2655 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2656 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2657 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2658 }
2659#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002660 if (!validateMotionEvent(args->action, args->actionButton,
2661 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 return;
2663 }
2664
2665 uint32_t policyFlags = args->policyFlags;
2666 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002667
2668 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002670 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2671 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2672 std::to_string(t.duration().count()).c_str());
2673 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674
2675 bool needWake;
2676 { // acquire lock
2677 mLock.lock();
2678
2679 if (shouldSendMotionToInputFilterLocked(args)) {
2680 mLock.unlock();
2681
2682 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002683 event.initialize(args->deviceId, args->source, args->displayId,
2684 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002685 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2686 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 args->downTime, args->eventTime,
2688 args->pointerCount, args->pointerProperties, args->pointerCoords);
2689
2690 policyFlags |= POLICY_FLAG_FILTERED;
2691 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2692 return; // event was consumed by the filter
2693 }
2694
2695 mLock.lock();
2696 }
2697
2698 // Just enqueue a new motion event.
2699 MotionEntry* newEntry = new MotionEntry(args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002700 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002701 args->action, args->actionButton, args->flags,
2702 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002704 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705
2706 needWake = enqueueInboundEventLocked(newEntry);
2707 mLock.unlock();
2708 } // release lock
2709
2710 if (needWake) {
2711 mLooper->wake();
2712 }
2713}
2714
2715bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2716 // TODO: support sending secondary display events to input filter
2717 return mInputFilterEnabled && isMainDisplay(args->displayId);
2718}
2719
2720void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2721#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002722 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2723 "switchMask=0x%08x",
2724 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725#endif
2726
2727 uint32_t policyFlags = args->policyFlags;
2728 policyFlags |= POLICY_FLAG_TRUSTED;
2729 mPolicy->notifySwitch(args->eventTime,
2730 args->switchValues, args->switchMask, policyFlags);
2731}
2732
2733void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2734#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002735 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 args->eventTime, args->deviceId);
2737#endif
2738
2739 bool needWake;
2740 { // acquire lock
2741 AutoMutex _l(mLock);
2742
2743 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2744 needWake = enqueueInboundEventLocked(newEntry);
2745 } // release lock
2746
2747 if (needWake) {
2748 mLooper->wake();
2749 }
2750}
2751
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002752int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002753 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2754 uint32_t policyFlags) {
2755#if DEBUG_INBOUND_EVENT_DETAILS
2756 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002757 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2758 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759#endif
2760
2761 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2762
2763 policyFlags |= POLICY_FLAG_INJECTED;
2764 if (hasInjectionPermission(injectorPid, injectorUid)) {
2765 policyFlags |= POLICY_FLAG_TRUSTED;
2766 }
2767
2768 EventEntry* firstInjectedEntry;
2769 EventEntry* lastInjectedEntry;
2770 switch (event->getType()) {
2771 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002772 KeyEvent keyEvent;
2773 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2774 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002775 if (! validateKeyEvent(action)) {
2776 return INPUT_EVENT_INJECTION_FAILED;
2777 }
2778
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002779 int32_t flags = keyEvent.getFlags();
2780 int32_t keyCode = keyEvent.getKeyCode();
2781 int32_t metaState = keyEvent.getMetaState();
2782 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2783 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002784 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002785 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002786 keyEvent.getDownTime(), keyEvent.getEventTime());
2787
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2789 policyFlags |= POLICY_FLAG_VIRTUAL;
2790 }
2791
2792 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002793 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002794 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002795 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2796 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2797 std::to_string(t.duration().count()).c_str());
2798 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002799 }
2800
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801 mLock.lock();
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002802 firstInjectedEntry = new KeyEntry(keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002803 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002804 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002805 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2806 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 lastInjectedEntry = firstInjectedEntry;
2808 break;
2809 }
2810
2811 case AINPUT_EVENT_TYPE_MOTION: {
2812 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 int32_t action = motionEvent->getAction();
2814 size_t pointerCount = motionEvent->getPointerCount();
2815 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002816 int32_t actionButton = motionEvent->getActionButton();
2817 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002818 return INPUT_EVENT_INJECTION_FAILED;
2819 }
2820
2821 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2822 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002823 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002825 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2826 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2827 std::to_string(t.duration().count()).c_str());
2828 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 }
2830
2831 mLock.lock();
2832 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2833 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2834 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002835 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2836 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002837 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 motionEvent->getMetaState(), motionEvent->getButtonState(),
2839 motionEvent->getEdgeFlags(),
2840 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002841 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002842 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2843 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844 lastInjectedEntry = firstInjectedEntry;
2845 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2846 sampleEventTimes += 1;
2847 samplePointerCoords += pointerCount;
2848 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002849 motionEvent->getDeviceId(), motionEvent->getSource(),
2850 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002851 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 motionEvent->getMetaState(), motionEvent->getButtonState(),
2853 motionEvent->getEdgeFlags(),
2854 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002855 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002856 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2857 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 lastInjectedEntry->next = nextInjectedEntry;
2859 lastInjectedEntry = nextInjectedEntry;
2860 }
2861 break;
2862 }
2863
2864 default:
2865 ALOGW("Cannot inject event of type %d", event->getType());
2866 return INPUT_EVENT_INJECTION_FAILED;
2867 }
2868
2869 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2870 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2871 injectionState->injectionIsAsync = true;
2872 }
2873
2874 injectionState->refCount += 1;
2875 lastInjectedEntry->injectionState = injectionState;
2876
2877 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002878 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002879 EventEntry* nextEntry = entry->next;
2880 needWake |= enqueueInboundEventLocked(entry);
2881 entry = nextEntry;
2882 }
2883
2884 mLock.unlock();
2885
2886 if (needWake) {
2887 mLooper->wake();
2888 }
2889
2890 int32_t injectionResult;
2891 { // acquire lock
2892 AutoMutex _l(mLock);
2893
2894 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2895 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2896 } else {
2897 for (;;) {
2898 injectionResult = injectionState->injectionResult;
2899 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2900 break;
2901 }
2902
2903 nsecs_t remainingTimeout = endTime - now();
2904 if (remainingTimeout <= 0) {
2905#if DEBUG_INJECTION
2906 ALOGD("injectInputEvent - Timed out waiting for injection result "
2907 "to become available.");
2908#endif
2909 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2910 break;
2911 }
2912
2913 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2914 }
2915
2916 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2917 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2918 while (injectionState->pendingForegroundDispatches != 0) {
2919#if DEBUG_INJECTION
2920 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2921 injectionState->pendingForegroundDispatches);
2922#endif
2923 nsecs_t remainingTimeout = endTime - now();
2924 if (remainingTimeout <= 0) {
2925#if DEBUG_INJECTION
2926 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2927 "dispatches to finish.");
2928#endif
2929 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2930 break;
2931 }
2932
2933 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2934 }
2935 }
2936 }
2937
2938 injectionState->release();
2939 } // release lock
2940
2941#if DEBUG_INJECTION
2942 ALOGD("injectInputEvent - Finished with result %d. "
2943 "injectorPid=%d, injectorUid=%d",
2944 injectionResult, injectorPid, injectorUid);
2945#endif
2946
2947 return injectionResult;
2948}
2949
2950bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2951 return injectorUid == 0
2952 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2953}
2954
2955void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2956 InjectionState* injectionState = entry->injectionState;
2957 if (injectionState) {
2958#if DEBUG_INJECTION
2959 ALOGD("Setting input event injection result to %d. "
2960 "injectorPid=%d, injectorUid=%d",
2961 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2962#endif
2963
2964 if (injectionState->injectionIsAsync
2965 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2966 // Log the outcome since the injector did not wait for the injection result.
2967 switch (injectionResult) {
2968 case INPUT_EVENT_INJECTION_SUCCEEDED:
2969 ALOGV("Asynchronous input event injection succeeded.");
2970 break;
2971 case INPUT_EVENT_INJECTION_FAILED:
2972 ALOGW("Asynchronous input event injection failed.");
2973 break;
2974 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2975 ALOGW("Asynchronous input event injection permission denied.");
2976 break;
2977 case INPUT_EVENT_INJECTION_TIMED_OUT:
2978 ALOGW("Asynchronous input event injection timed out.");
2979 break;
2980 }
2981 }
2982
2983 injectionState->injectionResult = injectionResult;
2984 mInjectionResultAvailableCondition.broadcast();
2985 }
2986}
2987
2988void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2989 InjectionState* injectionState = entry->injectionState;
2990 if (injectionState) {
2991 injectionState->pendingForegroundDispatches += 1;
2992 }
2993}
2994
2995void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2996 InjectionState* injectionState = entry->injectionState;
2997 if (injectionState) {
2998 injectionState->pendingForegroundDispatches -= 1;
2999
3000 if (injectionState->pendingForegroundDispatches == 0) {
3001 mInjectionSyncFinishedCondition.broadcast();
3002 }
3003 }
3004}
3005
Arthur Hungb92218b2018-08-14 12:00:21 +08003006Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
3007 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
3008 mWindowHandlesByDisplay.find(displayId);
3009 if(it != mWindowHandlesByDisplay.end()) {
3010 return it->second;
3011 }
3012
3013 // Return an empty one if nothing found.
3014 return Vector<sp<InputWindowHandle>>();
3015}
3016
Michael Wrightd02c5b62014-02-10 15:10:22 -08003017sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3018 const sp<InputChannel>& inputChannel) 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++) {
3023 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
Robert Carr5c8a0262018-10-03 16:30:44 -07003024 if (windowHandle->getToken() == inputChannel->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003025 return windowHandle;
3026 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003027 }
3028 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003029 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030}
3031
3032bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003033 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003034 for (auto& it : mWindowHandlesByDisplay) {
3035 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3036 size_t numWindows = windowHandles.size();
3037 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003038 if (windowHandles.itemAt(i)->getToken()
3039 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003040 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003041 ALOGE("Found window %s in display %" PRId32
3042 ", but it should belong to display %" PRId32,
3043 windowHandle->getName().c_str(), it.first,
3044 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003045 }
3046 return true;
3047 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048 }
3049 }
3050 return false;
3051}
3052
Robert Carr5c8a0262018-10-03 16:30:44 -07003053sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3054 size_t count = mInputChannelsByToken.count(token);
3055 if (count == 0) {
3056 return nullptr;
3057 }
3058 return mInputChannelsByToken.at(token);
3059}
3060
Arthur Hungb92218b2018-08-14 12:00:21 +08003061/**
3062 * Called from InputManagerService, update window handle list by displayId that can receive input.
3063 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3064 * If set an empty list, remove all handles from the specific display.
3065 * For focused handle, check if need to change and send a cancel event to previous one.
3066 * For removed handle, check if need to send a cancel event if already in touch.
3067 */
3068void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3069 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003071 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003072#endif
3073 { // acquire lock
3074 AutoMutex _l(mLock);
3075
Arthur Hungb92218b2018-08-14 12:00:21 +08003076 // Copy old handles for release if they are no longer present.
3077 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078
Tiger Huang721e26f2018-07-24 22:26:19 +08003079 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003081
3082 if (inputWindowHandles.isEmpty()) {
3083 // Remove all handles on a display if there are no windows left.
3084 mWindowHandlesByDisplay.erase(displayId);
3085 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003086 // Since we compare the pointer of input window handles across window updates, we need
3087 // to make sure the handle object for the same window stays unchanged across updates.
3088 const Vector<sp<InputWindowHandle>>& oldHandles = mWindowHandlesByDisplay[displayId];
3089 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3090 for (size_t i = 0; i < oldHandles.size(); i++) {
3091 const sp<InputWindowHandle>& handle = oldHandles.itemAt(i);
3092 oldHandlesByTokens[handle->getToken()] = handle;
3093 }
3094
3095 const size_t numWindows = inputWindowHandles.size();
3096 Vector<sp<InputWindowHandle>> newHandles;
Arthur Hungb92218b2018-08-14 12:00:21 +08003097 for (size_t i = 0; i < numWindows; i++) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003098 const sp<InputWindowHandle>& handle = inputWindowHandles.itemAt(i);
3099 if (!handle->updateInfo() || getInputChannelLocked(handle->getToken()) == nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003100 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003101 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003102 continue;
3103 }
3104
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003105 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003106 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003107 handle->getName().c_str(), displayId,
3108 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003109 continue;
3110 }
3111
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003112 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3113 const sp<InputWindowHandle> oldHandle =
3114 oldHandlesByTokens.at(handle->getToken());
3115 oldHandle->updateFrom(handle);
3116 newHandles.push_back(oldHandle);
3117 } else {
3118 newHandles.push_back(handle);
3119 }
3120 }
3121
3122 for (size_t i = 0; i < newHandles.size(); i++) {
3123 const sp<InputWindowHandle>& windowHandle = newHandles.itemAt(i);
Siarhei Vishniakou49ee3232018-12-03 15:10:36 -06003124 if (windowHandle->getInfo()->hasFocus && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003125 newFocusedWindowHandle = windowHandle;
3126 }
3127 if (windowHandle == mLastHoverWindowHandle) {
3128 foundHoveredWindow = true;
3129 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003130 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003131
3132 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003133 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003134 }
3135
3136 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003137 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 }
3139
Tiger Huang721e26f2018-07-24 22:26:19 +08003140 sp<InputWindowHandle> oldFocusedWindowHandle =
3141 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3142
3143 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3144 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003146 ALOGD("Focus left window: %s in display %" PRId32,
3147 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003149 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3150 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003151 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3153 "focus left window");
3154 synthesizeCancelationEventsForInputChannelLocked(
3155 focusedInputChannel, options);
3156 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003157 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003159 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003161 ALOGD("Focus entered window: %s in display %" PRId32,
3162 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003164 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 }
Robert Carrf759f162018-11-13 12:57:11 -08003166
3167 if (mFocusedDisplayId == displayId) {
3168 onFocusChangedLocked(newFocusedWindowHandle);
3169 }
3170
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 }
3172
Arthur Hungb92218b2018-08-14 12:00:21 +08003173 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3174 if (stateIndex >= 0) {
3175 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003176 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003177 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003178 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003180 ALOGD("Touched window was removed: %s in display %" PRId32,
3181 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003183 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003184 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003185 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003186 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3187 "touched window was removed");
3188 synthesizeCancelationEventsForInputChannelLocked(
3189 touchedInputChannel, options);
3190 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003191 state.windows.removeAt(i);
3192 } else {
3193 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195 }
3196 }
3197
3198 // Release information for windows that are no longer present.
3199 // This ensures that unused input channels are released promptly.
3200 // Otherwise, they might stick around until the window handle is destroyed
3201 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003202 size_t numWindows = oldWindowHandles.size();
3203 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003205 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003207 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003208#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003209 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003210 }
3211 }
3212 } // release lock
3213
3214 // Wake up poll loop since it may need to make new input dispatching choices.
3215 mLooper->wake();
3216}
3217
3218void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003219 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003221 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222#endif
3223 { // acquire lock
3224 AutoMutex _l(mLock);
3225
Tiger Huang721e26f2018-07-24 22:26:19 +08003226 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3227 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003228 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003229 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3230 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003232 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003234 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003236 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003238 oldFocusedApplicationHandle->releaseInfo();
3239 oldFocusedApplicationHandle.clear();
3240 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 }
3242
3243#if DEBUG_FOCUS
3244 //logDispatchStateLocked();
3245#endif
3246 } // release lock
3247
3248 // Wake up poll loop since it may need to make new input dispatching choices.
3249 mLooper->wake();
3250}
3251
Tiger Huang721e26f2018-07-24 22:26:19 +08003252/**
3253 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3254 * the display not specified.
3255 *
3256 * We track any unreleased events for each window. If a window loses the ability to receive the
3257 * released event, we will send a cancel event to it. So when the focused display is changed, we
3258 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3259 * display. The display-specified events won't be affected.
3260 */
3261void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3262#if DEBUG_FOCUS
3263 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3264#endif
3265 { // acquire lock
3266 AutoMutex _l(mLock);
3267
3268 if (mFocusedDisplayId != displayId) {
3269 sp<InputWindowHandle> oldFocusedWindowHandle =
3270 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3271 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003272 sp<InputChannel> inputChannel =
3273 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003274 if (inputChannel != nullptr) {
3275 CancelationOptions options(
3276 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3277 "The display which contains this window no longer has focus.");
3278 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3279 }
3280 }
3281 mFocusedDisplayId = displayId;
3282
3283 // Sanity check
3284 sp<InputWindowHandle> newFocusedWindowHandle =
3285 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Robert Carrf759f162018-11-13 12:57:11 -08003286 onFocusChangedLocked(newFocusedWindowHandle);
3287
Tiger Huang721e26f2018-07-24 22:26:19 +08003288 if (newFocusedWindowHandle == nullptr) {
3289 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3290 if (!mFocusedWindowHandlesByDisplay.empty()) {
3291 ALOGE("But another display has a focused window:");
3292 for (auto& it : mFocusedWindowHandlesByDisplay) {
3293 const int32_t displayId = it.first;
3294 const sp<InputWindowHandle>& windowHandle = it.second;
3295 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3296 displayId, windowHandle->getName().c_str());
3297 }
3298 }
3299 }
3300 }
3301
3302#if DEBUG_FOCUS
3303 logDispatchStateLocked();
3304#endif
3305 } // release lock
3306
3307 // Wake up poll loop since it may need to make new input dispatching choices.
3308 mLooper->wake();
3309}
3310
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3312#if DEBUG_FOCUS
3313 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3314#endif
3315
3316 bool changed;
3317 { // acquire lock
3318 AutoMutex _l(mLock);
3319
3320 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3321 if (mDispatchFrozen && !frozen) {
3322 resetANRTimeoutsLocked();
3323 }
3324
3325 if (mDispatchEnabled && !enabled) {
3326 resetAndDropEverythingLocked("dispatcher is being disabled");
3327 }
3328
3329 mDispatchEnabled = enabled;
3330 mDispatchFrozen = frozen;
3331 changed = true;
3332 } else {
3333 changed = false;
3334 }
3335
3336#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003337 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338#endif
3339 } // release lock
3340
3341 if (changed) {
3342 // Wake up poll loop since it may need to make new input dispatching choices.
3343 mLooper->wake();
3344 }
3345}
3346
3347void InputDispatcher::setInputFilterEnabled(bool enabled) {
3348#if DEBUG_FOCUS
3349 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3350#endif
3351
3352 { // acquire lock
3353 AutoMutex _l(mLock);
3354
3355 if (mInputFilterEnabled == enabled) {
3356 return;
3357 }
3358
3359 mInputFilterEnabled = enabled;
3360 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3361 } // release lock
3362
3363 // Wake up poll loop since there might be work to do to drop everything.
3364 mLooper->wake();
3365}
3366
3367bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3368 const sp<InputChannel>& toChannel) {
3369#if DEBUG_FOCUS
3370 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003371 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372#endif
3373 { // acquire lock
3374 AutoMutex _l(mLock);
3375
3376 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3377 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07003378 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379#if DEBUG_FOCUS
3380 ALOGD("Cannot transfer focus because from or to window not found.");
3381#endif
3382 return false;
3383 }
3384 if (fromWindowHandle == toWindowHandle) {
3385#if DEBUG_FOCUS
3386 ALOGD("Trivial transfer to same window.");
3387#endif
3388 return true;
3389 }
3390 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3391#if DEBUG_FOCUS
3392 ALOGD("Cannot transfer focus because windows are on different displays.");
3393#endif
3394 return false;
3395 }
3396
3397 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003398 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3399 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3400 for (size_t i = 0; i < state.windows.size(); i++) {
3401 const TouchedWindow& touchedWindow = state.windows[i];
3402 if (touchedWindow.windowHandle == fromWindowHandle) {
3403 int32_t oldTargetFlags = touchedWindow.targetFlags;
3404 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405
Jeff Brownf086ddb2014-02-11 14:28:48 -08003406 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407
Jeff Brownf086ddb2014-02-11 14:28:48 -08003408 int32_t newTargetFlags = oldTargetFlags
3409 & (InputTarget::FLAG_FOREGROUND
3410 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3411 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412
Jeff Brownf086ddb2014-02-11 14:28:48 -08003413 found = true;
3414 goto Found;
3415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 }
3417 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003418Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419
3420 if (! found) {
3421#if DEBUG_FOCUS
3422 ALOGD("Focus transfer failed because from window did not have focus.");
3423#endif
3424 return false;
3425 }
3426
3427 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3428 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3429 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3430 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3431 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3432
3433 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3434 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3435 "transferring touch focus from this window to another window");
3436 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3437 }
3438
3439#if DEBUG_FOCUS
3440 logDispatchStateLocked();
3441#endif
3442 } // release lock
3443
3444 // Wake up poll loop since it may need to make new input dispatching choices.
3445 mLooper->wake();
3446 return true;
3447}
3448
3449void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3450#if DEBUG_FOCUS
3451 ALOGD("Resetting and dropping all events (%s).", reason);
3452#endif
3453
3454 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3455 synthesizeCancelationEventsForAllConnectionsLocked(options);
3456
3457 resetKeyRepeatLocked();
3458 releasePendingEventLocked();
3459 drainInboundQueueLocked();
3460 resetANRTimeoutsLocked();
3461
Jeff Brownf086ddb2014-02-11 14:28:48 -08003462 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003463 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003464 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465}
3466
3467void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003468 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469 dumpDispatchStateLocked(dump);
3470
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003471 std::istringstream stream(dump);
3472 std::string line;
3473
3474 while (std::getline(stream, line, '\n')) {
3475 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476 }
3477}
3478
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003479void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3480 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3481 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003482 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483
Tiger Huang721e26f2018-07-24 22:26:19 +08003484 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3485 dump += StringPrintf(INDENT "FocusedApplications:\n");
3486 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3487 const int32_t displayId = it.first;
3488 const sp<InputApplicationHandle>& applicationHandle = it.second;
3489 dump += StringPrintf(
3490 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3491 displayId,
3492 applicationHandle->getName().c_str(),
3493 applicationHandle->getDispatchingTimeout(
3494 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3495 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003497 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003499
3500 if (!mFocusedWindowHandlesByDisplay.empty()) {
3501 dump += StringPrintf(INDENT "FocusedWindows:\n");
3502 for (auto& it : mFocusedWindowHandlesByDisplay) {
3503 const int32_t displayId = it.first;
3504 const sp<InputWindowHandle>& windowHandle = it.second;
3505 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3506 displayId, windowHandle->getName().c_str());
3507 }
3508 } else {
3509 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511
Jeff Brownf086ddb2014-02-11 14:28:48 -08003512 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003513 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003514 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3515 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003516 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003517 state.displayId, toString(state.down), toString(state.split),
3518 state.deviceId, state.source);
3519 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003520 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003521 for (size_t i = 0; i < state.windows.size(); i++) {
3522 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003523 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3524 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003525 touchedWindow.pointerIds.value,
3526 touchedWindow.targetFlags);
3527 }
3528 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003529 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 }
3532 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003533 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 }
3535
Arthur Hungb92218b2018-08-14 12:00:21 +08003536 if (!mWindowHandlesByDisplay.empty()) {
3537 for (auto& it : mWindowHandlesByDisplay) {
3538 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003539 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003540 if (!windowHandles.isEmpty()) {
3541 dump += INDENT2 "Windows:\n";
3542 for (size_t i = 0; i < windowHandles.size(); i++) {
3543 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3544 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545
Arthur Hungb92218b2018-08-14 12:00:21 +08003546 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3547 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3548 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003549 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003550 "touchableRegion=",
3551 i, windowInfo->name.c_str(), windowInfo->displayId,
3552 toString(windowInfo->paused),
3553 toString(windowInfo->hasFocus),
3554 toString(windowInfo->hasWallpaper),
3555 toString(windowInfo->visible),
3556 toString(windowInfo->canReceiveKeys),
3557 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3558 windowInfo->layer,
3559 windowInfo->frameLeft, windowInfo->frameTop,
3560 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003561 windowInfo->globalScaleFactor,
3562 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003563 dumpRegion(dump, windowInfo->touchableRegion);
3564 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3565 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3566 windowInfo->ownerPid, windowInfo->ownerUid,
3567 windowInfo->dispatchingTimeout / 1000000.0);
3568 }
3569 } else {
3570 dump += INDENT2 "Windows: <none>\n";
3571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 }
3573 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003574 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575 }
3576
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003577 if (!mMonitoringChannelsByDisplay.empty()) {
3578 for (auto& it : mMonitoringChannelsByDisplay) {
3579 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003580 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003581 const size_t numChannels = monitoringChannels.size();
3582 for (size_t i = 0; i < numChannels; i++) {
3583 const sp<InputChannel>& channel = monitoringChannels[i];
3584 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3585 }
3586 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003588 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 }
3590
3591 nsecs_t currentTime = now();
3592
3593 // Dump recently dispatched or dropped events from oldest to newest.
3594 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003595 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003597 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003599 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 (currentTime - entry->eventTime) * 0.000001f);
3601 }
3602 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003603 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 }
3605
3606 // Dump event currently being dispatched.
3607 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003608 dump += INDENT "PendingEvent:\n";
3609 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003611 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3613 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003614 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 }
3616
3617 // Dump inbound events from oldest to newest.
3618 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003619 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003621 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003623 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 (currentTime - entry->eventTime) * 0.000001f);
3625 }
3626 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003627 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 }
3629
Michael Wright78f24442014-08-06 15:55:28 -07003630 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003631 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003632 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3633 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3634 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003635 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003636 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3637 }
3638 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003639 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003640 }
3641
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003643 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3645 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003646 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003648 i, connection->getInputChannelName().c_str(),
3649 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650 connection->getStatusLabel(), toString(connection->monitor),
3651 toString(connection->inputPublisherBlocked));
3652
3653 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003654 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655 connection->outboundQueue.count());
3656 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3657 entry = entry->next) {
3658 dump.append(INDENT4);
3659 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003660 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 entry->targetFlags, entry->resolvedAction,
3662 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3663 }
3664 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003665 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 }
3667
3668 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003669 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 connection->waitQueue.count());
3671 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3672 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003673 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003675 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 "age=%0.1fms, wait=%0.1fms\n",
3677 entry->targetFlags, entry->resolvedAction,
3678 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3679 (currentTime - entry->deliveryTime) * 0.000001f);
3680 }
3681 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003682 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 }
3684 }
3685 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003686 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 }
3688
3689 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003690 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 (mAppSwitchDueTime - now()) / 1000000.0);
3692 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003693 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 }
3695
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003696 dump += INDENT "Configuration:\n";
3697 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003699 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 mConfig.keyRepeatTimeout * 0.000001f);
3701}
3702
Robert Carr803535b2018-08-02 16:38:15 -07003703status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003705 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3706 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707#endif
3708
3709 { // acquire lock
3710 AutoMutex _l(mLock);
3711
Robert Carr4e670e52018-08-15 13:26:12 -07003712 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3713 // treat inputChannel as monitor channel for displayId.
3714 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3715 if (monitor) {
3716 inputChannel->setToken(new BBinder());
3717 }
3718
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 if (getConnectionIndexLocked(inputChannel) >= 0) {
3720 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003721 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722 return BAD_VALUE;
3723 }
3724
Robert Carr803535b2018-08-02 16:38:15 -07003725 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726
3727 int fd = inputChannel->getFd();
3728 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003729 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003731 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003733 Vector<sp<InputChannel>>& monitoringChannels =
3734 mMonitoringChannelsByDisplay[displayId];
3735 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 }
3737
3738 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3739 } // release lock
3740
3741 // Wake the looper because some connections have changed.
3742 mLooper->wake();
3743 return OK;
3744}
3745
3746status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3747#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003748 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749#endif
3750
3751 { // acquire lock
3752 AutoMutex _l(mLock);
3753
3754 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3755 if (status) {
3756 return status;
3757 }
3758 } // release lock
3759
3760 // Wake the poll loop because removing the connection may have changed the current
3761 // synchronization state.
3762 mLooper->wake();
3763 return OK;
3764}
3765
3766status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3767 bool notify) {
3768 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3769 if (connectionIndex < 0) {
3770 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003771 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 return BAD_VALUE;
3773 }
3774
3775 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3776 mConnectionsByFd.removeItemsAt(connectionIndex);
3777
Robert Carr5c8a0262018-10-03 16:30:44 -07003778 mInputChannelsByToken.erase(inputChannel->getToken());
3779
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 if (connection->monitor) {
3781 removeMonitorChannelLocked(inputChannel);
3782 }
3783
3784 mLooper->removeFd(inputChannel->getFd());
3785
3786 nsecs_t currentTime = now();
3787 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3788
3789 connection->status = Connection::STATUS_ZOMBIE;
3790 return OK;
3791}
3792
3793void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003794 for (auto it = mMonitoringChannelsByDisplay.begin();
3795 it != mMonitoringChannelsByDisplay.end(); ) {
3796 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3797 const size_t numChannels = monitoringChannels.size();
3798 for (size_t i = 0; i < numChannels; i++) {
3799 if (monitoringChannels[i] == inputChannel) {
3800 monitoringChannels.removeAt(i);
3801 break;
3802 }
3803 }
3804 if (monitoringChannels.empty()) {
3805 it = mMonitoringChannelsByDisplay.erase(it);
3806 } else {
3807 ++it;
3808 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 }
3810}
3811
3812ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003813 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003814 return -1;
3815 }
3816
Robert Carr4e670e52018-08-15 13:26:12 -07003817 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3818 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3819 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3820 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003821 }
3822 }
Robert Carr4e670e52018-08-15 13:26:12 -07003823
Michael Wrightd02c5b62014-02-10 15:10:22 -08003824 return -1;
3825}
3826
3827void InputDispatcher::onDispatchCycleFinishedLocked(
3828 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3829 CommandEntry* commandEntry = postCommandLocked(
3830 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3831 commandEntry->connection = connection;
3832 commandEntry->eventTime = currentTime;
3833 commandEntry->seq = seq;
3834 commandEntry->handled = handled;
3835}
3836
3837void InputDispatcher::onDispatchCycleBrokenLocked(
3838 nsecs_t currentTime, const sp<Connection>& connection) {
3839 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003840 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841
3842 CommandEntry* commandEntry = postCommandLocked(
3843 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3844 commandEntry->connection = connection;
3845}
3846
Robert Carrf759f162018-11-13 12:57:11 -08003847void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& newFocus) {
3848 sp<IBinder> token = newFocus != nullptr ? newFocus->getToken() : nullptr;
3849 CommandEntry* commandEntry = postCommandLocked(
3850 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
3851 commandEntry->token = token;
3852}
3853
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854void InputDispatcher::onANRLocked(
3855 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3856 const sp<InputWindowHandle>& windowHandle,
3857 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3858 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3859 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3860 ALOGI("Application is not responding: %s. "
3861 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003862 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 dispatchLatency, waitDuration, reason);
3864
3865 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003866 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867 struct tm tm;
3868 localtime_r(&t, &tm);
3869 char timestr[64];
3870 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3871 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003872 mLastANRState += INDENT "ANR:\n";
3873 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3874 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3875 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3876 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3877 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3878 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 dumpDispatchStateLocked(mLastANRState);
3880
3881 CommandEntry* commandEntry = postCommandLocked(
3882 & InputDispatcher::doNotifyANRLockedInterruptible);
3883 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003884 commandEntry->inputChannel = windowHandle != nullptr ?
3885 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886 commandEntry->reason = reason;
3887}
3888
3889void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3890 CommandEntry* commandEntry) {
3891 mLock.unlock();
3892
3893 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3894
3895 mLock.lock();
3896}
3897
3898void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3899 CommandEntry* commandEntry) {
3900 sp<Connection> connection = commandEntry->connection;
3901
3902 if (connection->status != Connection::STATUS_ZOMBIE) {
3903 mLock.unlock();
3904
Robert Carr803535b2018-08-02 16:38:15 -07003905 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906
3907 mLock.lock();
3908 }
3909}
3910
Robert Carrf759f162018-11-13 12:57:11 -08003911void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3912 CommandEntry* commandEntry) {
3913 sp<IBinder> token = commandEntry->token;
3914 mLock.unlock();
3915 mPolicy->notifyFocusChanged(token);
3916 mLock.lock();
3917}
3918
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919void InputDispatcher::doNotifyANRLockedInterruptible(
3920 CommandEntry* commandEntry) {
3921 mLock.unlock();
3922
3923 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003924 commandEntry->inputApplicationHandle,
3925 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926 commandEntry->reason);
3927
3928 mLock.lock();
3929
3930 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003931 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932}
3933
3934void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3935 CommandEntry* commandEntry) {
3936 KeyEntry* entry = commandEntry->keyEntry;
3937
3938 KeyEvent event;
3939 initializeKeyEvent(&event, entry);
3940
3941 mLock.unlock();
3942
Michael Wright2b3c3302018-03-02 17:19:13 +00003943 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003944 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3945 commandEntry->inputChannel->getToken() : nullptr;
3946 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003948 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3949 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3950 std::to_string(t.duration().count()).c_str());
3951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952
3953 mLock.lock();
3954
3955 if (delay < 0) {
3956 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3957 } else if (!delay) {
3958 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3959 } else {
3960 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3961 entry->interceptKeyWakeupTime = now() + delay;
3962 }
3963 entry->release();
3964}
3965
3966void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3967 CommandEntry* commandEntry) {
3968 sp<Connection> connection = commandEntry->connection;
3969 nsecs_t finishTime = commandEntry->eventTime;
3970 uint32_t seq = commandEntry->seq;
3971 bool handled = commandEntry->handled;
3972
3973 // Handle post-event policy actions.
3974 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3975 if (dispatchEntry) {
3976 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3977 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003978 std::string msg =
3979 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003980 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003982 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 }
3984
3985 bool restartEvent;
3986 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3987 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3988 restartEvent = afterKeyEventLockedInterruptible(connection,
3989 dispatchEntry, keyEntry, handled);
3990 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3991 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3992 restartEvent = afterMotionEventLockedInterruptible(connection,
3993 dispatchEntry, motionEntry, handled);
3994 } else {
3995 restartEvent = false;
3996 }
3997
3998 // Dequeue the event and start the next cycle.
3999 // Note that because the lock might have been released, it is possible that the
4000 // contents of the wait queue to have been drained, so we need to double-check
4001 // a few things.
4002 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4003 connection->waitQueue.dequeue(dispatchEntry);
4004 traceWaitQueueLengthLocked(connection);
4005 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4006 connection->outboundQueue.enqueueAtHead(dispatchEntry);
4007 traceOutboundQueueLengthLocked(connection);
4008 } else {
4009 releaseDispatchEntryLocked(dispatchEntry);
4010 }
4011 }
4012
4013 // Start the next dispatch cycle for this connection.
4014 startDispatchCycleLocked(now(), connection);
4015 }
4016}
4017
4018bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4019 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
4020 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
4021 // Get the fallback key state.
4022 // Clear it out after dispatching the UP.
4023 int32_t originalKeyCode = keyEntry->keyCode;
4024 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4025 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4026 connection->inputState.removeFallbackKey(originalKeyCode);
4027 }
4028
4029 if (handled || !dispatchEntry->hasForegroundTarget()) {
4030 // If the application handles the original key for which we previously
4031 // generated a fallback or if the window is not a foreground window,
4032 // then cancel the associated fallback key, if any.
4033 if (fallbackKeyCode != -1) {
4034 // Dispatch the unhandled key to the policy with the cancel flag.
4035#if DEBUG_OUTBOUND_EVENT_DETAILS
4036 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
4037 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4038 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4039 keyEntry->policyFlags);
4040#endif
4041 KeyEvent event;
4042 initializeKeyEvent(&event, keyEntry);
4043 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
4044
4045 mLock.unlock();
4046
Robert Carr803535b2018-08-02 16:38:15 -07004047 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048 &event, keyEntry->policyFlags, &event);
4049
4050 mLock.lock();
4051
4052 // Cancel the fallback key.
4053 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
4054 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4055 "application handled the original non-fallback key "
4056 "or is no longer a foreground target, "
4057 "canceling previously dispatched fallback key");
4058 options.keyCode = fallbackKeyCode;
4059 synthesizeCancelationEventsForConnectionLocked(connection, options);
4060 }
4061 connection->inputState.removeFallbackKey(originalKeyCode);
4062 }
4063 } else {
4064 // If the application did not handle a non-fallback key, first check
4065 // that we are in a good state to perform unhandled key event processing
4066 // Then ask the policy what to do with it.
4067 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4068 && keyEntry->repeatCount == 0;
4069 if (fallbackKeyCode == -1 && !initialDown) {
4070#if DEBUG_OUTBOUND_EVENT_DETAILS
4071 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4072 "since this is not an initial down. "
4073 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4074 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4075 keyEntry->policyFlags);
4076#endif
4077 return false;
4078 }
4079
4080 // Dispatch the unhandled key to the policy.
4081#if DEBUG_OUTBOUND_EVENT_DETAILS
4082 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4083 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4084 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4085 keyEntry->policyFlags);
4086#endif
4087 KeyEvent event;
4088 initializeKeyEvent(&event, keyEntry);
4089
4090 mLock.unlock();
4091
Robert Carr803535b2018-08-02 16:38:15 -07004092 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 &event, keyEntry->policyFlags, &event);
4094
4095 mLock.lock();
4096
4097 if (connection->status != Connection::STATUS_NORMAL) {
4098 connection->inputState.removeFallbackKey(originalKeyCode);
4099 return false;
4100 }
4101
4102 // Latch the fallback keycode for this key on an initial down.
4103 // The fallback keycode cannot change at any other point in the lifecycle.
4104 if (initialDown) {
4105 if (fallback) {
4106 fallbackKeyCode = event.getKeyCode();
4107 } else {
4108 fallbackKeyCode = AKEYCODE_UNKNOWN;
4109 }
4110 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4111 }
4112
4113 ALOG_ASSERT(fallbackKeyCode != -1);
4114
4115 // Cancel the fallback key if the policy decides not to send it anymore.
4116 // We will continue to dispatch the key to the policy but we will no
4117 // longer dispatch a fallback key to the application.
4118 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4119 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4120#if DEBUG_OUTBOUND_EVENT_DETAILS
4121 if (fallback) {
4122 ALOGD("Unhandled key event: Policy requested to send key %d"
4123 "as a fallback for %d, but on the DOWN it had requested "
4124 "to send %d instead. Fallback canceled.",
4125 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4126 } else {
4127 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4128 "but on the DOWN it had requested to send %d. "
4129 "Fallback canceled.",
4130 originalKeyCode, fallbackKeyCode);
4131 }
4132#endif
4133
4134 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4135 "canceling fallback, policy no longer desires it");
4136 options.keyCode = fallbackKeyCode;
4137 synthesizeCancelationEventsForConnectionLocked(connection, options);
4138
4139 fallback = false;
4140 fallbackKeyCode = AKEYCODE_UNKNOWN;
4141 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4142 connection->inputState.setFallbackKey(originalKeyCode,
4143 fallbackKeyCode);
4144 }
4145 }
4146
4147#if DEBUG_OUTBOUND_EVENT_DETAILS
4148 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004149 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4151 connection->inputState.getFallbackKeys();
4152 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004153 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 fallbackKeys.valueAt(i));
4155 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07004156 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004157 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 }
4159#endif
4160
4161 if (fallback) {
4162 // Restart the dispatch cycle using the fallback key.
4163 keyEntry->eventTime = event.getEventTime();
4164 keyEntry->deviceId = event.getDeviceId();
4165 keyEntry->source = event.getSource();
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004166 keyEntry->displayId = event.getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4168 keyEntry->keyCode = fallbackKeyCode;
4169 keyEntry->scanCode = event.getScanCode();
4170 keyEntry->metaState = event.getMetaState();
4171 keyEntry->repeatCount = event.getRepeatCount();
4172 keyEntry->downTime = event.getDownTime();
4173 keyEntry->syntheticRepeat = false;
4174
4175#if DEBUG_OUTBOUND_EVENT_DETAILS
4176 ALOGD("Unhandled key event: Dispatching fallback key. "
4177 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4178 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4179#endif
4180 return true; // restart the event
4181 } else {
4182#if DEBUG_OUTBOUND_EVENT_DETAILS
4183 ALOGD("Unhandled key event: No fallback key.");
4184#endif
4185 }
4186 }
4187 }
4188 return false;
4189}
4190
4191bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4192 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4193 return false;
4194}
4195
4196void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4197 mLock.unlock();
4198
4199 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4200
4201 mLock.lock();
4202}
4203
4204void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004205 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4207 entry->downTime, entry->eventTime);
4208}
4209
4210void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4211 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4212 // TODO Write some statistics about how long we spend waiting.
4213}
4214
4215void InputDispatcher::traceInboundQueueLengthLocked() {
4216 if (ATRACE_ENABLED()) {
4217 ATRACE_INT("iq", mInboundQueue.count());
4218 }
4219}
4220
4221void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4222 if (ATRACE_ENABLED()) {
4223 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004224 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 ATRACE_INT(counterName, connection->outboundQueue.count());
4226 }
4227}
4228
4229void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4230 if (ATRACE_ENABLED()) {
4231 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004232 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 ATRACE_INT(counterName, connection->waitQueue.count());
4234 }
4235}
4236
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004237void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 AutoMutex _l(mLock);
4239
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004240 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 dumpDispatchStateLocked(dump);
4242
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004243 if (!mLastANRState.empty()) {
4244 dump += "\nInput Dispatcher State at time of last ANR:\n";
4245 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246 }
4247}
4248
4249void InputDispatcher::monitor() {
4250 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4251 mLock.lock();
4252 mLooper->wake();
4253 mDispatcherIsAliveCondition.wait(mLock);
4254 mLock.unlock();
4255}
4256
4257
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258// --- InputDispatcher::InjectionState ---
4259
4260InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4261 refCount(1),
4262 injectorPid(injectorPid), injectorUid(injectorUid),
4263 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4264 pendingForegroundDispatches(0) {
4265}
4266
4267InputDispatcher::InjectionState::~InjectionState() {
4268}
4269
4270void InputDispatcher::InjectionState::release() {
4271 refCount -= 1;
4272 if (refCount == 0) {
4273 delete this;
4274 } else {
4275 ALOG_ASSERT(refCount > 0);
4276 }
4277}
4278
4279
4280// --- InputDispatcher::EventEntry ---
4281
4282InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4283 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
Yi Kong9b14ac62018-07-17 13:48:38 -07004284 injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285}
4286
4287InputDispatcher::EventEntry::~EventEntry() {
4288 releaseInjectionState();
4289}
4290
4291void InputDispatcher::EventEntry::release() {
4292 refCount -= 1;
4293 if (refCount == 0) {
4294 delete this;
4295 } else {
4296 ALOG_ASSERT(refCount > 0);
4297 }
4298}
4299
4300void InputDispatcher::EventEntry::releaseInjectionState() {
4301 if (injectionState) {
4302 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004303 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 }
4305}
4306
4307
4308// --- InputDispatcher::ConfigurationChangedEntry ---
4309
4310InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4311 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4312}
4313
4314InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4315}
4316
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004317void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4318 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004319}
4320
4321
4322// --- InputDispatcher::DeviceResetEntry ---
4323
4324InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4325 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4326 deviceId(deviceId) {
4327}
4328
4329InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4330}
4331
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004332void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4333 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 deviceId, policyFlags);
4335}
4336
4337
4338// --- InputDispatcher::KeyEntry ---
4339
4340InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004341 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4343 int32_t repeatCount, nsecs_t downTime) :
4344 EventEntry(TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004345 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4347 repeatCount(repeatCount), downTime(downTime),
4348 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4349 interceptKeyWakeupTime(0) {
4350}
4351
4352InputDispatcher::KeyEntry::~KeyEntry() {
4353}
4354
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004355void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004356 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4358 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004359 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004360 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361}
4362
4363void InputDispatcher::KeyEntry::recycle() {
4364 releaseInjectionState();
4365
4366 dispatchInProgress = false;
4367 syntheticRepeat = false;
4368 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4369 interceptKeyWakeupTime = 0;
4370}
4371
4372
4373// --- InputDispatcher::MotionEntry ---
4374
Michael Wright7b159c92015-05-14 14:48:03 +01004375InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004376 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4377 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004378 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4379 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004380 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004381 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4382 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4384 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004385 deviceId(deviceId), source(source), displayId(displayId), action(action),
4386 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004387 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004388 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 for (uint32_t i = 0; i < pointerCount; i++) {
4390 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4391 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004392 if (xOffset || yOffset) {
4393 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 }
4396}
4397
4398InputDispatcher::MotionEntry::~MotionEntry() {
4399}
4400
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004401void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004402 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004403 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004404 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004405 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4406 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4407
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 for (uint32_t i = 0; i < pointerCount; i++) {
4409 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004410 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004411 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004412 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 pointerCoords[i].getX(), pointerCoords[i].getY());
4414 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004415 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416}
4417
4418
4419// --- InputDispatcher::DispatchEntry ---
4420
4421volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4422
4423InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004424 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4425 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004426 seq(nextSeq()),
4427 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004428 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4429 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004430 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4431 eventEntry->refCount += 1;
4432}
4433
4434InputDispatcher::DispatchEntry::~DispatchEntry() {
4435 eventEntry->release();
4436}
4437
4438uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4439 // Sequence number 0 is reserved and will never be returned.
4440 uint32_t seq;
4441 do {
4442 seq = android_atomic_inc(&sNextSeqAtomic);
4443 } while (!seq);
4444 return seq;
4445}
4446
4447
4448// --- InputDispatcher::InputState ---
4449
4450InputDispatcher::InputState::InputState() {
4451}
4452
4453InputDispatcher::InputState::~InputState() {
4454}
4455
4456bool InputDispatcher::InputState::isNeutral() const {
4457 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4458}
4459
4460bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4461 int32_t displayId) const {
4462 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4463 const MotionMemento& memento = mMotionMementos.itemAt(i);
4464 if (memento.deviceId == deviceId
4465 && memento.source == source
4466 && memento.displayId == displayId
4467 && memento.hovering) {
4468 return true;
4469 }
4470 }
4471 return false;
4472}
4473
4474bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4475 int32_t action, int32_t flags) {
4476 switch (action) {
4477 case AKEY_EVENT_ACTION_UP: {
4478 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4479 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4480 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4481 mFallbackKeys.removeItemsAt(i);
4482 } else {
4483 i += 1;
4484 }
4485 }
4486 }
4487 ssize_t index = findKeyMemento(entry);
4488 if (index >= 0) {
4489 mKeyMementos.removeAt(index);
4490 return true;
4491 }
4492 /* FIXME: We can't just drop the key up event because that prevents creating
4493 * popup windows that are automatically shown when a key is held and then
4494 * dismissed when the key is released. The problem is that the popup will
4495 * not have received the original key down, so the key up will be considered
4496 * to be inconsistent with its observed state. We could perhaps handle this
4497 * by synthesizing a key down but that will cause other problems.
4498 *
4499 * So for now, allow inconsistent key up events to be dispatched.
4500 *
4501#if DEBUG_OUTBOUND_EVENT_DETAILS
4502 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4503 "keyCode=%d, scanCode=%d",
4504 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4505#endif
4506 return false;
4507 */
4508 return true;
4509 }
4510
4511 case AKEY_EVENT_ACTION_DOWN: {
4512 ssize_t index = findKeyMemento(entry);
4513 if (index >= 0) {
4514 mKeyMementos.removeAt(index);
4515 }
4516 addKeyMemento(entry, flags);
4517 return true;
4518 }
4519
4520 default:
4521 return true;
4522 }
4523}
4524
4525bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4526 int32_t action, int32_t flags) {
4527 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4528 switch (actionMasked) {
4529 case AMOTION_EVENT_ACTION_UP:
4530 case AMOTION_EVENT_ACTION_CANCEL: {
4531 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4532 if (index >= 0) {
4533 mMotionMementos.removeAt(index);
4534 return true;
4535 }
4536#if DEBUG_OUTBOUND_EVENT_DETAILS
4537 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004538 "displayId=%" PRId32 ", actionMasked=%d",
4539 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004540#endif
4541 return false;
4542 }
4543
4544 case AMOTION_EVENT_ACTION_DOWN: {
4545 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4546 if (index >= 0) {
4547 mMotionMementos.removeAt(index);
4548 }
4549 addMotionMemento(entry, flags, false /*hovering*/);
4550 return true;
4551 }
4552
4553 case AMOTION_EVENT_ACTION_POINTER_UP:
4554 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4555 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004556 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4557 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4558 // generate cancellation events for these since they're based in relative rather than
4559 // absolute units.
4560 return true;
4561 }
4562
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004564
4565 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4566 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4567 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4568 // other value and we need to track the motion so we can send cancellation events for
4569 // anything generating fallback events (e.g. DPad keys for joystick movements).
4570 if (index >= 0) {
4571 if (entry->pointerCoords[0].isEmpty()) {
4572 mMotionMementos.removeAt(index);
4573 } else {
4574 MotionMemento& memento = mMotionMementos.editItemAt(index);
4575 memento.setPointers(entry);
4576 }
4577 } else if (!entry->pointerCoords[0].isEmpty()) {
4578 addMotionMemento(entry, flags, false /*hovering*/);
4579 }
4580
4581 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4582 return true;
4583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584 if (index >= 0) {
4585 MotionMemento& memento = mMotionMementos.editItemAt(index);
4586 memento.setPointers(entry);
4587 return true;
4588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589#if DEBUG_OUTBOUND_EVENT_DETAILS
4590 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004591 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4592 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593#endif
4594 return false;
4595 }
4596
4597 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4598 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4599 if (index >= 0) {
4600 mMotionMementos.removeAt(index);
4601 return true;
4602 }
4603#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004604 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4605 "displayId=%" PRId32,
4606 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607#endif
4608 return false;
4609 }
4610
4611 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4612 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4613 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4614 if (index >= 0) {
4615 mMotionMementos.removeAt(index);
4616 }
4617 addMotionMemento(entry, flags, true /*hovering*/);
4618 return true;
4619 }
4620
4621 default:
4622 return true;
4623 }
4624}
4625
4626ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4627 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4628 const KeyMemento& memento = mKeyMementos.itemAt(i);
4629 if (memento.deviceId == entry->deviceId
4630 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004631 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 && memento.keyCode == entry->keyCode
4633 && memento.scanCode == entry->scanCode) {
4634 return i;
4635 }
4636 }
4637 return -1;
4638}
4639
4640ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4641 bool hovering) const {
4642 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4643 const MotionMemento& memento = mMotionMementos.itemAt(i);
4644 if (memento.deviceId == entry->deviceId
4645 && memento.source == entry->source
4646 && memento.displayId == entry->displayId
4647 && memento.hovering == hovering) {
4648 return i;
4649 }
4650 }
4651 return -1;
4652}
4653
4654void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4655 mKeyMementos.push();
4656 KeyMemento& memento = mKeyMementos.editTop();
4657 memento.deviceId = entry->deviceId;
4658 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004659 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660 memento.keyCode = entry->keyCode;
4661 memento.scanCode = entry->scanCode;
4662 memento.metaState = entry->metaState;
4663 memento.flags = flags;
4664 memento.downTime = entry->downTime;
4665 memento.policyFlags = entry->policyFlags;
4666}
4667
4668void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4669 int32_t flags, bool hovering) {
4670 mMotionMementos.push();
4671 MotionMemento& memento = mMotionMementos.editTop();
4672 memento.deviceId = entry->deviceId;
4673 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004674 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675 memento.flags = flags;
4676 memento.xPrecision = entry->xPrecision;
4677 memento.yPrecision = entry->yPrecision;
4678 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679 memento.setPointers(entry);
4680 memento.hovering = hovering;
4681 memento.policyFlags = entry->policyFlags;
4682}
4683
4684void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4685 pointerCount = entry->pointerCount;
4686 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4687 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4688 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4689 }
4690}
4691
4692void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4693 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4694 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4695 const KeyMemento& memento = mKeyMementos.itemAt(i);
4696 if (shouldCancelKey(memento, options)) {
4697 outEvents.push(new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004698 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4700 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4701 }
4702 }
4703
4704 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4705 const MotionMemento& memento = mMotionMementos.itemAt(i);
4706 if (shouldCancelMotion(memento, options)) {
4707 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004708 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709 memento.hovering
4710 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4711 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004712 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004714 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4715 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 }
4717 }
4718}
4719
4720void InputDispatcher::InputState::clear() {
4721 mKeyMementos.clear();
4722 mMotionMementos.clear();
4723 mFallbackKeys.clear();
4724}
4725
4726void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4727 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4728 const MotionMemento& memento = mMotionMementos.itemAt(i);
4729 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4730 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4731 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4732 if (memento.deviceId == otherMemento.deviceId
4733 && memento.source == otherMemento.source
4734 && memento.displayId == otherMemento.displayId) {
4735 other.mMotionMementos.removeAt(j);
4736 } else {
4737 j += 1;
4738 }
4739 }
4740 other.mMotionMementos.push(memento);
4741 }
4742 }
4743}
4744
4745int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4746 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4747 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4748}
4749
4750void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4751 int32_t fallbackKeyCode) {
4752 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4753 if (index >= 0) {
4754 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4755 } else {
4756 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4757 }
4758}
4759
4760void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4761 mFallbackKeys.removeItem(originalKeyCode);
4762}
4763
4764bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4765 const CancelationOptions& options) {
4766 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4767 return false;
4768 }
4769
4770 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4771 return false;
4772 }
4773
4774 switch (options.mode) {
4775 case CancelationOptions::CANCEL_ALL_EVENTS:
4776 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4777 return true;
4778 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4779 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004780 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4781 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 default:
4783 return false;
4784 }
4785}
4786
4787bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4788 const CancelationOptions& options) {
4789 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4790 return false;
4791 }
4792
4793 switch (options.mode) {
4794 case CancelationOptions::CANCEL_ALL_EVENTS:
4795 return true;
4796 case CancelationOptions::CANCEL_POINTER_EVENTS:
4797 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4798 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4799 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004800 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4801 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 default:
4803 return false;
4804 }
4805}
4806
4807
4808// --- InputDispatcher::Connection ---
4809
Robert Carr803535b2018-08-02 16:38:15 -07004810InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4811 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 monitor(monitor),
4813 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4814}
4815
4816InputDispatcher::Connection::~Connection() {
4817}
4818
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004819const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004820 if (inputChannel != nullptr) {
4821 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 }
4823 if (monitor) {
4824 return "monitor";
4825 }
4826 return "?";
4827}
4828
4829const char* InputDispatcher::Connection::getStatusLabel() const {
4830 switch (status) {
4831 case STATUS_NORMAL:
4832 return "NORMAL";
4833
4834 case STATUS_BROKEN:
4835 return "BROKEN";
4836
4837 case STATUS_ZOMBIE:
4838 return "ZOMBIE";
4839
4840 default:
4841 return "UNKNOWN";
4842 }
4843}
4844
4845InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004846 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 if (entry->seq == seq) {
4848 return entry;
4849 }
4850 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004851 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852}
4853
4854
4855// --- InputDispatcher::CommandEntry ---
4856
4857InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004858 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 seq(0), handled(false) {
4860}
4861
4862InputDispatcher::CommandEntry::~CommandEntry() {
4863}
4864
4865
4866// --- InputDispatcher::TouchState ---
4867
4868InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004869 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870}
4871
4872InputDispatcher::TouchState::~TouchState() {
4873}
4874
4875void InputDispatcher::TouchState::reset() {
4876 down = false;
4877 split = false;
4878 deviceId = -1;
4879 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004880 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 windows.clear();
4882}
4883
4884void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4885 down = other.down;
4886 split = other.split;
4887 deviceId = other.deviceId;
4888 source = other.source;
4889 displayId = other.displayId;
4890 windows = other.windows;
4891}
4892
4893void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4894 int32_t targetFlags, BitSet32 pointerIds) {
4895 if (targetFlags & InputTarget::FLAG_SPLIT) {
4896 split = true;
4897 }
4898
4899 for (size_t i = 0; i < windows.size(); i++) {
4900 TouchedWindow& touchedWindow = windows.editItemAt(i);
4901 if (touchedWindow.windowHandle == windowHandle) {
4902 touchedWindow.targetFlags |= targetFlags;
4903 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4904 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4905 }
4906 touchedWindow.pointerIds.value |= pointerIds.value;
4907 return;
4908 }
4909 }
4910
4911 windows.push();
4912
4913 TouchedWindow& touchedWindow = windows.editTop();
4914 touchedWindow.windowHandle = windowHandle;
4915 touchedWindow.targetFlags = targetFlags;
4916 touchedWindow.pointerIds = pointerIds;
4917}
4918
4919void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4920 for (size_t i = 0; i < windows.size(); i++) {
4921 if (windows.itemAt(i).windowHandle == windowHandle) {
4922 windows.removeAt(i);
4923 return;
4924 }
4925 }
4926}
4927
Robert Carr803535b2018-08-02 16:38:15 -07004928void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4929 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004930 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004931 windows.removeAt(i);
4932 return;
4933 }
4934 }
4935}
4936
Michael Wrightd02c5b62014-02-10 15:10:22 -08004937void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4938 for (size_t i = 0 ; i < windows.size(); ) {
4939 TouchedWindow& window = windows.editItemAt(i);
4940 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4941 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4942 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4943 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4944 i += 1;
4945 } else {
4946 windows.removeAt(i);
4947 }
4948 }
4949}
4950
4951sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4952 for (size_t i = 0; i < windows.size(); i++) {
4953 const TouchedWindow& window = windows.itemAt(i);
4954 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4955 return window.windowHandle;
4956 }
4957 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004958 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959}
4960
4961bool InputDispatcher::TouchState::isSlippery() const {
4962 // Must have exactly one foreground window.
4963 bool haveSlipperyForegroundWindow = false;
4964 for (size_t i = 0; i < windows.size(); i++) {
4965 const TouchedWindow& window = windows.itemAt(i);
4966 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4967 if (haveSlipperyForegroundWindow
4968 || !(window.windowHandle->getInfo()->layoutParamsFlags
4969 & InputWindowInfo::FLAG_SLIPPERY)) {
4970 return false;
4971 }
4972 haveSlipperyForegroundWindow = true;
4973 }
4974 }
4975 return haveSlipperyForegroundWindow;
4976}
4977
4978
4979// --- InputDispatcherThread ---
4980
4981InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4982 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4983}
4984
4985InputDispatcherThread::~InputDispatcherThread() {
4986}
4987
4988bool InputDispatcherThread::threadLoop() {
4989 mDispatcher->dispatchOnce();
4990 return true;
4991}
4992
4993} // namespace android