blob: 7ba2d949516526cdace34c510223531d65401b3a [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
20//#define LOG_NDEBUG 0
21
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
38#define DEBUG_FOCUS 0
39
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wrightd02c5b62014-02-10 15:10:22 -080048#include <errno.h>
49#include <limits.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080050#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070051#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080052#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070053#include <unistd.h>
54
Michael Wright2b3c3302018-03-02 17:19:13 +000055#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080056#include <android-base/stringprintf.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070057#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <utils/Trace.h>
59#include <powermanager/PowerManager.h>
60#include <ui/Region.h>
Robert Carr4e670e52018-08-15 13:26:12 -070061#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080062
63#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66#define INDENT4 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
72// Default input dispatching timeout if there is no focused application or paused window
73// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000074constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
76// Amount of time to allow for all pending events to be processed when an app switch
77// key is on the way. This is used to preempt input dispatch and drop input events
78// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000079constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080080
81// Amount of time to allow for an event to be dispatched (measured since its eventTime)
82// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000083constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85// Amount of time to allow touch events to be streamed out to a connection before requiring
86// that the first event be finished. This value extends the ANR timeout by the specified
87// amount. For example, if streaming is allowed to get ahead by one second relative to the
88// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000089constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
91// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000092constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
93
94// Log a warning when an interception call takes longer than this to process.
95constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
97// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +000098constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
99
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100
101static inline nsecs_t now() {
102 return systemTime(SYSTEM_TIME_MONOTONIC);
103}
104
105static inline const char* toString(bool value) {
106 return value ? "true" : "false";
107}
108
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800109static std::string motionActionToString(int32_t action) {
110 // Convert MotionEvent action to string
111 switch(action & AMOTION_EVENT_ACTION_MASK) {
112 case AMOTION_EVENT_ACTION_DOWN:
113 return "DOWN";
114 case AMOTION_EVENT_ACTION_MOVE:
115 return "MOVE";
116 case AMOTION_EVENT_ACTION_UP:
117 return "UP";
118 case AMOTION_EVENT_ACTION_POINTER_DOWN:
119 return "POINTER_DOWN";
120 case AMOTION_EVENT_ACTION_POINTER_UP:
121 return "POINTER_UP";
122 }
123 return StringPrintf("%" PRId32, action);
124}
125
126static std::string keyActionToString(int32_t action) {
127 // Convert KeyEvent action to string
128 switch(action) {
129 case AKEY_EVENT_ACTION_DOWN:
130 return "DOWN";
131 case AKEY_EVENT_ACTION_UP:
132 return "UP";
133 case AKEY_EVENT_ACTION_MULTIPLE:
134 return "MULTIPLE";
135 }
136 return StringPrintf("%" PRId32, action);
137}
138
Michael Wrightd02c5b62014-02-10 15:10:22 -0800139static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
140 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
141 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
142}
143
144static bool isValidKeyAction(int32_t action) {
145 switch (action) {
146 case AKEY_EVENT_ACTION_DOWN:
147 case AKEY_EVENT_ACTION_UP:
148 return true;
149 default:
150 return false;
151 }
152}
153
154static bool validateKeyEvent(int32_t action) {
155 if (! isValidKeyAction(action)) {
156 ALOGE("Key event has invalid action code 0x%x", action);
157 return false;
158 }
159 return true;
160}
161
Michael Wright7b159c92015-05-14 14:48:03 +0100162static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800163 switch (action & AMOTION_EVENT_ACTION_MASK) {
164 case AMOTION_EVENT_ACTION_DOWN:
165 case AMOTION_EVENT_ACTION_UP:
166 case AMOTION_EVENT_ACTION_CANCEL:
167 case AMOTION_EVENT_ACTION_MOVE:
168 case AMOTION_EVENT_ACTION_OUTSIDE:
169 case AMOTION_EVENT_ACTION_HOVER_ENTER:
170 case AMOTION_EVENT_ACTION_HOVER_MOVE:
171 case AMOTION_EVENT_ACTION_HOVER_EXIT:
172 case AMOTION_EVENT_ACTION_SCROLL:
173 return true;
174 case AMOTION_EVENT_ACTION_POINTER_DOWN:
175 case AMOTION_EVENT_ACTION_POINTER_UP: {
176 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800177 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800178 }
Michael Wright7b159c92015-05-14 14:48:03 +0100179 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
180 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
181 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800182 default:
183 return false;
184 }
185}
186
Michael Wright7b159c92015-05-14 14:48:03 +0100187static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800188 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100189 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190 ALOGE("Motion event has invalid action code 0x%x", action);
191 return false;
192 }
193 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000194 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800195 pointerCount, MAX_POINTERS);
196 return false;
197 }
198 BitSet32 pointerIdBits;
199 for (size_t i = 0; i < pointerCount; i++) {
200 int32_t id = pointerProperties[i].id;
201 if (id < 0 || id > MAX_POINTER_ID) {
202 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
203 id, MAX_POINTER_ID);
204 return false;
205 }
206 if (pointerIdBits.hasBit(id)) {
207 ALOGE("Motion event has duplicate pointer id %d", id);
208 return false;
209 }
210 pointerIdBits.markBit(id);
211 }
212 return true;
213}
214
215static bool isMainDisplay(int32_t displayId) {
216 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
217}
218
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800219static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800221 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 return;
223 }
224
225 bool first = true;
226 Region::const_iterator cur = region.begin();
227 Region::const_iterator const tail = region.end();
228 while (cur != tail) {
229 if (first) {
230 first = false;
231 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800232 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800234 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800235 cur++;
236 }
237}
238
Tiger Huang721e26f2018-07-24 22:26:19 +0800239template<typename T, typename U>
240static T getValueByKey(std::unordered_map<U, T>& map, U key) {
241 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
242 return it != map.end() ? it->second : T{};
243}
244
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245
246// --- InputDispatcher ---
247
248InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
249 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700250 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100251 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700252 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800254 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
256 mLooper = new Looper(false);
257
Yi Kong9b14ac62018-07-17 13:48:38 -0700258 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259
260 policy->getDispatcherConfiguration(&mConfig);
261}
262
263InputDispatcher::~InputDispatcher() {
264 { // acquire lock
265 AutoMutex _l(mLock);
266
267 resetKeyRepeatLocked();
268 releasePendingEventLocked();
269 drainInboundQueueLocked();
270 }
271
272 while (mConnectionsByFd.size() != 0) {
273 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
274 }
275}
276
277void InputDispatcher::dispatchOnce() {
278 nsecs_t nextWakeupTime = LONG_LONG_MAX;
279 { // acquire lock
280 AutoMutex _l(mLock);
281 mDispatcherIsAliveCondition.broadcast();
282
283 // Run a dispatch loop if there are no pending commands.
284 // The dispatch loop might enqueue commands to run afterwards.
285 if (!haveCommandsLocked()) {
286 dispatchOnceInnerLocked(&nextWakeupTime);
287 }
288
289 // Run all pending commands if there are any.
290 // If any commands were run then force the next poll to wake up immediately.
291 if (runCommandsLockedInterruptible()) {
292 nextWakeupTime = LONG_LONG_MIN;
293 }
294 } // release lock
295
296 // Wait for callback or timeout or wake. (make sure we round up, not down)
297 nsecs_t currentTime = now();
298 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
299 mLooper->pollOnce(timeoutMillis);
300}
301
302void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
303 nsecs_t currentTime = now();
304
Jeff Browndc5992e2014-04-11 01:27:26 -0700305 // Reset the key repeat timer whenever normal dispatch is suspended while the
306 // device is in a non-interactive state. This is to ensure that we abort a key
307 // repeat if the device is just coming out of sleep.
308 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800309 resetKeyRepeatLocked();
310 }
311
312 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
313 if (mDispatchFrozen) {
314#if DEBUG_FOCUS
315 ALOGD("Dispatch frozen. Waiting some more.");
316#endif
317 return;
318 }
319
320 // Optimize latency of app switches.
321 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
322 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
323 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
324 if (mAppSwitchDueTime < *nextWakeupTime) {
325 *nextWakeupTime = mAppSwitchDueTime;
326 }
327
328 // Ready to start a new event.
329 // If we don't already have a pending event, go grab one.
330 if (! mPendingEvent) {
331 if (mInboundQueue.isEmpty()) {
332 if (isAppSwitchDue) {
333 // The inbound queue is empty so the app switch key we were waiting
334 // for will never arrive. Stop waiting for it.
335 resetPendingAppSwitchLocked(false);
336 isAppSwitchDue = false;
337 }
338
339 // Synthesize a key repeat if appropriate.
340 if (mKeyRepeatState.lastKeyEntry) {
341 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
342 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
343 } else {
344 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
345 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
346 }
347 }
348 }
349
350 // Nothing to do if there is no pending event.
351 if (!mPendingEvent) {
352 return;
353 }
354 } else {
355 // Inbound queue has at least one entry.
356 mPendingEvent = mInboundQueue.dequeueAtHead();
357 traceInboundQueueLengthLocked();
358 }
359
360 // Poke user activity for this event.
361 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
362 pokeUserActivityLocked(mPendingEvent);
363 }
364
365 // Get ready to dispatch the event.
366 resetANRTimeoutsLocked();
367 }
368
369 // Now we have an event to dispatch.
370 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700371 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372 bool done = false;
373 DropReason dropReason = DROP_REASON_NOT_DROPPED;
374 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
375 dropReason = DROP_REASON_POLICY;
376 } else if (!mDispatchEnabled) {
377 dropReason = DROP_REASON_DISABLED;
378 }
379
380 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700381 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800382 }
383
384 switch (mPendingEvent->type) {
385 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
386 ConfigurationChangedEntry* typedEntry =
387 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
388 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
389 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
390 break;
391 }
392
393 case EventEntry::TYPE_DEVICE_RESET: {
394 DeviceResetEntry* typedEntry =
395 static_cast<DeviceResetEntry*>(mPendingEvent);
396 done = dispatchDeviceResetLocked(currentTime, typedEntry);
397 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
398 break;
399 }
400
401 case EventEntry::TYPE_KEY: {
402 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
403 if (isAppSwitchDue) {
404 if (isAppSwitchKeyEventLocked(typedEntry)) {
405 resetPendingAppSwitchLocked(true);
406 isAppSwitchDue = false;
407 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
408 dropReason = DROP_REASON_APP_SWITCH;
409 }
410 }
411 if (dropReason == DROP_REASON_NOT_DROPPED
412 && isStaleEventLocked(currentTime, typedEntry)) {
413 dropReason = DROP_REASON_STALE;
414 }
415 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
416 dropReason = DROP_REASON_BLOCKED;
417 }
418 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
419 break;
420 }
421
422 case EventEntry::TYPE_MOTION: {
423 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
424 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
425 dropReason = DROP_REASON_APP_SWITCH;
426 }
427 if (dropReason == DROP_REASON_NOT_DROPPED
428 && isStaleEventLocked(currentTime, typedEntry)) {
429 dropReason = DROP_REASON_STALE;
430 }
431 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
432 dropReason = DROP_REASON_BLOCKED;
433 }
434 done = dispatchMotionLocked(currentTime, typedEntry,
435 &dropReason, nextWakeupTime);
436 break;
437 }
438
439 default:
440 ALOG_ASSERT(false);
441 break;
442 }
443
444 if (done) {
445 if (dropReason != DROP_REASON_NOT_DROPPED) {
446 dropInboundEventLocked(mPendingEvent, dropReason);
447 }
Michael Wright3a981722015-06-10 15:26:13 +0100448 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449
450 releasePendingEventLocked();
451 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
452 }
453}
454
455bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
456 bool needWake = mInboundQueue.isEmpty();
457 mInboundQueue.enqueueAtTail(entry);
458 traceInboundQueueLengthLocked();
459
460 switch (entry->type) {
461 case EventEntry::TYPE_KEY: {
462 // Optimize app switch latency.
463 // If the application takes too long to catch up then we drop all events preceding
464 // the app switch key.
465 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
466 if (isAppSwitchKeyEventLocked(keyEntry)) {
467 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
468 mAppSwitchSawKeyDown = true;
469 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
470 if (mAppSwitchSawKeyDown) {
471#if DEBUG_APP_SWITCH
472 ALOGD("App switch is pending!");
473#endif
474 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
475 mAppSwitchSawKeyDown = false;
476 needWake = true;
477 }
478 }
479 }
480 break;
481 }
482
483 case EventEntry::TYPE_MOTION: {
484 // Optimize case where the current application is unresponsive and the user
485 // decides to touch a window in a different application.
486 // If the application takes too long to catch up then we drop all events preceding
487 // the touch into the other window.
488 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
489 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
490 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
491 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Yi Kong9b14ac62018-07-17 13:48:38 -0700492 && mInputTargetWaitApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 int32_t displayId = motionEntry->displayId;
494 int32_t x = int32_t(motionEntry->pointerCoords[0].
495 getAxisValue(AMOTION_EVENT_AXIS_X));
496 int32_t y = int32_t(motionEntry->pointerCoords[0].
497 getAxisValue(AMOTION_EVENT_AXIS_Y));
498 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700499 if (touchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500 && touchedWindowHandle->inputApplicationHandle
501 != mInputTargetWaitApplicationHandle) {
502 // User touched a different application than the one we are waiting on.
503 // Flag the event, and start pruning the input queue.
504 mNextUnblockedEvent = motionEntry;
505 needWake = true;
506 }
507 }
508 break;
509 }
510 }
511
512 return needWake;
513}
514
515void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
516 entry->refCount += 1;
517 mRecentQueue.enqueueAtTail(entry);
518 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
519 mRecentQueue.dequeueAtHead()->release();
520 }
521}
522
523sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
524 int32_t x, int32_t y) {
525 // Traverse windows from front to back to find touched window.
Arthur Hungb92218b2018-08-14 12:00:21 +0800526 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
527 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800529 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 const InputWindowInfo* windowInfo = windowHandle->getInfo();
531 if (windowInfo->displayId == displayId) {
532 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533
534 if (windowInfo->visible) {
535 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
536 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
537 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
538 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
539 // Found window.
540 return windowHandle;
541 }
542 }
543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 }
545 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700546 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547}
548
549void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
550 const char* reason;
551 switch (dropReason) {
552 case DROP_REASON_POLICY:
553#if DEBUG_INBOUND_EVENT_DETAILS
554 ALOGD("Dropped event because policy consumed it.");
555#endif
556 reason = "inbound event was dropped because the policy consumed it";
557 break;
558 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100559 if (mLastDropReason != DROP_REASON_DISABLED) {
560 ALOGI("Dropped event because input dispatch is disabled.");
561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 reason = "inbound event was dropped because input dispatch is disabled";
563 break;
564 case DROP_REASON_APP_SWITCH:
565 ALOGI("Dropped event because of pending overdue app switch.");
566 reason = "inbound event was dropped because of pending overdue app switch";
567 break;
568 case DROP_REASON_BLOCKED:
569 ALOGI("Dropped event because the current application is not responding and the user "
570 "has started interacting with a different application.");
571 reason = "inbound event was dropped because the current application is not responding "
572 "and the user has started interacting with a different application";
573 break;
574 case DROP_REASON_STALE:
575 ALOGI("Dropped event because it is stale.");
576 reason = "inbound event was dropped because it is stale";
577 break;
578 default:
579 ALOG_ASSERT(false);
580 return;
581 }
582
583 switch (entry->type) {
584 case EventEntry::TYPE_KEY: {
585 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
586 synthesizeCancelationEventsForAllConnectionsLocked(options);
587 break;
588 }
589 case EventEntry::TYPE_MOTION: {
590 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
591 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
592 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
593 synthesizeCancelationEventsForAllConnectionsLocked(options);
594 } else {
595 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
596 synthesizeCancelationEventsForAllConnectionsLocked(options);
597 }
598 break;
599 }
600 }
601}
602
603bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
604 return keyCode == AKEYCODE_HOME
605 || keyCode == AKEYCODE_ENDCALL
606 || keyCode == AKEYCODE_APP_SWITCH;
607}
608
609bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
610 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
611 && isAppSwitchKeyCode(keyEntry->keyCode)
612 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
613 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
614}
615
616bool InputDispatcher::isAppSwitchPendingLocked() {
617 return mAppSwitchDueTime != LONG_LONG_MAX;
618}
619
620void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
621 mAppSwitchDueTime = LONG_LONG_MAX;
622
623#if DEBUG_APP_SWITCH
624 if (handled) {
625 ALOGD("App switch has arrived.");
626 } else {
627 ALOGD("App switch was abandoned.");
628 }
629#endif
630}
631
632bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
633 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
634}
635
636bool InputDispatcher::haveCommandsLocked() const {
637 return !mCommandQueue.isEmpty();
638}
639
640bool InputDispatcher::runCommandsLockedInterruptible() {
641 if (mCommandQueue.isEmpty()) {
642 return false;
643 }
644
645 do {
646 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
647
648 Command command = commandEntry->command;
649 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
650
651 commandEntry->connection.clear();
652 delete commandEntry;
653 } while (! mCommandQueue.isEmpty());
654 return true;
655}
656
657InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
658 CommandEntry* commandEntry = new CommandEntry(command);
659 mCommandQueue.enqueueAtTail(commandEntry);
660 return commandEntry;
661}
662
663void InputDispatcher::drainInboundQueueLocked() {
664 while (! mInboundQueue.isEmpty()) {
665 EventEntry* entry = mInboundQueue.dequeueAtHead();
666 releaseInboundEventLocked(entry);
667 }
668 traceInboundQueueLengthLocked();
669}
670
671void InputDispatcher::releasePendingEventLocked() {
672 if (mPendingEvent) {
673 resetANRTimeoutsLocked();
674 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700675 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800676 }
677}
678
679void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
680 InjectionState* injectionState = entry->injectionState;
681 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
682#if DEBUG_DISPATCH_CYCLE
683 ALOGD("Injected inbound event was dropped.");
684#endif
685 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
686 }
687 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700688 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 }
690 addRecentEventLocked(entry);
691 entry->release();
692}
693
694void InputDispatcher::resetKeyRepeatLocked() {
695 if (mKeyRepeatState.lastKeyEntry) {
696 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700697 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 }
699}
700
701InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
702 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
703
704 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700705 uint32_t policyFlags = entry->policyFlags &
706 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 if (entry->refCount == 1) {
708 entry->recycle();
709 entry->eventTime = currentTime;
710 entry->policyFlags = policyFlags;
711 entry->repeatCount += 1;
712 } else {
713 KeyEntry* newEntry = new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100714 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800715 entry->action, entry->flags, entry->keyCode, entry->scanCode,
716 entry->metaState, entry->repeatCount + 1, entry->downTime);
717
718 mKeyRepeatState.lastKeyEntry = newEntry;
719 entry->release();
720
721 entry = newEntry;
722 }
723 entry->syntheticRepeat = true;
724
725 // Increment reference count since we keep a reference to the event in
726 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
727 entry->refCount += 1;
728
729 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
730 return entry;
731}
732
733bool InputDispatcher::dispatchConfigurationChangedLocked(
734 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
735#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700736 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737#endif
738
739 // Reset key repeating in case a keyboard device was added or removed or something.
740 resetKeyRepeatLocked();
741
742 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
743 CommandEntry* commandEntry = postCommandLocked(
744 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
745 commandEntry->eventTime = entry->eventTime;
746 return true;
747}
748
749bool InputDispatcher::dispatchDeviceResetLocked(
750 nsecs_t currentTime, DeviceResetEntry* entry) {
751#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700752 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
753 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754#endif
755
756 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
757 "device was reset");
758 options.deviceId = entry->deviceId;
759 synthesizeCancelationEventsForAllConnectionsLocked(options);
760 return true;
761}
762
763bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
764 DropReason* dropReason, nsecs_t* nextWakeupTime) {
765 // Preprocessing.
766 if (! entry->dispatchInProgress) {
767 if (entry->repeatCount == 0
768 && entry->action == AKEY_EVENT_ACTION_DOWN
769 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
770 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
771 if (mKeyRepeatState.lastKeyEntry
772 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
773 // We have seen two identical key downs in a row which indicates that the device
774 // driver is automatically generating key repeats itself. We take note of the
775 // repeat here, but we disable our own next key repeat timer since it is clear that
776 // we will not need to synthesize key repeats ourselves.
777 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
778 resetKeyRepeatLocked();
779 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
780 } else {
781 // Not a repeat. Save key down state in case we do see a repeat later.
782 resetKeyRepeatLocked();
783 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
784 }
785 mKeyRepeatState.lastKeyEntry = entry;
786 entry->refCount += 1;
787 } else if (! entry->syntheticRepeat) {
788 resetKeyRepeatLocked();
789 }
790
791 if (entry->repeatCount == 1) {
792 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
793 } else {
794 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
795 }
796
797 entry->dispatchInProgress = true;
798
799 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
800 }
801
802 // Handle case where the policy asked us to try again later last time.
803 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
804 if (currentTime < entry->interceptKeyWakeupTime) {
805 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
806 *nextWakeupTime = entry->interceptKeyWakeupTime;
807 }
808 return false; // wait until next wakeup
809 }
810 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
811 entry->interceptKeyWakeupTime = 0;
812 }
813
814 // Give the policy a chance to intercept the key.
815 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
816 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
817 CommandEntry* commandEntry = postCommandLocked(
818 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800819 sp<InputWindowHandle> focusedWindowHandle =
820 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
821 if (focusedWindowHandle != nullptr) {
Robert Carr803535b2018-08-02 16:38:15 -0700822 commandEntry->inputChannel = focusedWindowHandle->getInputChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 }
824 commandEntry->keyEntry = entry;
825 entry->refCount += 1;
826 return false; // wait for the command to run
827 } else {
828 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
829 }
830 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
831 if (*dropReason == DROP_REASON_NOT_DROPPED) {
832 *dropReason = DROP_REASON_POLICY;
833 }
834 }
835
836 // Clean up if dropping the event.
837 if (*dropReason != DROP_REASON_NOT_DROPPED) {
838 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
839 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
840 return true;
841 }
842
843 // Identify targets.
844 Vector<InputTarget> inputTargets;
845 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
846 entry, inputTargets, nextWakeupTime);
847 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
848 return false;
849 }
850
851 setInjectionResultLocked(entry, injectionResult);
852 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
853 return true;
854 }
855
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800856 // Add monitor channels from event's or focused display.
857 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858
859 // Dispatch the key.
860 dispatchEventLocked(currentTime, entry, inputTargets);
861 return true;
862}
863
864void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
865#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100866 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
867 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung3b413f22018-10-26 18:05:34 +0800868 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64 ", displayId=%" PRId32,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100870 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung3b413f22018-10-26 18:05:34 +0800872 entry->repeatCount, entry->downTime, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873#endif
874}
875
876bool InputDispatcher::dispatchMotionLocked(
877 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
878 // Preprocessing.
879 if (! entry->dispatchInProgress) {
880 entry->dispatchInProgress = true;
881
882 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
883 }
884
885 // Clean up if dropping the event.
886 if (*dropReason != DROP_REASON_NOT_DROPPED) {
887 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
888 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
889 return true;
890 }
891
892 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
893
894 // Identify targets.
895 Vector<InputTarget> inputTargets;
896
897 bool conflictingPointerActions = false;
898 int32_t injectionResult;
899 if (isPointerEvent) {
900 // Pointer event. (eg. touchscreen)
901 injectionResult = findTouchedWindowTargetsLocked(currentTime,
902 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
903 } else {
904 // Non touch event. (eg. trackball)
905 injectionResult = findFocusedWindowTargetsLocked(currentTime,
906 entry, inputTargets, nextWakeupTime);
907 }
908 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
909 return false;
910 }
911
912 setInjectionResultLocked(entry, injectionResult);
913 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100914 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
915 CancelationOptions::Mode mode(isPointerEvent ?
916 CancelationOptions::CANCEL_POINTER_EVENTS :
917 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
918 CancelationOptions options(mode, "input event injection failed");
919 synthesizeCancelationEventsForMonitorsLocked(options);
920 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 return true;
922 }
923
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800924 // Add monitor channels from event's or focused display.
925 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926
927 // Dispatch the motion.
928 if (conflictingPointerActions) {
929 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
930 "conflicting pointer actions");
931 synthesizeCancelationEventsForAllConnectionsLocked(options);
932 }
933 dispatchEventLocked(currentTime, entry, inputTargets);
934 return true;
935}
936
937
938void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
939#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800940 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
941 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100942 "action=0x%x, actionButton=0x%x, flags=0x%x, "
943 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung3b413f22018-10-26 18:05:34 +0800944 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64", displayId=%" PRId32,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800946 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100947 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948 entry->metaState, entry->buttonState,
949 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung3b413f22018-10-26 18:05:34 +0800950 entry->downTime, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951
952 for (uint32_t i = 0; i < entry->pointerCount; i++) {
953 ALOGD(" Pointer %d: id=%d, toolType=%d, "
954 "x=%f, y=%f, pressure=%f, size=%f, "
955 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800956 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 i, entry->pointerProperties[i].id,
958 entry->pointerProperties[i].toolType,
959 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
960 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
961 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
962 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
963 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
964 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
965 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
966 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800967 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968 }
969#endif
970}
971
972void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
973 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
974#if DEBUG_DISPATCH_CYCLE
975 ALOGD("dispatchEventToCurrentInputTargets");
976#endif
977
978 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
979
980 pokeUserActivityLocked(eventEntry);
981
982 for (size_t i = 0; i < inputTargets.size(); i++) {
983 const InputTarget& inputTarget = inputTargets.itemAt(i);
984
985 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
986 if (connectionIndex >= 0) {
987 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
988 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
989 } else {
990#if DEBUG_FOCUS
991 ALOGD("Dropping event delivery to target with channel '%s' because it "
992 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800993 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994#endif
995 }
996 }
997}
998
999int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1000 const EventEntry* entry,
1001 const sp<InputApplicationHandle>& applicationHandle,
1002 const sp<InputWindowHandle>& windowHandle,
1003 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001004 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1006#if DEBUG_FOCUS
1007 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1008#endif
1009 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1010 mInputTargetWaitStartTime = currentTime;
1011 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1012 mInputTargetWaitTimeoutExpired = false;
1013 mInputTargetWaitApplicationHandle.clear();
1014 }
1015 } else {
1016 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1017#if DEBUG_FOCUS
1018 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001019 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 reason);
1021#endif
1022 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001023 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001025 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001026 timeout = applicationHandle->getDispatchingTimeout(
1027 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1028 } else {
1029 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1030 }
1031
1032 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1033 mInputTargetWaitStartTime = currentTime;
1034 mInputTargetWaitTimeoutTime = currentTime + timeout;
1035 mInputTargetWaitTimeoutExpired = false;
1036 mInputTargetWaitApplicationHandle.clear();
1037
Yi Kong9b14ac62018-07-17 13:48:38 -07001038 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
1040 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001041 if (mInputTargetWaitApplicationHandle == nullptr && applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 mInputTargetWaitApplicationHandle = applicationHandle;
1043 }
1044 }
1045 }
1046
1047 if (mInputTargetWaitTimeoutExpired) {
1048 return INPUT_EVENT_INJECTION_TIMED_OUT;
1049 }
1050
1051 if (currentTime >= mInputTargetWaitTimeoutTime) {
1052 onANRLocked(currentTime, applicationHandle, windowHandle,
1053 entry->eventTime, mInputTargetWaitStartTime, reason);
1054
1055 // Force poll loop to wake up immediately on next iteration once we get the
1056 // ANR response back from the policy.
1057 *nextWakeupTime = LONG_LONG_MIN;
1058 return INPUT_EVENT_INJECTION_PENDING;
1059 } else {
1060 // Force poll loop to wake up when timeout is due.
1061 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1062 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1063 }
1064 return INPUT_EVENT_INJECTION_PENDING;
1065 }
1066}
1067
Robert Carr803535b2018-08-02 16:38:15 -07001068void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1069 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1070 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1071 state.removeWindowByToken(token);
1072 }
1073}
1074
Michael Wrightd02c5b62014-02-10 15:10:22 -08001075void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1076 const sp<InputChannel>& inputChannel) {
1077 if (newTimeout > 0) {
1078 // Extend the timeout.
1079 mInputTargetWaitTimeoutTime = now() + newTimeout;
1080 } else {
1081 // Give up.
1082 mInputTargetWaitTimeoutExpired = true;
1083
1084 // Input state will not be realistic. Mark it out of sync.
1085 if (inputChannel.get()) {
1086 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1087 if (connectionIndex >= 0) {
1088 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001089 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090
Robert Carr803535b2018-08-02 16:38:15 -07001091 if (token != nullptr) {
1092 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001093 }
1094
1095 if (connection->status == Connection::STATUS_NORMAL) {
1096 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1097 "application not responding");
1098 synthesizeCancelationEventsForConnectionLocked(connection, options);
1099 }
1100 }
1101 }
1102 }
1103}
1104
1105nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1106 nsecs_t currentTime) {
1107 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1108 return currentTime - mInputTargetWaitStartTime;
1109 }
1110 return 0;
1111}
1112
1113void InputDispatcher::resetANRTimeoutsLocked() {
1114#if DEBUG_FOCUS
1115 ALOGD("Resetting ANR timeouts.");
1116#endif
1117
1118 // Reset input target wait timeout.
1119 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1120 mInputTargetWaitApplicationHandle.clear();
1121}
1122
Tiger Huang721e26f2018-07-24 22:26:19 +08001123/**
1124 * Get the display id that the given event should go to. If this event specifies a valid display id,
1125 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1126 * Focused display is the display that the user most recently interacted with.
1127 */
1128int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1129 int32_t displayId;
1130 switch (entry->type) {
1131 case EventEntry::TYPE_KEY: {
1132 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1133 displayId = typedEntry->displayId;
1134 break;
1135 }
1136 case EventEntry::TYPE_MOTION: {
1137 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1138 displayId = typedEntry->displayId;
1139 break;
1140 }
1141 default: {
1142 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1143 return ADISPLAY_ID_NONE;
1144 }
1145 }
1146 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1147}
1148
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1150 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1151 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001152 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153
Tiger Huang721e26f2018-07-24 22:26:19 +08001154 int32_t displayId = getTargetDisplayId(entry);
1155 sp<InputWindowHandle> focusedWindowHandle =
1156 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1157 sp<InputApplicationHandle> focusedApplicationHandle =
1158 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1159
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 // If there is no currently focused window and no focused application
1161 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001162 if (focusedWindowHandle == nullptr) {
1163 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001165 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 "Waiting because no window has focus but there is a "
1167 "focused application that may eventually add a window "
1168 "when it finishes starting up.");
1169 goto Unresponsive;
1170 }
1171
Arthur Hung3b413f22018-10-26 18:05:34 +08001172 ALOGI("Dropping event because there is no focused window or focused application in display "
1173 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001174 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1175 goto Failed;
1176 }
1177
1178 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001179 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1181 goto Failed;
1182 }
1183
Jeff Brownffb49772014-10-10 19:01:34 -07001184 // Check whether the window is ready for more input.
1185 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001186 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001187 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001188 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001189 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 goto Unresponsive;
1191 }
1192
1193 // Success! Output targets.
1194 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001195 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1197 inputTargets);
1198
1199 // Done.
1200Failed:
1201Unresponsive:
1202 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1203 updateDispatchStatisticsLocked(currentTime, entry,
1204 injectionResult, timeSpentWaitingForApplication);
1205#if DEBUG_FOCUS
1206 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1207 "timeSpentWaitingForApplication=%0.1fms",
1208 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1209#endif
1210 return injectionResult;
1211}
1212
1213int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1214 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1215 bool* outConflictingPointerActions) {
1216 enum InjectionPermission {
1217 INJECTION_PERMISSION_UNKNOWN,
1218 INJECTION_PERMISSION_GRANTED,
1219 INJECTION_PERMISSION_DENIED
1220 };
1221
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 // For security reasons, we defer updating the touch state until we are sure that
1223 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 int32_t displayId = entry->displayId;
1225 int32_t action = entry->action;
1226 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1227
1228 // Update the touch state as needed based on the properties of the touch event.
1229 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1230 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1231 sp<InputWindowHandle> newHoverWindowHandle;
1232
Jeff Brownf086ddb2014-02-11 14:28:48 -08001233 // Copy current touch state into mTempTouchState.
1234 // This state is always reset at the end of this function, so if we don't find state
1235 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001236 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001237 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1238 if (oldStateIndex >= 0) {
1239 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1240 mTempTouchState.copyFrom(*oldState);
1241 }
1242
1243 bool isSplit = mTempTouchState.split;
1244 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1245 && (mTempTouchState.deviceId != entry->deviceId
1246 || mTempTouchState.source != entry->source
1247 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1249 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1250 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1251 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1252 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1253 || isHoverAction);
1254 bool wrongDevice = false;
1255 if (newGesture) {
1256 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001257 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001259 ALOGD("Dropping event because a pointer for a different device is already down "
1260 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001262 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1264 switchedDevice = false;
1265 wrongDevice = true;
1266 goto Failed;
1267 }
1268 mTempTouchState.reset();
1269 mTempTouchState.down = down;
1270 mTempTouchState.deviceId = entry->deviceId;
1271 mTempTouchState.source = entry->source;
1272 mTempTouchState.displayId = displayId;
1273 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001274 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1275#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001276 ALOGI("Dropping move event because a pointer for a different device is already active "
1277 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001278#endif
1279 // TODO: test multiple simultaneous input streams.
1280 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1281 switchedDevice = false;
1282 wrongDevice = true;
1283 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284 }
1285
1286 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1287 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1288
1289 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1290 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1291 getAxisValue(AMOTION_EVENT_AXIS_X));
1292 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1293 getAxisValue(AMOTION_EVENT_AXIS_Y));
1294 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001295 bool isTouchModal = false;
1296
1297 // Traverse windows from front to back to find touched window and outside targets.
Arthur Hungb92218b2018-08-14 12:00:21 +08001298 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1299 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001300 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001301 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1303 if (windowInfo->displayId != displayId) {
1304 continue; // wrong display
1305 }
1306
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307 int32_t flags = windowInfo->layoutParamsFlags;
1308 if (windowInfo->visible) {
1309 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1310 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1311 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1312 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001313 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 break; // found touched window, exit window loop
1315 }
1316 }
1317
1318 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1319 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001321 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 }
1323 }
1324 }
1325
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001327 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1329 // New window supports splitting.
1330 isSplit = true;
1331 } else if (isSplit) {
1332 // New window does not support splitting but we have already split events.
1333 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001334 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 }
1336
1337 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001338 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 // Try to assign the pointer to the first foreground window we find, if there is one.
1340 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001341 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001342 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1343 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1345 goto Failed;
1346 }
1347 }
1348
1349 // Set target flags.
1350 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1351 if (isSplit) {
1352 targetFlags |= InputTarget::FLAG_SPLIT;
1353 }
1354 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1355 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001356 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1357 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 }
1359
1360 // Update hover state.
1361 if (isHoverAction) {
1362 newHoverWindowHandle = newTouchedWindowHandle;
1363 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1364 newHoverWindowHandle = mLastHoverWindowHandle;
1365 }
1366
1367 // Update the temporary touch state.
1368 BitSet32 pointerIds;
1369 if (isSplit) {
1370 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1371 pointerIds.markBit(pointerId);
1372 }
1373 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1374 } else {
1375 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1376
1377 // If the pointer is not currently down, then ignore the event.
1378 if (! mTempTouchState.down) {
1379#if DEBUG_FOCUS
1380 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001381 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382#endif
1383 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1384 goto Failed;
1385 }
1386
1387 // Check whether touches should slip outside of the current foreground window.
1388 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1389 && entry->pointerCount == 1
1390 && mTempTouchState.isSlippery()) {
1391 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1392 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1393
1394 sp<InputWindowHandle> oldTouchedWindowHandle =
1395 mTempTouchState.getFirstForegroundWindowHandle();
1396 sp<InputWindowHandle> newTouchedWindowHandle =
1397 findTouchedWindowAtLocked(displayId, x, y);
1398 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001399 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001401 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001402 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001403 newTouchedWindowHandle->getName().c_str(),
1404 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405#endif
1406 // Make a slippery exit from the old window.
1407 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1408 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1409
1410 // Make a slippery entrance into the new window.
1411 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1412 isSplit = true;
1413 }
1414
1415 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1416 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1417 if (isSplit) {
1418 targetFlags |= InputTarget::FLAG_SPLIT;
1419 }
1420 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1421 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1422 }
1423
1424 BitSet32 pointerIds;
1425 if (isSplit) {
1426 pointerIds.markBit(entry->pointerProperties[0].id);
1427 }
1428 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1429 }
1430 }
1431 }
1432
1433 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1434 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001435 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436#if DEBUG_HOVER
1437 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001438 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439#endif
1440 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1441 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1442 }
1443
1444 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001445 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446#if DEBUG_HOVER
1447 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001448 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449#endif
1450 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1451 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1452 }
1453 }
1454
1455 // Check permission to inject into all touched foreground windows and ensure there
1456 // is at least one touched foreground window.
1457 {
1458 bool haveForegroundWindow = false;
1459 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1460 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1461 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1462 haveForegroundWindow = true;
1463 if (! checkInjectionPermission(touchedWindow.windowHandle,
1464 entry->injectionState)) {
1465 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1466 injectionPermission = INJECTION_PERMISSION_DENIED;
1467 goto Failed;
1468 }
1469 }
1470 }
1471 if (! haveForegroundWindow) {
1472#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001473 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1474 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475#endif
1476 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1477 goto Failed;
1478 }
1479
1480 // Permission granted to injection into all touched foreground windows.
1481 injectionPermission = INJECTION_PERMISSION_GRANTED;
1482 }
1483
1484 // Check whether windows listening for outside touches are owned by the same UID. If it is
1485 // set the policy flag that we will not reveal coordinate information to this window.
1486 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1487 sp<InputWindowHandle> foregroundWindowHandle =
1488 mTempTouchState.getFirstForegroundWindowHandle();
1489 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1490 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1491 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1492 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1493 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1494 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1495 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1496 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1497 }
1498 }
1499 }
1500 }
1501
1502 // Ensure all touched foreground windows are ready for new input.
1503 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1504 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1505 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001506 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001507 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001508 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001509 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001511 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 goto Unresponsive;
1513 }
1514 }
1515 }
1516
1517 // If this is the first pointer going down and the touched window has a wallpaper
1518 // then also add the touched wallpaper windows so they are locked in for the duration
1519 // of the touch gesture.
1520 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1521 // engine only supports touch events. We would need to add a mechanism similar
1522 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1523 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1524 sp<InputWindowHandle> foregroundWindowHandle =
1525 mTempTouchState.getFirstForegroundWindowHandle();
1526 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001527 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1528 size_t numWindows = windowHandles.size();
1529 for (size_t i = 0; i < numWindows; i++) {
1530 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 const InputWindowInfo* info = windowHandle->getInfo();
1532 if (info->displayId == displayId
1533 && windowHandle->getInfo()->layoutParamsType
1534 == InputWindowInfo::TYPE_WALLPAPER) {
1535 mTempTouchState.addOrUpdateWindow(windowHandle,
1536 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001537 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 | InputTarget::FLAG_DISPATCH_AS_IS,
1539 BitSet32(0));
1540 }
1541 }
1542 }
1543 }
1544
1545 // Success! Output targets.
1546 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1547
1548 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1549 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1550 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1551 touchedWindow.pointerIds, inputTargets);
1552 }
1553
1554 // Drop the outside or hover touch windows since we will not care about them
1555 // in the next iteration.
1556 mTempTouchState.filterNonAsIsTouchWindows();
1557
1558Failed:
1559 // Check injection permission once and for all.
1560 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001561 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 injectionPermission = INJECTION_PERMISSION_GRANTED;
1563 } else {
1564 injectionPermission = INJECTION_PERMISSION_DENIED;
1565 }
1566 }
1567
1568 // Update final pieces of touch state if the injector had permission.
1569 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1570 if (!wrongDevice) {
1571 if (switchedDevice) {
1572#if DEBUG_FOCUS
1573 ALOGD("Conflicting pointer actions: Switched to a different device.");
1574#endif
1575 *outConflictingPointerActions = true;
1576 }
1577
1578 if (isHoverAction) {
1579 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001580 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581#if DEBUG_FOCUS
1582 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1583#endif
1584 *outConflictingPointerActions = true;
1585 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001586 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1588 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001589 mTempTouchState.deviceId = entry->deviceId;
1590 mTempTouchState.source = entry->source;
1591 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 }
1593 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1594 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1595 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001596 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1598 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001599 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600#if DEBUG_FOCUS
1601 ALOGD("Conflicting pointer actions: Down received while already down.");
1602#endif
1603 *outConflictingPointerActions = true;
1604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1606 // One pointer went up.
1607 if (isSplit) {
1608 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1609 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1610
1611 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1612 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1613 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1614 touchedWindow.pointerIds.clearBit(pointerId);
1615 if (touchedWindow.pointerIds.isEmpty()) {
1616 mTempTouchState.windows.removeAt(i);
1617 continue;
1618 }
1619 }
1620 i += 1;
1621 }
1622 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001623 }
1624
1625 // Save changes unless the action was scroll in which case the temporary touch
1626 // state was only valid for this one action.
1627 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1628 if (mTempTouchState.displayId >= 0) {
1629 if (oldStateIndex >= 0) {
1630 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1631 } else {
1632 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1633 }
1634 } else if (oldStateIndex >= 0) {
1635 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1636 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001637 }
1638
1639 // Update hover state.
1640 mLastHoverWindowHandle = newHoverWindowHandle;
1641 }
1642 } else {
1643#if DEBUG_FOCUS
1644 ALOGD("Not updating touch focus because injection was denied.");
1645#endif
1646 }
1647
1648Unresponsive:
1649 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1650 mTempTouchState.reset();
1651
1652 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1653 updateDispatchStatisticsLocked(currentTime, entry,
1654 injectionResult, timeSpentWaitingForApplication);
1655#if DEBUG_FOCUS
1656 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1657 "timeSpentWaitingForApplication=%0.1fms",
1658 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1659#endif
1660 return injectionResult;
1661}
1662
1663void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1664 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1665 inputTargets.push();
1666
1667 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1668 InputTarget& target = inputTargets.editTop();
1669 target.inputChannel = windowInfo->inputChannel;
1670 target.flags = targetFlags;
1671 target.xOffset = - windowInfo->frameLeft;
1672 target.yOffset = - windowInfo->frameTop;
1673 target.scaleFactor = windowInfo->scaleFactor;
1674 target.pointerIds = pointerIds;
1675}
1676
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001677void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets,
1678 int32_t displayId) {
1679 std::unordered_map<int32_t, Vector<sp<InputChannel>>>::const_iterator it =
1680 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001682 if (it != mMonitoringChannelsByDisplay.end()) {
1683 const Vector<sp<InputChannel>>& monitoringChannels = it->second;
1684 const size_t numChannels = monitoringChannels.size();
1685 for (size_t i = 0; i < numChannels; i++) {
1686 inputTargets.push();
1687
1688 InputTarget& target = inputTargets.editTop();
1689 target.inputChannel = monitoringChannels[i];
1690 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1691 target.xOffset = 0;
1692 target.yOffset = 0;
1693 target.pointerIds.clear();
1694 target.scaleFactor = 1.0f;
1695 }
1696 } else {
1697 // If there is no monitor channel registered or all monitor channel unregistered,
1698 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001699 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 }
1701}
1702
1703bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1704 const InjectionState* injectionState) {
1705 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001706 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1708 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001709 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1711 "owned by uid %d",
1712 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001713 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 windowHandle->getInfo()->ownerUid);
1715 } else {
1716 ALOGW("Permission denied: injecting event from pid %d uid %d",
1717 injectionState->injectorPid, injectionState->injectorUid);
1718 }
1719 return false;
1720 }
1721 return true;
1722}
1723
1724bool InputDispatcher::isWindowObscuredAtPointLocked(
1725 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1726 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001727 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1728 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001730 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001731 if (otherHandle == windowHandle) {
1732 break;
1733 }
1734
1735 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1736 if (otherInfo->displayId == displayId
1737 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1738 && otherInfo->frameContainsPoint(x, y)) {
1739 return true;
1740 }
1741 }
1742 return false;
1743}
1744
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001745
1746bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1747 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001748 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001749 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hungb92218b2018-08-14 12:00:21 +08001750 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001751 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001752 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001753 if (otherHandle == windowHandle) {
1754 break;
1755 }
1756
1757 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1758 if (otherInfo->displayId == displayId
1759 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1760 && otherInfo->overlaps(windowInfo)) {
1761 return true;
1762 }
1763 }
1764 return false;
1765}
1766
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001767std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001768 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1769 const char* targetType) {
1770 // If the window is paused then keep waiting.
1771 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001772 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001773 }
1774
1775 // If the window's connection is not registered then keep waiting.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brownffb49772014-10-10 19:01:34 -07001777 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001778 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001779 "registered with the input dispatcher. The window may be in the process "
1780 "of being removed.", targetType);
1781 }
1782
1783 // If the connection is dead then keep waiting.
1784 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1785 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001786 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001787 "The window may be in the process of being removed.", targetType,
1788 connection->getStatusLabel());
1789 }
1790
1791 // If the connection is backed up then keep waiting.
1792 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001793 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001794 "Outbound queue length: %d. Wait queue length: %d.",
1795 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1796 }
1797
1798 // Ensure that the dispatch queues aren't too far backed up for this event.
1799 if (eventEntry->type == EventEntry::TYPE_KEY) {
1800 // If the event is a key event, then we must wait for all previous events to
1801 // complete before delivering it because previous events may have the
1802 // side-effect of transferring focus to a different window and we want to
1803 // ensure that the following keys are sent to the new window.
1804 //
1805 // Suppose the user touches a button in a window then immediately presses "A".
1806 // If the button causes a pop-up window to appear then we want to ensure that
1807 // the "A" key is delivered to the new pop-up window. This is because users
1808 // often anticipate pending UI changes when typing on a keyboard.
1809 // To obtain this behavior, we must serialize key events with respect to all
1810 // prior input events.
1811 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001812 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001813 "finished processing all of the input events that were previously "
1814 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1815 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001816 }
Jeff Brownffb49772014-10-10 19:01:34 -07001817 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001818 // Touch events can always be sent to a window immediately because the user intended
1819 // to touch whatever was visible at the time. Even if focus changes or a new
1820 // window appears moments later, the touch event was meant to be delivered to
1821 // whatever window happened to be on screen at the time.
1822 //
1823 // Generic motion events, such as trackball or joystick events are a little trickier.
1824 // Like key events, generic motion events are delivered to the focused window.
1825 // Unlike key events, generic motion events don't tend to transfer focus to other
1826 // windows and it is not important for them to be serialized. So we prefer to deliver
1827 // generic motion events as soon as possible to improve efficiency and reduce lag
1828 // through batching.
1829 //
1830 // The one case where we pause input event delivery is when the wait queue is piling
1831 // up with lots of events because the application is not responding.
1832 // This condition ensures that ANRs are detected reliably.
1833 if (!connection->waitQueue.isEmpty()
1834 && currentTime >= connection->waitQueue.head->deliveryTime
1835 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001836 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001837 "finished processing certain input events that were delivered to it over "
1838 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1839 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1840 connection->waitQueue.count(),
1841 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842 }
1843 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001844 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845}
1846
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001847std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 const sp<InputApplicationHandle>& applicationHandle,
1849 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001850 if (applicationHandle != nullptr) {
1851 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001852 std::string label(applicationHandle->getName());
1853 label += " - ";
1854 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 return label;
1856 } else {
1857 return applicationHandle->getName();
1858 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001859 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 return windowHandle->getName();
1861 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001862 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 }
1864}
1865
1866void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001867 int32_t displayId = getTargetDisplayId(eventEntry);
1868 sp<InputWindowHandle> focusedWindowHandle =
1869 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1870 if (focusedWindowHandle != nullptr) {
1871 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1873#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001874 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875#endif
1876 return;
1877 }
1878 }
1879
1880 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1881 switch (eventEntry->type) {
1882 case EventEntry::TYPE_MOTION: {
1883 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1884 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1885 return;
1886 }
1887
1888 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1889 eventType = USER_ACTIVITY_EVENT_TOUCH;
1890 }
1891 break;
1892 }
1893 case EventEntry::TYPE_KEY: {
1894 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1895 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1896 return;
1897 }
1898 eventType = USER_ACTIVITY_EVENT_BUTTON;
1899 break;
1900 }
1901 }
1902
1903 CommandEntry* commandEntry = postCommandLocked(
1904 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1905 commandEntry->eventTime = eventEntry->eventTime;
1906 commandEntry->userActivityEventType = eventType;
1907}
1908
1909void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1910 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1911#if DEBUG_DISPATCH_CYCLE
1912 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1913 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1914 "pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001915 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 inputTarget->xOffset, inputTarget->yOffset,
1917 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1918#endif
1919
1920 // Skip this event if the connection status is not normal.
1921 // We don't want to enqueue additional outbound events if the connection is broken.
1922 if (connection->status != Connection::STATUS_NORMAL) {
1923#if DEBUG_DISPATCH_CYCLE
1924 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001925 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926#endif
1927 return;
1928 }
1929
1930 // Split a motion event if needed.
1931 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1932 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1933
1934 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1935 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1936 MotionEntry* splitMotionEntry = splitMotionEvent(
1937 originalMotionEntry, inputTarget->pointerIds);
1938 if (!splitMotionEntry) {
1939 return; // split event was dropped
1940 }
1941#if DEBUG_FOCUS
1942 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001943 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1945#endif
1946 enqueueDispatchEntriesLocked(currentTime, connection,
1947 splitMotionEntry, inputTarget);
1948 splitMotionEntry->release();
1949 return;
1950 }
1951 }
1952
1953 // Not splitting. Enqueue dispatch entries for the event as is.
1954 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1955}
1956
1957void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1958 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1959 bool wasEmpty = connection->outboundQueue.isEmpty();
1960
1961 // Enqueue dispatch entries for the requested modes.
1962 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1963 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1964 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1965 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1966 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1967 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1968 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1969 InputTarget::FLAG_DISPATCH_AS_IS);
1970 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1971 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1972 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1973 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1974
1975 // If the outbound queue was previously empty, start the dispatch cycle going.
1976 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1977 startDispatchCycleLocked(currentTime, connection);
1978 }
1979}
1980
1981void InputDispatcher::enqueueDispatchEntryLocked(
1982 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1983 int32_t dispatchMode) {
1984 int32_t inputTargetFlags = inputTarget->flags;
1985 if (!(inputTargetFlags & dispatchMode)) {
1986 return;
1987 }
1988 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1989
1990 // This is a new event.
1991 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1992 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1993 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1994 inputTarget->scaleFactor);
1995
1996 // Apply target flags and update the connection's input state.
1997 switch (eventEntry->type) {
1998 case EventEntry::TYPE_KEY: {
1999 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2000 dispatchEntry->resolvedAction = keyEntry->action;
2001 dispatchEntry->resolvedFlags = keyEntry->flags;
2002
2003 if (!connection->inputState.trackKey(keyEntry,
2004 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2005#if DEBUG_DISPATCH_CYCLE
2006 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002007 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008#endif
2009 delete dispatchEntry;
2010 return; // skip the inconsistent event
2011 }
2012 break;
2013 }
2014
2015 case EventEntry::TYPE_MOTION: {
2016 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2017 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2018 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2019 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2020 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2021 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2022 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2023 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2024 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2025 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2026 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2027 } else {
2028 dispatchEntry->resolvedAction = motionEntry->action;
2029 }
2030 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2031 && !connection->inputState.isHovering(
2032 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2033#if DEBUG_DISPATCH_CYCLE
2034 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002035 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036#endif
2037 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2038 }
2039
2040 dispatchEntry->resolvedFlags = motionEntry->flags;
2041 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2042 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2043 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002044 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2045 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047
2048 if (!connection->inputState.trackMotion(motionEntry,
2049 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2050#if DEBUG_DISPATCH_CYCLE
2051 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002052 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053#endif
2054 delete dispatchEntry;
2055 return; // skip the inconsistent event
2056 }
2057 break;
2058 }
2059 }
2060
2061 // Remember that we are waiting for this dispatch to complete.
2062 if (dispatchEntry->hasForegroundTarget()) {
2063 incrementPendingForegroundDispatchesLocked(eventEntry);
2064 }
2065
2066 // Enqueue the dispatch entry.
2067 connection->outboundQueue.enqueueAtTail(dispatchEntry);
2068 traceOutboundQueueLengthLocked(connection);
2069}
2070
2071void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2072 const sp<Connection>& connection) {
2073#if DEBUG_DISPATCH_CYCLE
2074 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002075 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002076#endif
2077
2078 while (connection->status == Connection::STATUS_NORMAL
2079 && !connection->outboundQueue.isEmpty()) {
2080 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2081 dispatchEntry->deliveryTime = currentTime;
2082
2083 // Publish the event.
2084 status_t status;
2085 EventEntry* eventEntry = dispatchEntry->eventEntry;
2086 switch (eventEntry->type) {
2087 case EventEntry::TYPE_KEY: {
2088 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2089
2090 // Publish the key event.
2091 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002092 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2094 keyEntry->keyCode, keyEntry->scanCode,
2095 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2096 keyEntry->eventTime);
2097 break;
2098 }
2099
2100 case EventEntry::TYPE_MOTION: {
2101 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2102
2103 PointerCoords scaledCoords[MAX_POINTERS];
2104 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2105
2106 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002107 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2109 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002110 float scaleFactor = dispatchEntry->scaleFactor;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 xOffset = dispatchEntry->xOffset * scaleFactor;
2112 yOffset = dispatchEntry->yOffset * scaleFactor;
2113 if (scaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002114 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 scaledCoords[i] = motionEntry->pointerCoords[i];
2116 scaledCoords[i].scale(scaleFactor);
2117 }
2118 usingCoords = scaledCoords;
2119 }
2120 } else {
2121 xOffset = 0.0f;
2122 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123
2124 // We don't want the dispatch target to know.
2125 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002126 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 scaledCoords[i].clear();
2128 }
2129 usingCoords = scaledCoords;
2130 }
2131 }
2132
2133 // Publish the motion event.
2134 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002135 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002136 dispatchEntry->resolvedAction, motionEntry->actionButton,
2137 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2138 motionEntry->metaState, motionEntry->buttonState,
2139 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 motionEntry->downTime, motionEntry->eventTime,
2141 motionEntry->pointerCount, motionEntry->pointerProperties,
2142 usingCoords);
2143 break;
2144 }
2145
2146 default:
2147 ALOG_ASSERT(false);
2148 return;
2149 }
2150
2151 // Check the result.
2152 if (status) {
2153 if (status == WOULD_BLOCK) {
2154 if (connection->waitQueue.isEmpty()) {
2155 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2156 "This is unexpected because the wait queue is empty, so the pipe "
2157 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002158 "event to it, status=%d", connection->getInputChannelName().c_str(),
2159 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002160 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2161 } else {
2162 // Pipe is full and we are waiting for the app to finish process some events
2163 // before sending more events to it.
2164#if DEBUG_DISPATCH_CYCLE
2165 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2166 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002167 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168#endif
2169 connection->inputPublisherBlocked = true;
2170 }
2171 } else {
2172 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002173 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2175 }
2176 return;
2177 }
2178
2179 // Re-enqueue the event on the wait queue.
2180 connection->outboundQueue.dequeue(dispatchEntry);
2181 traceOutboundQueueLengthLocked(connection);
2182 connection->waitQueue.enqueueAtTail(dispatchEntry);
2183 traceWaitQueueLengthLocked(connection);
2184 }
2185}
2186
2187void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2188 const sp<Connection>& connection, uint32_t seq, bool handled) {
2189#if DEBUG_DISPATCH_CYCLE
2190 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002191 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192#endif
2193
2194 connection->inputPublisherBlocked = false;
2195
2196 if (connection->status == Connection::STATUS_BROKEN
2197 || connection->status == Connection::STATUS_ZOMBIE) {
2198 return;
2199 }
2200
2201 // Notify other system components and prepare to start the next dispatch cycle.
2202 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2203}
2204
2205void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2206 const sp<Connection>& connection, bool notify) {
2207#if DEBUG_DISPATCH_CYCLE
2208 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002209 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210#endif
2211
2212 // Clear the dispatch queues.
2213 drainDispatchQueueLocked(&connection->outboundQueue);
2214 traceOutboundQueueLengthLocked(connection);
2215 drainDispatchQueueLocked(&connection->waitQueue);
2216 traceWaitQueueLengthLocked(connection);
2217
2218 // The connection appears to be unrecoverably broken.
2219 // Ignore already broken or zombie connections.
2220 if (connection->status == Connection::STATUS_NORMAL) {
2221 connection->status = Connection::STATUS_BROKEN;
2222
2223 if (notify) {
2224 // Notify other system components.
2225 onDispatchCycleBrokenLocked(currentTime, connection);
2226 }
2227 }
2228}
2229
2230void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2231 while (!queue->isEmpty()) {
2232 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2233 releaseDispatchEntryLocked(dispatchEntry);
2234 }
2235}
2236
2237void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2238 if (dispatchEntry->hasForegroundTarget()) {
2239 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2240 }
2241 delete dispatchEntry;
2242}
2243
2244int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2245 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2246
2247 { // acquire lock
2248 AutoMutex _l(d->mLock);
2249
2250 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2251 if (connectionIndex < 0) {
2252 ALOGE("Received spurious receive callback for unknown input channel. "
2253 "fd=%d, events=0x%x", fd, events);
2254 return 0; // remove the callback
2255 }
2256
2257 bool notify;
2258 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2259 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2260 if (!(events & ALOOPER_EVENT_INPUT)) {
2261 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002262 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 return 1;
2264 }
2265
2266 nsecs_t currentTime = now();
2267 bool gotOne = false;
2268 status_t status;
2269 for (;;) {
2270 uint32_t seq;
2271 bool handled;
2272 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2273 if (status) {
2274 break;
2275 }
2276 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2277 gotOne = true;
2278 }
2279 if (gotOne) {
2280 d->runCommandsLockedInterruptible();
2281 if (status == WOULD_BLOCK) {
2282 return 1;
2283 }
2284 }
2285
2286 notify = status != DEAD_OBJECT || !connection->monitor;
2287 if (notify) {
2288 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002289 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 }
2291 } else {
2292 // Monitor channels are never explicitly unregistered.
2293 // We do it automatically when the remote endpoint is closed so don't warn
2294 // about them.
2295 notify = !connection->monitor;
2296 if (notify) {
2297 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002298 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299 }
2300 }
2301
2302 // Unregister the channel.
2303 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2304 return 0; // remove the callback
2305 } // release lock
2306}
2307
2308void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2309 const CancelationOptions& options) {
2310 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2311 synthesizeCancelationEventsForConnectionLocked(
2312 mConnectionsByFd.valueAt(i), options);
2313 }
2314}
2315
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002316void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2317 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002318 for (auto& it : mMonitoringChannelsByDisplay) {
2319 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
2320 const size_t numChannels = monitoringChannels.size();
2321 for (size_t i = 0; i < numChannels; i++) {
2322 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2323 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002324 }
2325}
2326
Michael Wrightd02c5b62014-02-10 15:10:22 -08002327void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2328 const sp<InputChannel>& channel, const CancelationOptions& options) {
2329 ssize_t index = getConnectionIndexLocked(channel);
2330 if (index >= 0) {
2331 synthesizeCancelationEventsForConnectionLocked(
2332 mConnectionsByFd.valueAt(index), options);
2333 }
2334}
2335
2336void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2337 const sp<Connection>& connection, const CancelationOptions& options) {
2338 if (connection->status == Connection::STATUS_BROKEN) {
2339 return;
2340 }
2341
2342 nsecs_t currentTime = now();
2343
2344 Vector<EventEntry*> cancelationEvents;
2345 connection->inputState.synthesizeCancelationEvents(currentTime,
2346 cancelationEvents, options);
2347
2348 if (!cancelationEvents.isEmpty()) {
2349#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002350 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002352 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 options.reason, options.mode);
2354#endif
2355 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2356 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2357 switch (cancelationEventEntry->type) {
2358 case EventEntry::TYPE_KEY:
2359 logOutboundKeyDetailsLocked("cancel - ",
2360 static_cast<KeyEntry*>(cancelationEventEntry));
2361 break;
2362 case EventEntry::TYPE_MOTION:
2363 logOutboundMotionDetailsLocked("cancel - ",
2364 static_cast<MotionEntry*>(cancelationEventEntry));
2365 break;
2366 }
2367
2368 InputTarget target;
2369 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07002370 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2372 target.xOffset = -windowInfo->frameLeft;
2373 target.yOffset = -windowInfo->frameTop;
2374 target.scaleFactor = windowInfo->scaleFactor;
2375 } else {
2376 target.xOffset = 0;
2377 target.yOffset = 0;
2378 target.scaleFactor = 1.0f;
2379 }
2380 target.inputChannel = connection->inputChannel;
2381 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2382
2383 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2384 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2385
2386 cancelationEventEntry->release();
2387 }
2388
2389 startDispatchCycleLocked(currentTime, connection);
2390 }
2391}
2392
2393InputDispatcher::MotionEntry*
2394InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2395 ALOG_ASSERT(pointerIds.value != 0);
2396
2397 uint32_t splitPointerIndexMap[MAX_POINTERS];
2398 PointerProperties splitPointerProperties[MAX_POINTERS];
2399 PointerCoords splitPointerCoords[MAX_POINTERS];
2400
2401 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2402 uint32_t splitPointerCount = 0;
2403
2404 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2405 originalPointerIndex++) {
2406 const PointerProperties& pointerProperties =
2407 originalMotionEntry->pointerProperties[originalPointerIndex];
2408 uint32_t pointerId = uint32_t(pointerProperties.id);
2409 if (pointerIds.hasBit(pointerId)) {
2410 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2411 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2412 splitPointerCoords[splitPointerCount].copyFrom(
2413 originalMotionEntry->pointerCoords[originalPointerIndex]);
2414 splitPointerCount += 1;
2415 }
2416 }
2417
2418 if (splitPointerCount != pointerIds.count()) {
2419 // This is bad. We are missing some of the pointers that we expected to deliver.
2420 // Most likely this indicates that we received an ACTION_MOVE events that has
2421 // different pointer ids than we expected based on the previous ACTION_DOWN
2422 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2423 // in this way.
2424 ALOGW("Dropping split motion event because the pointer count is %d but "
2425 "we expected there to be %d pointers. This probably means we received "
2426 "a broken sequence of pointer ids from the input device.",
2427 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002428 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 }
2430
2431 int32_t action = originalMotionEntry->action;
2432 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2433 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2434 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2435 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2436 const PointerProperties& pointerProperties =
2437 originalMotionEntry->pointerProperties[originalPointerIndex];
2438 uint32_t pointerId = uint32_t(pointerProperties.id);
2439 if (pointerIds.hasBit(pointerId)) {
2440 if (pointerIds.count() == 1) {
2441 // The first/last pointer went down/up.
2442 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2443 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2444 } else {
2445 // A secondary pointer went down/up.
2446 uint32_t splitPointerIndex = 0;
2447 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2448 splitPointerIndex += 1;
2449 }
2450 action = maskedAction | (splitPointerIndex
2451 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2452 }
2453 } else {
2454 // An unrelated pointer changed.
2455 action = AMOTION_EVENT_ACTION_MOVE;
2456 }
2457 }
2458
2459 MotionEntry* splitMotionEntry = new MotionEntry(
2460 originalMotionEntry->eventTime,
2461 originalMotionEntry->deviceId,
2462 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002463 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 originalMotionEntry->policyFlags,
2465 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002466 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 originalMotionEntry->flags,
2468 originalMotionEntry->metaState,
2469 originalMotionEntry->buttonState,
2470 originalMotionEntry->edgeFlags,
2471 originalMotionEntry->xPrecision,
2472 originalMotionEntry->yPrecision,
2473 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002474 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475
2476 if (originalMotionEntry->injectionState) {
2477 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2478 splitMotionEntry->injectionState->refCount += 1;
2479 }
2480
2481 return splitMotionEntry;
2482}
2483
2484void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2485#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002486 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487#endif
2488
2489 bool needWake;
2490 { // acquire lock
2491 AutoMutex _l(mLock);
2492
2493 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2494 needWake = enqueueInboundEventLocked(newEntry);
2495 } // release lock
2496
2497 if (needWake) {
2498 mLooper->wake();
2499 }
2500}
2501
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002502/**
2503 * If one of the meta shortcuts is detected, process them here:
2504 * Meta + Backspace -> generate BACK
2505 * Meta + Enter -> generate HOME
2506 * This will potentially overwrite keyCode and metaState.
2507 */
2508void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2509 int32_t& keyCode, int32_t& metaState) {
2510 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2511 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2512 if (keyCode == AKEYCODE_DEL) {
2513 newKeyCode = AKEYCODE_BACK;
2514 } else if (keyCode == AKEYCODE_ENTER) {
2515 newKeyCode = AKEYCODE_HOME;
2516 }
2517 if (newKeyCode != AKEYCODE_UNKNOWN) {
2518 AutoMutex _l(mLock);
2519 struct KeyReplacement replacement = {keyCode, deviceId};
2520 mReplacedKeys.add(replacement, newKeyCode);
2521 keyCode = newKeyCode;
2522 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2523 }
2524 } else if (action == AKEY_EVENT_ACTION_UP) {
2525 // In order to maintain a consistent stream of up and down events, check to see if the key
2526 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2527 // even if the modifier was released between the down and the up events.
2528 AutoMutex _l(mLock);
2529 struct KeyReplacement replacement = {keyCode, deviceId};
2530 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2531 if (index >= 0) {
2532 keyCode = mReplacedKeys.valueAt(index);
2533 mReplacedKeys.removeItemsAt(index);
2534 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2535 }
2536 }
2537}
2538
Michael Wrightd02c5b62014-02-10 15:10:22 -08002539void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2540#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002541 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002542 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung3b413f22018-10-26 18:05:34 +08002543 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64
2544 ", displayId=%" PRId32,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002545 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung3b413f22018-10-26 18:05:34 +08002547 args->metaState, args->downTime, args->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548#endif
2549 if (!validateKeyEvent(args->action)) {
2550 return;
2551 }
2552
2553 uint32_t policyFlags = args->policyFlags;
2554 int32_t flags = args->flags;
2555 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002556 // InputDispatcher tracks and generates key repeats on behalf of
2557 // whatever notifies it, so repeatCount should always be set to 0
2558 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2560 policyFlags |= POLICY_FLAG_VIRTUAL;
2561 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 if (policyFlags & POLICY_FLAG_FUNCTION) {
2564 metaState |= AMETA_FUNCTION_ON;
2565 }
2566
2567 policyFlags |= POLICY_FLAG_TRUSTED;
2568
Michael Wright78f24442014-08-06 15:55:28 -07002569 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002570 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002571
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002573 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002574 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575 args->downTime, args->eventTime);
2576
Michael Wright2b3c3302018-03-02 17:19:13 +00002577 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002579 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2580 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2581 std::to_string(t.duration().count()).c_str());
2582 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 bool needWake;
2585 { // acquire lock
2586 mLock.lock();
2587
2588 if (shouldSendKeyToInputFilterLocked(args)) {
2589 mLock.unlock();
2590
2591 policyFlags |= POLICY_FLAG_FILTERED;
2592 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2593 return; // event was consumed by the filter
2594 }
2595
2596 mLock.lock();
2597 }
2598
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 KeyEntry* newEntry = new KeyEntry(args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002600 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002601 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 metaState, repeatCount, args->downTime);
2603
2604 needWake = enqueueInboundEventLocked(newEntry);
2605 mLock.unlock();
2606 } // release lock
2607
2608 if (needWake) {
2609 mLooper->wake();
2610 }
2611}
2612
2613bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2614 return mInputFilterEnabled;
2615}
2616
2617void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2618#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002619 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2620 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002621 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung3b413f22018-10-26 18:05:34 +08002622 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", displayId=%" PRId32
2623 , args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002624 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung3b413f22018-10-26 18:05:34 +08002625 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime, args->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626 for (uint32_t i = 0; i < args->pointerCount; i++) {
2627 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2628 "x=%f, y=%f, pressure=%f, size=%f, "
2629 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2630 "orientation=%f",
2631 i, args->pointerProperties[i].id,
2632 args->pointerProperties[i].toolType,
2633 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2634 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2635 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2636 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2637 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2638 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2639 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2640 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2641 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2642 }
2643#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002644 if (!validateMotionEvent(args->action, args->actionButton,
2645 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 return;
2647 }
2648
2649 uint32_t policyFlags = args->policyFlags;
2650 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002651
2652 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002654 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2655 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2656 std::to_string(t.duration().count()).c_str());
2657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658
2659 bool needWake;
2660 { // acquire lock
2661 mLock.lock();
2662
2663 if (shouldSendMotionToInputFilterLocked(args)) {
2664 mLock.unlock();
2665
2666 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002667 event.initialize(args->deviceId, args->source, args->displayId,
2668 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002669 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2670 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 args->downTime, args->eventTime,
2672 args->pointerCount, args->pointerProperties, args->pointerCoords);
2673
2674 policyFlags |= POLICY_FLAG_FILTERED;
2675 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2676 return; // event was consumed by the filter
2677 }
2678
2679 mLock.lock();
2680 }
2681
2682 // Just enqueue a new motion event.
2683 MotionEntry* newEntry = new MotionEntry(args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002684 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002685 args->action, args->actionButton, args->flags,
2686 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002688 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689
2690 needWake = enqueueInboundEventLocked(newEntry);
2691 mLock.unlock();
2692 } // release lock
2693
2694 if (needWake) {
2695 mLooper->wake();
2696 }
2697}
2698
2699bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2700 // TODO: support sending secondary display events to input filter
2701 return mInputFilterEnabled && isMainDisplay(args->displayId);
2702}
2703
2704void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2705#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002706 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2707 "switchMask=0x%08x",
2708 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709#endif
2710
2711 uint32_t policyFlags = args->policyFlags;
2712 policyFlags |= POLICY_FLAG_TRUSTED;
2713 mPolicy->notifySwitch(args->eventTime,
2714 args->switchValues, args->switchMask, policyFlags);
2715}
2716
2717void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2718#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002719 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 args->eventTime, args->deviceId);
2721#endif
2722
2723 bool needWake;
2724 { // acquire lock
2725 AutoMutex _l(mLock);
2726
2727 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2728 needWake = enqueueInboundEventLocked(newEntry);
2729 } // release lock
2730
2731 if (needWake) {
2732 mLooper->wake();
2733 }
2734}
2735
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002736int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2738 uint32_t policyFlags) {
2739#if DEBUG_INBOUND_EVENT_DETAILS
2740 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002741 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2742 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743#endif
2744
2745 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2746
2747 policyFlags |= POLICY_FLAG_INJECTED;
2748 if (hasInjectionPermission(injectorPid, injectorUid)) {
2749 policyFlags |= POLICY_FLAG_TRUSTED;
2750 }
2751
2752 EventEntry* firstInjectedEntry;
2753 EventEntry* lastInjectedEntry;
2754 switch (event->getType()) {
2755 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002756 KeyEvent keyEvent;
2757 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2758 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759 if (! validateKeyEvent(action)) {
2760 return INPUT_EVENT_INJECTION_FAILED;
2761 }
2762
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002763 int32_t flags = keyEvent.getFlags();
2764 int32_t keyCode = keyEvent.getKeyCode();
2765 int32_t metaState = keyEvent.getMetaState();
2766 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2767 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002768 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002769 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002770 keyEvent.getDownTime(), keyEvent.getEventTime());
2771
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2773 policyFlags |= POLICY_FLAG_VIRTUAL;
2774 }
2775
2776 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002777 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002778 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002779 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2780 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2781 std::to_string(t.duration().count()).c_str());
2782 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783 }
2784
Michael Wrightd02c5b62014-02-10 15:10:22 -08002785 mLock.lock();
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002786 firstInjectedEntry = new KeyEntry(keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002787 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002789 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2790 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002791 lastInjectedEntry = firstInjectedEntry;
2792 break;
2793 }
2794
2795 case AINPUT_EVENT_TYPE_MOTION: {
2796 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002797 int32_t action = motionEvent->getAction();
2798 size_t pointerCount = motionEvent->getPointerCount();
2799 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002800 int32_t actionButton = motionEvent->getActionButton();
2801 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802 return INPUT_EVENT_INJECTION_FAILED;
2803 }
2804
2805 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2806 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002807 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002809 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2810 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2811 std::to_string(t.duration().count()).c_str());
2812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 }
2814
2815 mLock.lock();
2816 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2817 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2818 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002819 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2820 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002821 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 motionEvent->getMetaState(), motionEvent->getButtonState(),
2823 motionEvent->getEdgeFlags(),
2824 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002825 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002826 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2827 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 lastInjectedEntry = firstInjectedEntry;
2829 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2830 sampleEventTimes += 1;
2831 samplePointerCoords += pointerCount;
2832 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002833 motionEvent->getDeviceId(), motionEvent->getSource(),
2834 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002835 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 motionEvent->getMetaState(), motionEvent->getButtonState(),
2837 motionEvent->getEdgeFlags(),
2838 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002839 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002840 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2841 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842 lastInjectedEntry->next = nextInjectedEntry;
2843 lastInjectedEntry = nextInjectedEntry;
2844 }
2845 break;
2846 }
2847
2848 default:
2849 ALOGW("Cannot inject event of type %d", event->getType());
2850 return INPUT_EVENT_INJECTION_FAILED;
2851 }
2852
2853 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2854 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2855 injectionState->injectionIsAsync = true;
2856 }
2857
2858 injectionState->refCount += 1;
2859 lastInjectedEntry->injectionState = injectionState;
2860
2861 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002862 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 EventEntry* nextEntry = entry->next;
2864 needWake |= enqueueInboundEventLocked(entry);
2865 entry = nextEntry;
2866 }
2867
2868 mLock.unlock();
2869
2870 if (needWake) {
2871 mLooper->wake();
2872 }
2873
2874 int32_t injectionResult;
2875 { // acquire lock
2876 AutoMutex _l(mLock);
2877
2878 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2879 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2880 } else {
2881 for (;;) {
2882 injectionResult = injectionState->injectionResult;
2883 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2884 break;
2885 }
2886
2887 nsecs_t remainingTimeout = endTime - now();
2888 if (remainingTimeout <= 0) {
2889#if DEBUG_INJECTION
2890 ALOGD("injectInputEvent - Timed out waiting for injection result "
2891 "to become available.");
2892#endif
2893 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2894 break;
2895 }
2896
2897 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2898 }
2899
2900 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2901 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2902 while (injectionState->pendingForegroundDispatches != 0) {
2903#if DEBUG_INJECTION
2904 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2905 injectionState->pendingForegroundDispatches);
2906#endif
2907 nsecs_t remainingTimeout = endTime - now();
2908 if (remainingTimeout <= 0) {
2909#if DEBUG_INJECTION
2910 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2911 "dispatches to finish.");
2912#endif
2913 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2914 break;
2915 }
2916
2917 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2918 }
2919 }
2920 }
2921
2922 injectionState->release();
2923 } // release lock
2924
2925#if DEBUG_INJECTION
2926 ALOGD("injectInputEvent - Finished with result %d. "
2927 "injectorPid=%d, injectorUid=%d",
2928 injectionResult, injectorPid, injectorUid);
2929#endif
2930
2931 return injectionResult;
2932}
2933
2934bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2935 return injectorUid == 0
2936 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2937}
2938
2939void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2940 InjectionState* injectionState = entry->injectionState;
2941 if (injectionState) {
2942#if DEBUG_INJECTION
2943 ALOGD("Setting input event injection result to %d. "
2944 "injectorPid=%d, injectorUid=%d",
2945 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2946#endif
2947
2948 if (injectionState->injectionIsAsync
2949 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2950 // Log the outcome since the injector did not wait for the injection result.
2951 switch (injectionResult) {
2952 case INPUT_EVENT_INJECTION_SUCCEEDED:
2953 ALOGV("Asynchronous input event injection succeeded.");
2954 break;
2955 case INPUT_EVENT_INJECTION_FAILED:
2956 ALOGW("Asynchronous input event injection failed.");
2957 break;
2958 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2959 ALOGW("Asynchronous input event injection permission denied.");
2960 break;
2961 case INPUT_EVENT_INJECTION_TIMED_OUT:
2962 ALOGW("Asynchronous input event injection timed out.");
2963 break;
2964 }
2965 }
2966
2967 injectionState->injectionResult = injectionResult;
2968 mInjectionResultAvailableCondition.broadcast();
2969 }
2970}
2971
2972void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2973 InjectionState* injectionState = entry->injectionState;
2974 if (injectionState) {
2975 injectionState->pendingForegroundDispatches += 1;
2976 }
2977}
2978
2979void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2980 InjectionState* injectionState = entry->injectionState;
2981 if (injectionState) {
2982 injectionState->pendingForegroundDispatches -= 1;
2983
2984 if (injectionState->pendingForegroundDispatches == 0) {
2985 mInjectionSyncFinishedCondition.broadcast();
2986 }
2987 }
2988}
2989
Arthur Hungb92218b2018-08-14 12:00:21 +08002990Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
2991 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
2992 mWindowHandlesByDisplay.find(displayId);
2993 if(it != mWindowHandlesByDisplay.end()) {
2994 return it->second;
2995 }
2996
2997 // Return an empty one if nothing found.
2998 return Vector<sp<InputWindowHandle>>();
2999}
3000
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3002 const sp<InputChannel>& inputChannel) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003003 for (auto& it : mWindowHandlesByDisplay) {
3004 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3005 size_t numWindows = windowHandles.size();
3006 for (size_t i = 0; i < numWindows; i++) {
3007 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3008 if (windowHandle->getInputChannel() == inputChannel) {
3009 return windowHandle;
3010 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 }
3012 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003013 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003014}
3015
3016bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003017 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003018 for (auto& it : mWindowHandlesByDisplay) {
3019 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3020 size_t numWindows = windowHandles.size();
3021 for (size_t i = 0; i < numWindows; i++) {
Robert Carr4e670e52018-08-15 13:26:12 -07003022 if (windowHandles.itemAt(i)->getInputChannel()->getToken()
3023 == windowHandle->getInputChannel()->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003024 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003025 ALOGE("Found window %s in display %" PRId32
3026 ", but it should belong to display %" PRId32,
3027 windowHandle->getName().c_str(), it.first,
3028 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003029 }
3030 return true;
3031 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003032 }
3033 }
3034 return false;
3035}
3036
Arthur Hungb92218b2018-08-14 12:00:21 +08003037/**
3038 * Called from InputManagerService, update window handle list by displayId that can receive input.
3039 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3040 * If set an empty list, remove all handles from the specific display.
3041 * For focused handle, check if need to change and send a cancel event to previous one.
3042 * For removed handle, check if need to send a cancel event if already in touch.
3043 */
3044void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3045 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003047 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048#endif
3049 { // acquire lock
3050 AutoMutex _l(mLock);
3051
Arthur Hungb92218b2018-08-14 12:00:21 +08003052 // Copy old handles for release if they are no longer present.
3053 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054
Tiger Huang721e26f2018-07-24 22:26:19 +08003055 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003057
3058 if (inputWindowHandles.isEmpty()) {
3059 // Remove all handles on a display if there are no windows left.
3060 mWindowHandlesByDisplay.erase(displayId);
3061 } else {
3062 size_t numWindows = inputWindowHandles.size();
3063 for (size_t i = 0; i < numWindows; i++) {
3064 const sp<InputWindowHandle>& windowHandle = inputWindowHandles.itemAt(i);
3065 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == nullptr) {
3066 continue;
3067 }
3068
3069 if (windowHandle->getInfo()->displayId != displayId) {
3070 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3071 windowHandle->getName().c_str(), displayId,
3072 windowHandle->getInfo()->displayId);
3073 continue;
3074 }
3075
3076 if (windowHandle->getInfo()->hasFocus) {
3077 newFocusedWindowHandle = windowHandle;
3078 }
3079 if (windowHandle == mLastHoverWindowHandle) {
3080 foundHoveredWindow = true;
3081 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003082 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003083
3084 // Insert or replace
3085 mWindowHandlesByDisplay[displayId] = inputWindowHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086 }
3087
3088 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003089 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090 }
3091
Tiger Huang721e26f2018-07-24 22:26:19 +08003092 sp<InputWindowHandle> oldFocusedWindowHandle =
3093 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3094
3095 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3096 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003098 ALOGD("Focus left window: %s in display %" PRId32,
3099 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003101 sp<InputChannel> focusedInputChannel = oldFocusedWindowHandle->getInputChannel();
Yi Kong9b14ac62018-07-17 13:48:38 -07003102 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3104 "focus left window");
3105 synthesizeCancelationEventsForInputChannelLocked(
3106 focusedInputChannel, options);
3107 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003108 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003110 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003112 ALOGD("Focus entered window: %s in display %" PRId32,
3113 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003115 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117 }
3118
Arthur Hungb92218b2018-08-14 12:00:21 +08003119 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3120 if (stateIndex >= 0) {
3121 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003122 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003123 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003124 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003126 ALOGD("Touched window was removed: %s in display %" PRId32,
3127 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003128#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003129 sp<InputChannel> touchedInputChannel =
3130 touchedWindow.windowHandle->getInputChannel();
Yi Kong9b14ac62018-07-17 13:48:38 -07003131 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003132 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3133 "touched window was removed");
3134 synthesizeCancelationEventsForInputChannelLocked(
3135 touchedInputChannel, options);
3136 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003137 state.windows.removeAt(i);
3138 } else {
3139 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141 }
3142 }
3143
3144 // Release information for windows that are no longer present.
3145 // This ensures that unused input channels are released promptly.
3146 // Otherwise, they might stick around until the window handle is destroyed
3147 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003148 size_t numWindows = oldWindowHandles.size();
3149 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003151 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003153 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003155 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156 }
3157 }
3158 } // release lock
3159
3160 // Wake up poll loop since it may need to make new input dispatching choices.
3161 mLooper->wake();
3162}
3163
3164void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003165 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003167 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168#endif
3169 { // acquire lock
3170 AutoMutex _l(mLock);
3171
Tiger Huang721e26f2018-07-24 22:26:19 +08003172 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3173 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003174 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003175 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3176 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003178 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003180 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003182 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003184 oldFocusedApplicationHandle->releaseInfo();
3185 oldFocusedApplicationHandle.clear();
3186 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 }
3188
3189#if DEBUG_FOCUS
3190 //logDispatchStateLocked();
3191#endif
3192 } // release lock
3193
3194 // Wake up poll loop since it may need to make new input dispatching choices.
3195 mLooper->wake();
3196}
3197
Tiger Huang721e26f2018-07-24 22:26:19 +08003198/**
3199 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3200 * the display not specified.
3201 *
3202 * We track any unreleased events for each window. If a window loses the ability to receive the
3203 * released event, we will send a cancel event to it. So when the focused display is changed, we
3204 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3205 * display. The display-specified events won't be affected.
3206 */
3207void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3208#if DEBUG_FOCUS
3209 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3210#endif
3211 { // acquire lock
3212 AutoMutex _l(mLock);
3213
3214 if (mFocusedDisplayId != displayId) {
3215 sp<InputWindowHandle> oldFocusedWindowHandle =
3216 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3217 if (oldFocusedWindowHandle != nullptr) {
3218 sp<InputChannel> inputChannel = oldFocusedWindowHandle->getInputChannel();
3219 if (inputChannel != nullptr) {
3220 CancelationOptions options(
3221 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3222 "The display which contains this window no longer has focus.");
3223 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3224 }
3225 }
3226 mFocusedDisplayId = displayId;
3227
3228 // Sanity check
3229 sp<InputWindowHandle> newFocusedWindowHandle =
3230 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3231 if (newFocusedWindowHandle == nullptr) {
3232 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3233 if (!mFocusedWindowHandlesByDisplay.empty()) {
3234 ALOGE("But another display has a focused window:");
3235 for (auto& it : mFocusedWindowHandlesByDisplay) {
3236 const int32_t displayId = it.first;
3237 const sp<InputWindowHandle>& windowHandle = it.second;
3238 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3239 displayId, windowHandle->getName().c_str());
3240 }
3241 }
3242 }
3243 }
3244
3245#if DEBUG_FOCUS
3246 logDispatchStateLocked();
3247#endif
3248 } // release lock
3249
3250 // Wake up poll loop since it may need to make new input dispatching choices.
3251 mLooper->wake();
3252}
3253
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3255#if DEBUG_FOCUS
3256 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3257#endif
3258
3259 bool changed;
3260 { // acquire lock
3261 AutoMutex _l(mLock);
3262
3263 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3264 if (mDispatchFrozen && !frozen) {
3265 resetANRTimeoutsLocked();
3266 }
3267
3268 if (mDispatchEnabled && !enabled) {
3269 resetAndDropEverythingLocked("dispatcher is being disabled");
3270 }
3271
3272 mDispatchEnabled = enabled;
3273 mDispatchFrozen = frozen;
3274 changed = true;
3275 } else {
3276 changed = false;
3277 }
3278
3279#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003280 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281#endif
3282 } // release lock
3283
3284 if (changed) {
3285 // Wake up poll loop since it may need to make new input dispatching choices.
3286 mLooper->wake();
3287 }
3288}
3289
3290void InputDispatcher::setInputFilterEnabled(bool enabled) {
3291#if DEBUG_FOCUS
3292 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3293#endif
3294
3295 { // acquire lock
3296 AutoMutex _l(mLock);
3297
3298 if (mInputFilterEnabled == enabled) {
3299 return;
3300 }
3301
3302 mInputFilterEnabled = enabled;
3303 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3304 } // release lock
3305
3306 // Wake up poll loop since there might be work to do to drop everything.
3307 mLooper->wake();
3308}
3309
3310bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3311 const sp<InputChannel>& toChannel) {
3312#if DEBUG_FOCUS
3313 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003314 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315#endif
3316 { // acquire lock
3317 AutoMutex _l(mLock);
3318
3319 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3320 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07003321 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322#if DEBUG_FOCUS
3323 ALOGD("Cannot transfer focus because from or to window not found.");
3324#endif
3325 return false;
3326 }
3327 if (fromWindowHandle == toWindowHandle) {
3328#if DEBUG_FOCUS
3329 ALOGD("Trivial transfer to same window.");
3330#endif
3331 return true;
3332 }
3333 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3334#if DEBUG_FOCUS
3335 ALOGD("Cannot transfer focus because windows are on different displays.");
3336#endif
3337 return false;
3338 }
3339
3340 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003341 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3342 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3343 for (size_t i = 0; i < state.windows.size(); i++) {
3344 const TouchedWindow& touchedWindow = state.windows[i];
3345 if (touchedWindow.windowHandle == fromWindowHandle) {
3346 int32_t oldTargetFlags = touchedWindow.targetFlags;
3347 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348
Jeff Brownf086ddb2014-02-11 14:28:48 -08003349 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350
Jeff Brownf086ddb2014-02-11 14:28:48 -08003351 int32_t newTargetFlags = oldTargetFlags
3352 & (InputTarget::FLAG_FOREGROUND
3353 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3354 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355
Jeff Brownf086ddb2014-02-11 14:28:48 -08003356 found = true;
3357 goto Found;
3358 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359 }
3360 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003361Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362
3363 if (! found) {
3364#if DEBUG_FOCUS
3365 ALOGD("Focus transfer failed because from window did not have focus.");
3366#endif
3367 return false;
3368 }
3369
3370 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3371 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3372 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3373 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3374 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3375
3376 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3377 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3378 "transferring touch focus from this window to another window");
3379 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3380 }
3381
3382#if DEBUG_FOCUS
3383 logDispatchStateLocked();
3384#endif
3385 } // release lock
3386
3387 // Wake up poll loop since it may need to make new input dispatching choices.
3388 mLooper->wake();
3389 return true;
3390}
3391
3392void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3393#if DEBUG_FOCUS
3394 ALOGD("Resetting and dropping all events (%s).", reason);
3395#endif
3396
3397 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3398 synthesizeCancelationEventsForAllConnectionsLocked(options);
3399
3400 resetKeyRepeatLocked();
3401 releasePendingEventLocked();
3402 drainInboundQueueLocked();
3403 resetANRTimeoutsLocked();
3404
Jeff Brownf086ddb2014-02-11 14:28:48 -08003405 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003407 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408}
3409
3410void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003411 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 dumpDispatchStateLocked(dump);
3413
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003414 std::istringstream stream(dump);
3415 std::string line;
3416
3417 while (std::getline(stream, line, '\n')) {
3418 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 }
3420}
3421
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003422void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3423 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3424 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003425 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426
Tiger Huang721e26f2018-07-24 22:26:19 +08003427 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3428 dump += StringPrintf(INDENT "FocusedApplications:\n");
3429 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3430 const int32_t displayId = it.first;
3431 const sp<InputApplicationHandle>& applicationHandle = it.second;
3432 dump += StringPrintf(
3433 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3434 displayId,
3435 applicationHandle->getName().c_str(),
3436 applicationHandle->getDispatchingTimeout(
3437 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3438 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003440 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003441 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003442
3443 if (!mFocusedWindowHandlesByDisplay.empty()) {
3444 dump += StringPrintf(INDENT "FocusedWindows:\n");
3445 for (auto& it : mFocusedWindowHandlesByDisplay) {
3446 const int32_t displayId = it.first;
3447 const sp<InputWindowHandle>& windowHandle = it.second;
3448 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3449 displayId, windowHandle->getName().c_str());
3450 }
3451 } else {
3452 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3453 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454
Jeff Brownf086ddb2014-02-11 14:28:48 -08003455 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003456 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003457 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3458 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003459 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003460 state.displayId, toString(state.down), toString(state.split),
3461 state.deviceId, state.source);
3462 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003463 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003464 for (size_t i = 0; i < state.windows.size(); i++) {
3465 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003466 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3467 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003468 touchedWindow.pointerIds.value,
3469 touchedWindow.targetFlags);
3470 }
3471 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003472 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 }
3475 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003476 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 }
3478
Arthur Hungb92218b2018-08-14 12:00:21 +08003479 if (!mWindowHandlesByDisplay.empty()) {
3480 for (auto& it : mWindowHandlesByDisplay) {
3481 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003482 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003483 if (!windowHandles.isEmpty()) {
3484 dump += INDENT2 "Windows:\n";
3485 for (size_t i = 0; i < windowHandles.size(); i++) {
3486 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3487 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488
Arthur Hungb92218b2018-08-14 12:00:21 +08003489 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3490 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3491 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3492 "frame=[%d,%d][%d,%d], scale=%f, "
3493 "touchableRegion=",
3494 i, windowInfo->name.c_str(), windowInfo->displayId,
3495 toString(windowInfo->paused),
3496 toString(windowInfo->hasFocus),
3497 toString(windowInfo->hasWallpaper),
3498 toString(windowInfo->visible),
3499 toString(windowInfo->canReceiveKeys),
3500 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3501 windowInfo->layer,
3502 windowInfo->frameLeft, windowInfo->frameTop,
3503 windowInfo->frameRight, windowInfo->frameBottom,
3504 windowInfo->scaleFactor);
3505 dumpRegion(dump, windowInfo->touchableRegion);
3506 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3507 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3508 windowInfo->ownerPid, windowInfo->ownerUid,
3509 windowInfo->dispatchingTimeout / 1000000.0);
3510 }
3511 } else {
3512 dump += INDENT2 "Windows: <none>\n";
3513 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514 }
3515 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003516 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517 }
3518
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003519 if (!mMonitoringChannelsByDisplay.empty()) {
3520 for (auto& it : mMonitoringChannelsByDisplay) {
3521 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003522 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003523 const size_t numChannels = monitoringChannels.size();
3524 for (size_t i = 0; i < numChannels; i++) {
3525 const sp<InputChannel>& channel = monitoringChannels[i];
3526 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3527 }
3528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003530 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 }
3532
3533 nsecs_t currentTime = now();
3534
3535 // Dump recently dispatched or dropped events from oldest to newest.
3536 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003537 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003539 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003541 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542 (currentTime - entry->eventTime) * 0.000001f);
3543 }
3544 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003545 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546 }
3547
3548 // Dump event currently being dispatched.
3549 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003550 dump += INDENT "PendingEvent:\n";
3551 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003553 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3555 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003556 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 }
3558
3559 // Dump inbound events from oldest to newest.
3560 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003561 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003563 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003565 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566 (currentTime - entry->eventTime) * 0.000001f);
3567 }
3568 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003569 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570 }
3571
Michael Wright78f24442014-08-06 15:55:28 -07003572 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003573 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003574 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3575 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3576 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003577 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003578 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3579 }
3580 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003581 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003582 }
3583
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003585 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3587 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003588 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003590 i, connection->getInputChannelName().c_str(),
3591 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003592 connection->getStatusLabel(), toString(connection->monitor),
3593 toString(connection->inputPublisherBlocked));
3594
3595 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003596 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 connection->outboundQueue.count());
3598 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3599 entry = entry->next) {
3600 dump.append(INDENT4);
3601 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003602 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 entry->targetFlags, entry->resolvedAction,
3604 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3605 }
3606 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003607 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 }
3609
3610 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003611 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 connection->waitQueue.count());
3613 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3614 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003615 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003617 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 "age=%0.1fms, wait=%0.1fms\n",
3619 entry->targetFlags, entry->resolvedAction,
3620 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3621 (currentTime - entry->deliveryTime) * 0.000001f);
3622 }
3623 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003624 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625 }
3626 }
3627 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003628 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 }
3630
3631 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003632 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 (mAppSwitchDueTime - now()) / 1000000.0);
3634 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003635 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 }
3637
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003638 dump += INDENT "Configuration:\n";
3639 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003641 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 mConfig.keyRepeatTimeout * 0.000001f);
3643}
3644
Robert Carr803535b2018-08-02 16:38:15 -07003645status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003647 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3648 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649#endif
3650
3651 { // acquire lock
3652 AutoMutex _l(mLock);
3653
Robert Carr4e670e52018-08-15 13:26:12 -07003654 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3655 // treat inputChannel as monitor channel for displayId.
3656 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3657 if (monitor) {
3658 inputChannel->setToken(new BBinder());
3659 }
3660
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 if (getConnectionIndexLocked(inputChannel) >= 0) {
3662 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003663 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 return BAD_VALUE;
3665 }
3666
Robert Carr803535b2018-08-02 16:38:15 -07003667 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668
3669 int fd = inputChannel->getFd();
3670 mConnectionsByFd.add(fd, connection);
3671
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003672 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003674 Vector<sp<InputChannel>>& monitoringChannels =
3675 mMonitoringChannelsByDisplay[displayId];
3676 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 }
3678
3679 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3680 } // release lock
3681
3682 // Wake the looper because some connections have changed.
3683 mLooper->wake();
3684 return OK;
3685}
3686
3687status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3688#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003689 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690#endif
3691
3692 { // acquire lock
3693 AutoMutex _l(mLock);
3694
3695 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3696 if (status) {
3697 return status;
3698 }
3699 } // release lock
3700
3701 // Wake the poll loop because removing the connection may have changed the current
3702 // synchronization state.
3703 mLooper->wake();
3704 return OK;
3705}
3706
3707status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3708 bool notify) {
3709 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3710 if (connectionIndex < 0) {
3711 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003712 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 return BAD_VALUE;
3714 }
3715
3716 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3717 mConnectionsByFd.removeItemsAt(connectionIndex);
3718
3719 if (connection->monitor) {
3720 removeMonitorChannelLocked(inputChannel);
3721 }
3722
3723 mLooper->removeFd(inputChannel->getFd());
3724
3725 nsecs_t currentTime = now();
3726 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3727
3728 connection->status = Connection::STATUS_ZOMBIE;
3729 return OK;
3730}
3731
3732void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003733 for (auto it = mMonitoringChannelsByDisplay.begin();
3734 it != mMonitoringChannelsByDisplay.end(); ) {
3735 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3736 const size_t numChannels = monitoringChannels.size();
3737 for (size_t i = 0; i < numChannels; i++) {
3738 if (monitoringChannels[i] == inputChannel) {
3739 monitoringChannels.removeAt(i);
3740 break;
3741 }
3742 }
3743 if (monitoringChannels.empty()) {
3744 it = mMonitoringChannelsByDisplay.erase(it);
3745 } else {
3746 ++it;
3747 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 }
3749}
3750
3751ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003752 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003753 return -1;
3754 }
3755
Robert Carr4e670e52018-08-15 13:26:12 -07003756 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3757 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3758 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3759 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 }
3761 }
Robert Carr4e670e52018-08-15 13:26:12 -07003762
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763 return -1;
3764}
3765
3766void InputDispatcher::onDispatchCycleFinishedLocked(
3767 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3768 CommandEntry* commandEntry = postCommandLocked(
3769 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3770 commandEntry->connection = connection;
3771 commandEntry->eventTime = currentTime;
3772 commandEntry->seq = seq;
3773 commandEntry->handled = handled;
3774}
3775
3776void InputDispatcher::onDispatchCycleBrokenLocked(
3777 nsecs_t currentTime, const sp<Connection>& connection) {
3778 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003779 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780
3781 CommandEntry* commandEntry = postCommandLocked(
3782 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3783 commandEntry->connection = connection;
3784}
3785
3786void InputDispatcher::onANRLocked(
3787 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3788 const sp<InputWindowHandle>& windowHandle,
3789 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3790 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3791 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3792 ALOGI("Application is not responding: %s. "
3793 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003794 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 dispatchLatency, waitDuration, reason);
3796
3797 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003798 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 struct tm tm;
3800 localtime_r(&t, &tm);
3801 char timestr[64];
3802 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3803 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003804 mLastANRState += INDENT "ANR:\n";
3805 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3806 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3807 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3808 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3809 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3810 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003811 dumpDispatchStateLocked(mLastANRState);
3812
3813 CommandEntry* commandEntry = postCommandLocked(
3814 & InputDispatcher::doNotifyANRLockedInterruptible);
3815 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr803535b2018-08-02 16:38:15 -07003816 commandEntry->inputChannel = windowHandle != nullptr ? windowHandle->getInputChannel() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003817 commandEntry->reason = reason;
3818}
3819
3820void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3821 CommandEntry* commandEntry) {
3822 mLock.unlock();
3823
3824 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3825
3826 mLock.lock();
3827}
3828
3829void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3830 CommandEntry* commandEntry) {
3831 sp<Connection> connection = commandEntry->connection;
3832
3833 if (connection->status != Connection::STATUS_ZOMBIE) {
3834 mLock.unlock();
3835
Robert Carr803535b2018-08-02 16:38:15 -07003836 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003837
3838 mLock.lock();
3839 }
3840}
3841
3842void InputDispatcher::doNotifyANRLockedInterruptible(
3843 CommandEntry* commandEntry) {
3844 mLock.unlock();
3845
3846 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003847 commandEntry->inputApplicationHandle,
3848 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849 commandEntry->reason);
3850
3851 mLock.lock();
3852
3853 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003854 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855}
3856
3857void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3858 CommandEntry* commandEntry) {
3859 KeyEntry* entry = commandEntry->keyEntry;
3860
3861 KeyEvent event;
3862 initializeKeyEvent(&event, entry);
3863
3864 mLock.unlock();
3865
Michael Wright2b3c3302018-03-02 17:19:13 +00003866 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003867 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3868 commandEntry->inputChannel->getToken() : nullptr;
3869 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003871 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3872 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3873 std::to_string(t.duration().count()).c_str());
3874 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875
3876 mLock.lock();
3877
3878 if (delay < 0) {
3879 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3880 } else if (!delay) {
3881 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3882 } else {
3883 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3884 entry->interceptKeyWakeupTime = now() + delay;
3885 }
3886 entry->release();
3887}
3888
3889void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3890 CommandEntry* commandEntry) {
3891 sp<Connection> connection = commandEntry->connection;
3892 nsecs_t finishTime = commandEntry->eventTime;
3893 uint32_t seq = commandEntry->seq;
3894 bool handled = commandEntry->handled;
3895
3896 // Handle post-event policy actions.
3897 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3898 if (dispatchEntry) {
3899 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3900 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003901 std::string msg =
3902 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003903 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003905 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906 }
3907
3908 bool restartEvent;
3909 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3910 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3911 restartEvent = afterKeyEventLockedInterruptible(connection,
3912 dispatchEntry, keyEntry, handled);
3913 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3914 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3915 restartEvent = afterMotionEventLockedInterruptible(connection,
3916 dispatchEntry, motionEntry, handled);
3917 } else {
3918 restartEvent = false;
3919 }
3920
3921 // Dequeue the event and start the next cycle.
3922 // Note that because the lock might have been released, it is possible that the
3923 // contents of the wait queue to have been drained, so we need to double-check
3924 // a few things.
3925 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3926 connection->waitQueue.dequeue(dispatchEntry);
3927 traceWaitQueueLengthLocked(connection);
3928 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3929 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3930 traceOutboundQueueLengthLocked(connection);
3931 } else {
3932 releaseDispatchEntryLocked(dispatchEntry);
3933 }
3934 }
3935
3936 // Start the next dispatch cycle for this connection.
3937 startDispatchCycleLocked(now(), connection);
3938 }
3939}
3940
3941bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3942 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3943 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3944 // Get the fallback key state.
3945 // Clear it out after dispatching the UP.
3946 int32_t originalKeyCode = keyEntry->keyCode;
3947 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3948 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3949 connection->inputState.removeFallbackKey(originalKeyCode);
3950 }
3951
3952 if (handled || !dispatchEntry->hasForegroundTarget()) {
3953 // If the application handles the original key for which we previously
3954 // generated a fallback or if the window is not a foreground window,
3955 // then cancel the associated fallback key, if any.
3956 if (fallbackKeyCode != -1) {
3957 // Dispatch the unhandled key to the policy with the cancel flag.
3958#if DEBUG_OUTBOUND_EVENT_DETAILS
3959 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3960 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3961 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3962 keyEntry->policyFlags);
3963#endif
3964 KeyEvent event;
3965 initializeKeyEvent(&event, keyEntry);
3966 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3967
3968 mLock.unlock();
3969
Robert Carr803535b2018-08-02 16:38:15 -07003970 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 &event, keyEntry->policyFlags, &event);
3972
3973 mLock.lock();
3974
3975 // Cancel the fallback key.
3976 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3977 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3978 "application handled the original non-fallback key "
3979 "or is no longer a foreground target, "
3980 "canceling previously dispatched fallback key");
3981 options.keyCode = fallbackKeyCode;
3982 synthesizeCancelationEventsForConnectionLocked(connection, options);
3983 }
3984 connection->inputState.removeFallbackKey(originalKeyCode);
3985 }
3986 } else {
3987 // If the application did not handle a non-fallback key, first check
3988 // that we are in a good state to perform unhandled key event processing
3989 // Then ask the policy what to do with it.
3990 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3991 && keyEntry->repeatCount == 0;
3992 if (fallbackKeyCode == -1 && !initialDown) {
3993#if DEBUG_OUTBOUND_EVENT_DETAILS
3994 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3995 "since this is not an initial down. "
3996 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3997 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3998 keyEntry->policyFlags);
3999#endif
4000 return false;
4001 }
4002
4003 // Dispatch the unhandled key to the policy.
4004#if DEBUG_OUTBOUND_EVENT_DETAILS
4005 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4006 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4007 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4008 keyEntry->policyFlags);
4009#endif
4010 KeyEvent event;
4011 initializeKeyEvent(&event, keyEntry);
4012
4013 mLock.unlock();
4014
Robert Carr803535b2018-08-02 16:38:15 -07004015 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004016 &event, keyEntry->policyFlags, &event);
4017
4018 mLock.lock();
4019
4020 if (connection->status != Connection::STATUS_NORMAL) {
4021 connection->inputState.removeFallbackKey(originalKeyCode);
4022 return false;
4023 }
4024
4025 // Latch the fallback keycode for this key on an initial down.
4026 // The fallback keycode cannot change at any other point in the lifecycle.
4027 if (initialDown) {
4028 if (fallback) {
4029 fallbackKeyCode = event.getKeyCode();
4030 } else {
4031 fallbackKeyCode = AKEYCODE_UNKNOWN;
4032 }
4033 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4034 }
4035
4036 ALOG_ASSERT(fallbackKeyCode != -1);
4037
4038 // Cancel the fallback key if the policy decides not to send it anymore.
4039 // We will continue to dispatch the key to the policy but we will no
4040 // longer dispatch a fallback key to the application.
4041 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4042 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4043#if DEBUG_OUTBOUND_EVENT_DETAILS
4044 if (fallback) {
4045 ALOGD("Unhandled key event: Policy requested to send key %d"
4046 "as a fallback for %d, but on the DOWN it had requested "
4047 "to send %d instead. Fallback canceled.",
4048 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4049 } else {
4050 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4051 "but on the DOWN it had requested to send %d. "
4052 "Fallback canceled.",
4053 originalKeyCode, fallbackKeyCode);
4054 }
4055#endif
4056
4057 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4058 "canceling fallback, policy no longer desires it");
4059 options.keyCode = fallbackKeyCode;
4060 synthesizeCancelationEventsForConnectionLocked(connection, options);
4061
4062 fallback = false;
4063 fallbackKeyCode = AKEYCODE_UNKNOWN;
4064 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4065 connection->inputState.setFallbackKey(originalKeyCode,
4066 fallbackKeyCode);
4067 }
4068 }
4069
4070#if DEBUG_OUTBOUND_EVENT_DETAILS
4071 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004072 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4074 connection->inputState.getFallbackKeys();
4075 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004076 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077 fallbackKeys.valueAt(i));
4078 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07004079 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004080 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 }
4082#endif
4083
4084 if (fallback) {
4085 // Restart the dispatch cycle using the fallback key.
4086 keyEntry->eventTime = event.getEventTime();
4087 keyEntry->deviceId = event.getDeviceId();
4088 keyEntry->source = event.getSource();
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004089 keyEntry->displayId = event.getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4091 keyEntry->keyCode = fallbackKeyCode;
4092 keyEntry->scanCode = event.getScanCode();
4093 keyEntry->metaState = event.getMetaState();
4094 keyEntry->repeatCount = event.getRepeatCount();
4095 keyEntry->downTime = event.getDownTime();
4096 keyEntry->syntheticRepeat = false;
4097
4098#if DEBUG_OUTBOUND_EVENT_DETAILS
4099 ALOGD("Unhandled key event: Dispatching fallback key. "
4100 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4101 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4102#endif
4103 return true; // restart the event
4104 } else {
4105#if DEBUG_OUTBOUND_EVENT_DETAILS
4106 ALOGD("Unhandled key event: No fallback key.");
4107#endif
4108 }
4109 }
4110 }
4111 return false;
4112}
4113
4114bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4115 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4116 return false;
4117}
4118
4119void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4120 mLock.unlock();
4121
4122 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4123
4124 mLock.lock();
4125}
4126
4127void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004128 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4130 entry->downTime, entry->eventTime);
4131}
4132
4133void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4134 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4135 // TODO Write some statistics about how long we spend waiting.
4136}
4137
4138void InputDispatcher::traceInboundQueueLengthLocked() {
4139 if (ATRACE_ENABLED()) {
4140 ATRACE_INT("iq", mInboundQueue.count());
4141 }
4142}
4143
4144void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4145 if (ATRACE_ENABLED()) {
4146 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004147 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 ATRACE_INT(counterName, connection->outboundQueue.count());
4149 }
4150}
4151
4152void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4153 if (ATRACE_ENABLED()) {
4154 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004155 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156 ATRACE_INT(counterName, connection->waitQueue.count());
4157 }
4158}
4159
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004160void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 AutoMutex _l(mLock);
4162
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004163 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 dumpDispatchStateLocked(dump);
4165
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004166 if (!mLastANRState.empty()) {
4167 dump += "\nInput Dispatcher State at time of last ANR:\n";
4168 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 }
4170}
4171
4172void InputDispatcher::monitor() {
4173 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4174 mLock.lock();
4175 mLooper->wake();
4176 mDispatcherIsAliveCondition.wait(mLock);
4177 mLock.unlock();
4178}
4179
4180
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181// --- InputDispatcher::InjectionState ---
4182
4183InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4184 refCount(1),
4185 injectorPid(injectorPid), injectorUid(injectorUid),
4186 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4187 pendingForegroundDispatches(0) {
4188}
4189
4190InputDispatcher::InjectionState::~InjectionState() {
4191}
4192
4193void InputDispatcher::InjectionState::release() {
4194 refCount -= 1;
4195 if (refCount == 0) {
4196 delete this;
4197 } else {
4198 ALOG_ASSERT(refCount > 0);
4199 }
4200}
4201
4202
4203// --- InputDispatcher::EventEntry ---
4204
4205InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4206 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
Yi Kong9b14ac62018-07-17 13:48:38 -07004207 injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208}
4209
4210InputDispatcher::EventEntry::~EventEntry() {
4211 releaseInjectionState();
4212}
4213
4214void InputDispatcher::EventEntry::release() {
4215 refCount -= 1;
4216 if (refCount == 0) {
4217 delete this;
4218 } else {
4219 ALOG_ASSERT(refCount > 0);
4220 }
4221}
4222
4223void InputDispatcher::EventEntry::releaseInjectionState() {
4224 if (injectionState) {
4225 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004226 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 }
4228}
4229
4230
4231// --- InputDispatcher::ConfigurationChangedEntry ---
4232
4233InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4234 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4235}
4236
4237InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4238}
4239
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004240void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4241 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242}
4243
4244
4245// --- InputDispatcher::DeviceResetEntry ---
4246
4247InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4248 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4249 deviceId(deviceId) {
4250}
4251
4252InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4253}
4254
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004255void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4256 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004257 deviceId, policyFlags);
4258}
4259
4260
4261// --- InputDispatcher::KeyEntry ---
4262
4263InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004264 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4266 int32_t repeatCount, nsecs_t downTime) :
4267 EventEntry(TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004268 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4270 repeatCount(repeatCount), downTime(downTime),
4271 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4272 interceptKeyWakeupTime(0) {
4273}
4274
4275InputDispatcher::KeyEntry::~KeyEntry() {
4276}
4277
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004278void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004279 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4281 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004282 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004283 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284}
4285
4286void InputDispatcher::KeyEntry::recycle() {
4287 releaseInjectionState();
4288
4289 dispatchInProgress = false;
4290 syntheticRepeat = false;
4291 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4292 interceptKeyWakeupTime = 0;
4293}
4294
4295
4296// --- InputDispatcher::MotionEntry ---
4297
Michael Wright7b159c92015-05-14 14:48:03 +01004298InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004299 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4300 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004301 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4302 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004303 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004304 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4305 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4307 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004308 deviceId(deviceId), source(source), displayId(displayId), action(action),
4309 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004310 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004311 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312 for (uint32_t i = 0; i < pointerCount; i++) {
4313 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4314 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004315 if (xOffset || yOffset) {
4316 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 }
4319}
4320
4321InputDispatcher::MotionEntry::~MotionEntry() {
4322}
4323
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004324void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004325 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004326 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004327 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004328 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4329 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4330
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 for (uint32_t i = 0; i < pointerCount; i++) {
4332 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004333 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004335 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 pointerCoords[i].getX(), pointerCoords[i].getY());
4337 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004338 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339}
4340
4341
4342// --- InputDispatcher::DispatchEntry ---
4343
4344volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4345
4346InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4347 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4348 seq(nextSeq()),
4349 eventEntry(eventEntry), targetFlags(targetFlags),
4350 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4351 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4352 eventEntry->refCount += 1;
4353}
4354
4355InputDispatcher::DispatchEntry::~DispatchEntry() {
4356 eventEntry->release();
4357}
4358
4359uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4360 // Sequence number 0 is reserved and will never be returned.
4361 uint32_t seq;
4362 do {
4363 seq = android_atomic_inc(&sNextSeqAtomic);
4364 } while (!seq);
4365 return seq;
4366}
4367
4368
4369// --- InputDispatcher::InputState ---
4370
4371InputDispatcher::InputState::InputState() {
4372}
4373
4374InputDispatcher::InputState::~InputState() {
4375}
4376
4377bool InputDispatcher::InputState::isNeutral() const {
4378 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4379}
4380
4381bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4382 int32_t displayId) const {
4383 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4384 const MotionMemento& memento = mMotionMementos.itemAt(i);
4385 if (memento.deviceId == deviceId
4386 && memento.source == source
4387 && memento.displayId == displayId
4388 && memento.hovering) {
4389 return true;
4390 }
4391 }
4392 return false;
4393}
4394
4395bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4396 int32_t action, int32_t flags) {
4397 switch (action) {
4398 case AKEY_EVENT_ACTION_UP: {
4399 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4400 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4401 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4402 mFallbackKeys.removeItemsAt(i);
4403 } else {
4404 i += 1;
4405 }
4406 }
4407 }
4408 ssize_t index = findKeyMemento(entry);
4409 if (index >= 0) {
4410 mKeyMementos.removeAt(index);
4411 return true;
4412 }
4413 /* FIXME: We can't just drop the key up event because that prevents creating
4414 * popup windows that are automatically shown when a key is held and then
4415 * dismissed when the key is released. The problem is that the popup will
4416 * not have received the original key down, so the key up will be considered
4417 * to be inconsistent with its observed state. We could perhaps handle this
4418 * by synthesizing a key down but that will cause other problems.
4419 *
4420 * So for now, allow inconsistent key up events to be dispatched.
4421 *
4422#if DEBUG_OUTBOUND_EVENT_DETAILS
4423 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4424 "keyCode=%d, scanCode=%d",
4425 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4426#endif
4427 return false;
4428 */
4429 return true;
4430 }
4431
4432 case AKEY_EVENT_ACTION_DOWN: {
4433 ssize_t index = findKeyMemento(entry);
4434 if (index >= 0) {
4435 mKeyMementos.removeAt(index);
4436 }
4437 addKeyMemento(entry, flags);
4438 return true;
4439 }
4440
4441 default:
4442 return true;
4443 }
4444}
4445
4446bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4447 int32_t action, int32_t flags) {
4448 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4449 switch (actionMasked) {
4450 case AMOTION_EVENT_ACTION_UP:
4451 case AMOTION_EVENT_ACTION_CANCEL: {
4452 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4453 if (index >= 0) {
4454 mMotionMementos.removeAt(index);
4455 return true;
4456 }
4457#if DEBUG_OUTBOUND_EVENT_DETAILS
4458 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004459 "displayId=%" PRId32 ", actionMasked=%d",
4460 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004461#endif
4462 return false;
4463 }
4464
4465 case AMOTION_EVENT_ACTION_DOWN: {
4466 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4467 if (index >= 0) {
4468 mMotionMementos.removeAt(index);
4469 }
4470 addMotionMemento(entry, flags, false /*hovering*/);
4471 return true;
4472 }
4473
4474 case AMOTION_EVENT_ACTION_POINTER_UP:
4475 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4476 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004477 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4478 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4479 // generate cancellation events for these since they're based in relative rather than
4480 // absolute units.
4481 return true;
4482 }
4483
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004485
4486 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4487 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4488 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4489 // other value and we need to track the motion so we can send cancellation events for
4490 // anything generating fallback events (e.g. DPad keys for joystick movements).
4491 if (index >= 0) {
4492 if (entry->pointerCoords[0].isEmpty()) {
4493 mMotionMementos.removeAt(index);
4494 } else {
4495 MotionMemento& memento = mMotionMementos.editItemAt(index);
4496 memento.setPointers(entry);
4497 }
4498 } else if (!entry->pointerCoords[0].isEmpty()) {
4499 addMotionMemento(entry, flags, false /*hovering*/);
4500 }
4501
4502 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4503 return true;
4504 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 if (index >= 0) {
4506 MotionMemento& memento = mMotionMementos.editItemAt(index);
4507 memento.setPointers(entry);
4508 return true;
4509 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004510#if DEBUG_OUTBOUND_EVENT_DETAILS
4511 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004512 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4513 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514#endif
4515 return false;
4516 }
4517
4518 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4519 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4520 if (index >= 0) {
4521 mMotionMementos.removeAt(index);
4522 return true;
4523 }
4524#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004525 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4526 "displayId=%" PRId32,
4527 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004528#endif
4529 return false;
4530 }
4531
4532 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4533 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4534 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4535 if (index >= 0) {
4536 mMotionMementos.removeAt(index);
4537 }
4538 addMotionMemento(entry, flags, true /*hovering*/);
4539 return true;
4540 }
4541
4542 default:
4543 return true;
4544 }
4545}
4546
4547ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4548 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4549 const KeyMemento& memento = mKeyMementos.itemAt(i);
4550 if (memento.deviceId == entry->deviceId
4551 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004552 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004553 && memento.keyCode == entry->keyCode
4554 && memento.scanCode == entry->scanCode) {
4555 return i;
4556 }
4557 }
4558 return -1;
4559}
4560
4561ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4562 bool hovering) const {
4563 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4564 const MotionMemento& memento = mMotionMementos.itemAt(i);
4565 if (memento.deviceId == entry->deviceId
4566 && memento.source == entry->source
4567 && memento.displayId == entry->displayId
4568 && memento.hovering == hovering) {
4569 return i;
4570 }
4571 }
4572 return -1;
4573}
4574
4575void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4576 mKeyMementos.push();
4577 KeyMemento& memento = mKeyMementos.editTop();
4578 memento.deviceId = entry->deviceId;
4579 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004580 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581 memento.keyCode = entry->keyCode;
4582 memento.scanCode = entry->scanCode;
4583 memento.metaState = entry->metaState;
4584 memento.flags = flags;
4585 memento.downTime = entry->downTime;
4586 memento.policyFlags = entry->policyFlags;
4587}
4588
4589void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4590 int32_t flags, bool hovering) {
4591 mMotionMementos.push();
4592 MotionMemento& memento = mMotionMementos.editTop();
4593 memento.deviceId = entry->deviceId;
4594 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004595 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 memento.flags = flags;
4597 memento.xPrecision = entry->xPrecision;
4598 memento.yPrecision = entry->yPrecision;
4599 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004600 memento.setPointers(entry);
4601 memento.hovering = hovering;
4602 memento.policyFlags = entry->policyFlags;
4603}
4604
4605void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4606 pointerCount = entry->pointerCount;
4607 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4608 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4609 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4610 }
4611}
4612
4613void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4614 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4615 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4616 const KeyMemento& memento = mKeyMementos.itemAt(i);
4617 if (shouldCancelKey(memento, options)) {
4618 outEvents.push(new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004619 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4621 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4622 }
4623 }
4624
4625 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4626 const MotionMemento& memento = mMotionMementos.itemAt(i);
4627 if (shouldCancelMotion(memento, options)) {
4628 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004629 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 memento.hovering
4631 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4632 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004633 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004635 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4636 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637 }
4638 }
4639}
4640
4641void InputDispatcher::InputState::clear() {
4642 mKeyMementos.clear();
4643 mMotionMementos.clear();
4644 mFallbackKeys.clear();
4645}
4646
4647void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4648 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4649 const MotionMemento& memento = mMotionMementos.itemAt(i);
4650 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4651 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4652 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4653 if (memento.deviceId == otherMemento.deviceId
4654 && memento.source == otherMemento.source
4655 && memento.displayId == otherMemento.displayId) {
4656 other.mMotionMementos.removeAt(j);
4657 } else {
4658 j += 1;
4659 }
4660 }
4661 other.mMotionMementos.push(memento);
4662 }
4663 }
4664}
4665
4666int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4667 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4668 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4669}
4670
4671void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4672 int32_t fallbackKeyCode) {
4673 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4674 if (index >= 0) {
4675 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4676 } else {
4677 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4678 }
4679}
4680
4681void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4682 mFallbackKeys.removeItem(originalKeyCode);
4683}
4684
4685bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4686 const CancelationOptions& options) {
4687 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4688 return false;
4689 }
4690
4691 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4692 return false;
4693 }
4694
4695 switch (options.mode) {
4696 case CancelationOptions::CANCEL_ALL_EVENTS:
4697 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4698 return true;
4699 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4700 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004701 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4702 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 default:
4704 return false;
4705 }
4706}
4707
4708bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4709 const CancelationOptions& options) {
4710 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4711 return false;
4712 }
4713
4714 switch (options.mode) {
4715 case CancelationOptions::CANCEL_ALL_EVENTS:
4716 return true;
4717 case CancelationOptions::CANCEL_POINTER_EVENTS:
4718 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4719 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4720 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004721 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4722 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723 default:
4724 return false;
4725 }
4726}
4727
4728
4729// --- InputDispatcher::Connection ---
4730
Robert Carr803535b2018-08-02 16:38:15 -07004731InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4732 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 monitor(monitor),
4734 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4735}
4736
4737InputDispatcher::Connection::~Connection() {
4738}
4739
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004740const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004741 if (inputChannel != nullptr) {
4742 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 }
4744 if (monitor) {
4745 return "monitor";
4746 }
4747 return "?";
4748}
4749
4750const char* InputDispatcher::Connection::getStatusLabel() const {
4751 switch (status) {
4752 case STATUS_NORMAL:
4753 return "NORMAL";
4754
4755 case STATUS_BROKEN:
4756 return "BROKEN";
4757
4758 case STATUS_ZOMBIE:
4759 return "ZOMBIE";
4760
4761 default:
4762 return "UNKNOWN";
4763 }
4764}
4765
4766InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004767 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 if (entry->seq == seq) {
4769 return entry;
4770 }
4771 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004772 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773}
4774
4775
4776// --- InputDispatcher::CommandEntry ---
4777
4778InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004779 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780 seq(0), handled(false) {
4781}
4782
4783InputDispatcher::CommandEntry::~CommandEntry() {
4784}
4785
4786
4787// --- InputDispatcher::TouchState ---
4788
4789InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004790 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791}
4792
4793InputDispatcher::TouchState::~TouchState() {
4794}
4795
4796void InputDispatcher::TouchState::reset() {
4797 down = false;
4798 split = false;
4799 deviceId = -1;
4800 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004801 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 windows.clear();
4803}
4804
4805void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4806 down = other.down;
4807 split = other.split;
4808 deviceId = other.deviceId;
4809 source = other.source;
4810 displayId = other.displayId;
4811 windows = other.windows;
4812}
4813
4814void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4815 int32_t targetFlags, BitSet32 pointerIds) {
4816 if (targetFlags & InputTarget::FLAG_SPLIT) {
4817 split = true;
4818 }
4819
4820 for (size_t i = 0; i < windows.size(); i++) {
4821 TouchedWindow& touchedWindow = windows.editItemAt(i);
4822 if (touchedWindow.windowHandle == windowHandle) {
4823 touchedWindow.targetFlags |= targetFlags;
4824 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4825 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4826 }
4827 touchedWindow.pointerIds.value |= pointerIds.value;
4828 return;
4829 }
4830 }
4831
4832 windows.push();
4833
4834 TouchedWindow& touchedWindow = windows.editTop();
4835 touchedWindow.windowHandle = windowHandle;
4836 touchedWindow.targetFlags = targetFlags;
4837 touchedWindow.pointerIds = pointerIds;
4838}
4839
4840void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4841 for (size_t i = 0; i < windows.size(); i++) {
4842 if (windows.itemAt(i).windowHandle == windowHandle) {
4843 windows.removeAt(i);
4844 return;
4845 }
4846 }
4847}
4848
Robert Carr803535b2018-08-02 16:38:15 -07004849void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4850 for (size_t i = 0; i < windows.size(); i++) {
4851 if (windows.itemAt(i).windowHandle->getInputChannel()->getToken() == token) {
4852 windows.removeAt(i);
4853 return;
4854 }
4855 }
4856}
4857
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4859 for (size_t i = 0 ; i < windows.size(); ) {
4860 TouchedWindow& window = windows.editItemAt(i);
4861 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4862 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4863 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4864 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4865 i += 1;
4866 } else {
4867 windows.removeAt(i);
4868 }
4869 }
4870}
4871
4872sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4873 for (size_t i = 0; i < windows.size(); i++) {
4874 const TouchedWindow& window = windows.itemAt(i);
4875 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4876 return window.windowHandle;
4877 }
4878 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004879 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880}
4881
4882bool InputDispatcher::TouchState::isSlippery() const {
4883 // Must have exactly one foreground window.
4884 bool haveSlipperyForegroundWindow = false;
4885 for (size_t i = 0; i < windows.size(); i++) {
4886 const TouchedWindow& window = windows.itemAt(i);
4887 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4888 if (haveSlipperyForegroundWindow
4889 || !(window.windowHandle->getInfo()->layoutParamsFlags
4890 & InputWindowInfo::FLAG_SLIPPERY)) {
4891 return false;
4892 }
4893 haveSlipperyForegroundWindow = true;
4894 }
4895 }
4896 return haveSlipperyForegroundWindow;
4897}
4898
4899
4900// --- InputDispatcherThread ---
4901
4902InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4903 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4904}
4905
4906InputDispatcherThread::~InputDispatcherThread() {
4907}
4908
4909bool InputDispatcherThread::threadLoop() {
4910 mDispatcher->dispatchOnce();
4911 return true;
4912}
4913
4914} // namespace android