blob: 177f8320298ab6f6338fd356613d36ef633a5054 [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>
Michael Wrightd02c5b62014-02-10 15:10:22 -080061
62#define INDENT " "
63#define INDENT2 " "
64#define INDENT3 " "
65#define INDENT4 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
71// Default input dispatching timeout if there is no focused application or paused window
72// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000073constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080074
75// Amount of time to allow for all pending events to be processed when an app switch
76// key is on the way. This is used to preempt input dispatch and drop input events
77// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000078constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80// Amount of time to allow for an event to be dispatched (measured since its eventTime)
81// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000082constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080083
84// Amount of time to allow touch events to be streamed out to a connection before requiring
85// that the first event be finished. This value extends the ANR timeout by the specified
86// amount. For example, if streaming is allowed to get ahead by one second relative to the
87// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000088constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080089
90// 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 +000091constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
92
93// Log a warning when an interception call takes longer than this to process.
94constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
96// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +000097constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
98
Michael Wrightd02c5b62014-02-10 15:10:22 -080099
100static inline nsecs_t now() {
101 return systemTime(SYSTEM_TIME_MONOTONIC);
102}
103
104static inline const char* toString(bool value) {
105 return value ? "true" : "false";
106}
107
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800108static std::string motionActionToString(int32_t action) {
109 // Convert MotionEvent action to string
110 switch(action & AMOTION_EVENT_ACTION_MASK) {
111 case AMOTION_EVENT_ACTION_DOWN:
112 return "DOWN";
113 case AMOTION_EVENT_ACTION_MOVE:
114 return "MOVE";
115 case AMOTION_EVENT_ACTION_UP:
116 return "UP";
117 case AMOTION_EVENT_ACTION_POINTER_DOWN:
118 return "POINTER_DOWN";
119 case AMOTION_EVENT_ACTION_POINTER_UP:
120 return "POINTER_UP";
121 }
122 return StringPrintf("%" PRId32, action);
123}
124
125static std::string keyActionToString(int32_t action) {
126 // Convert KeyEvent action to string
127 switch(action) {
128 case AKEY_EVENT_ACTION_DOWN:
129 return "DOWN";
130 case AKEY_EVENT_ACTION_UP:
131 return "UP";
132 case AKEY_EVENT_ACTION_MULTIPLE:
133 return "MULTIPLE";
134 }
135 return StringPrintf("%" PRId32, action);
136}
137
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
139 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
140 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
141}
142
143static bool isValidKeyAction(int32_t action) {
144 switch (action) {
145 case AKEY_EVENT_ACTION_DOWN:
146 case AKEY_EVENT_ACTION_UP:
147 return true;
148 default:
149 return false;
150 }
151}
152
153static bool validateKeyEvent(int32_t action) {
154 if (! isValidKeyAction(action)) {
155 ALOGE("Key event has invalid action code 0x%x", action);
156 return false;
157 }
158 return true;
159}
160
Michael Wright7b159c92015-05-14 14:48:03 +0100161static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800162 switch (action & AMOTION_EVENT_ACTION_MASK) {
163 case AMOTION_EVENT_ACTION_DOWN:
164 case AMOTION_EVENT_ACTION_UP:
165 case AMOTION_EVENT_ACTION_CANCEL:
166 case AMOTION_EVENT_ACTION_MOVE:
167 case AMOTION_EVENT_ACTION_OUTSIDE:
168 case AMOTION_EVENT_ACTION_HOVER_ENTER:
169 case AMOTION_EVENT_ACTION_HOVER_MOVE:
170 case AMOTION_EVENT_ACTION_HOVER_EXIT:
171 case AMOTION_EVENT_ACTION_SCROLL:
172 return true;
173 case AMOTION_EVENT_ACTION_POINTER_DOWN:
174 case AMOTION_EVENT_ACTION_POINTER_UP: {
175 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800176 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 }
Michael Wright7b159c92015-05-14 14:48:03 +0100178 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
179 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
180 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 default:
182 return false;
183 }
184}
185
Michael Wright7b159c92015-05-14 14:48:03 +0100186static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100188 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 ALOGE("Motion event has invalid action code 0x%x", action);
190 return false;
191 }
192 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000193 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 pointerCount, MAX_POINTERS);
195 return false;
196 }
197 BitSet32 pointerIdBits;
198 for (size_t i = 0; i < pointerCount; i++) {
199 int32_t id = pointerProperties[i].id;
200 if (id < 0 || id > MAX_POINTER_ID) {
201 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
202 id, MAX_POINTER_ID);
203 return false;
204 }
205 if (pointerIdBits.hasBit(id)) {
206 ALOGE("Motion event has duplicate pointer id %d", id);
207 return false;
208 }
209 pointerIdBits.markBit(id);
210 }
211 return true;
212}
213
214static bool isMainDisplay(int32_t displayId) {
215 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
216}
217
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800218static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800220 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 return;
222 }
223
224 bool first = true;
225 Region::const_iterator cur = region.begin();
226 Region::const_iterator const tail = region.end();
227 while (cur != tail) {
228 if (first) {
229 first = false;
230 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800231 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800233 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 cur++;
235 }
236}
237
Tiger Huang721e26f2018-07-24 22:26:19 +0800238template<typename T, typename U>
239static T getValueByKey(std::unordered_map<U, T>& map, U key) {
240 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
241 return it != map.end() ? it->second : T{};
242}
243
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244
245// --- InputDispatcher ---
246
247InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
248 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700249 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100250 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700251 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800253 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
255 mLooper = new Looper(false);
256
Yi Kong9b14ac62018-07-17 13:48:38 -0700257 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258
259 policy->getDispatcherConfiguration(&mConfig);
260}
261
262InputDispatcher::~InputDispatcher() {
263 { // acquire lock
264 AutoMutex _l(mLock);
265
266 resetKeyRepeatLocked();
267 releasePendingEventLocked();
268 drainInboundQueueLocked();
269 }
270
271 while (mConnectionsByFd.size() != 0) {
272 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
273 }
274}
275
276void InputDispatcher::dispatchOnce() {
277 nsecs_t nextWakeupTime = LONG_LONG_MAX;
278 { // acquire lock
279 AutoMutex _l(mLock);
280 mDispatcherIsAliveCondition.broadcast();
281
282 // Run a dispatch loop if there are no pending commands.
283 // The dispatch loop might enqueue commands to run afterwards.
284 if (!haveCommandsLocked()) {
285 dispatchOnceInnerLocked(&nextWakeupTime);
286 }
287
288 // Run all pending commands if there are any.
289 // If any commands were run then force the next poll to wake up immediately.
290 if (runCommandsLockedInterruptible()) {
291 nextWakeupTime = LONG_LONG_MIN;
292 }
293 } // release lock
294
295 // Wait for callback or timeout or wake. (make sure we round up, not down)
296 nsecs_t currentTime = now();
297 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
298 mLooper->pollOnce(timeoutMillis);
299}
300
301void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
302 nsecs_t currentTime = now();
303
Jeff Browndc5992e2014-04-11 01:27:26 -0700304 // Reset the key repeat timer whenever normal dispatch is suspended while the
305 // device is in a non-interactive state. This is to ensure that we abort a key
306 // repeat if the device is just coming out of sleep.
307 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800308 resetKeyRepeatLocked();
309 }
310
311 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
312 if (mDispatchFrozen) {
313#if DEBUG_FOCUS
314 ALOGD("Dispatch frozen. Waiting some more.");
315#endif
316 return;
317 }
318
319 // Optimize latency of app switches.
320 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
321 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
322 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
323 if (mAppSwitchDueTime < *nextWakeupTime) {
324 *nextWakeupTime = mAppSwitchDueTime;
325 }
326
327 // Ready to start a new event.
328 // If we don't already have a pending event, go grab one.
329 if (! mPendingEvent) {
330 if (mInboundQueue.isEmpty()) {
331 if (isAppSwitchDue) {
332 // The inbound queue is empty so the app switch key we were waiting
333 // for will never arrive. Stop waiting for it.
334 resetPendingAppSwitchLocked(false);
335 isAppSwitchDue = false;
336 }
337
338 // Synthesize a key repeat if appropriate.
339 if (mKeyRepeatState.lastKeyEntry) {
340 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
341 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
342 } else {
343 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
344 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
345 }
346 }
347 }
348
349 // Nothing to do if there is no pending event.
350 if (!mPendingEvent) {
351 return;
352 }
353 } else {
354 // Inbound queue has at least one entry.
355 mPendingEvent = mInboundQueue.dequeueAtHead();
356 traceInboundQueueLengthLocked();
357 }
358
359 // Poke user activity for this event.
360 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
361 pokeUserActivityLocked(mPendingEvent);
362 }
363
364 // Get ready to dispatch the event.
365 resetANRTimeoutsLocked();
366 }
367
368 // Now we have an event to dispatch.
369 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700370 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800371 bool done = false;
372 DropReason dropReason = DROP_REASON_NOT_DROPPED;
373 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
374 dropReason = DROP_REASON_POLICY;
375 } else if (!mDispatchEnabled) {
376 dropReason = DROP_REASON_DISABLED;
377 }
378
379 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700380 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800381 }
382
383 switch (mPendingEvent->type) {
384 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
385 ConfigurationChangedEntry* typedEntry =
386 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
387 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
388 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
389 break;
390 }
391
392 case EventEntry::TYPE_DEVICE_RESET: {
393 DeviceResetEntry* typedEntry =
394 static_cast<DeviceResetEntry*>(mPendingEvent);
395 done = dispatchDeviceResetLocked(currentTime, typedEntry);
396 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
397 break;
398 }
399
400 case EventEntry::TYPE_KEY: {
401 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
402 if (isAppSwitchDue) {
403 if (isAppSwitchKeyEventLocked(typedEntry)) {
404 resetPendingAppSwitchLocked(true);
405 isAppSwitchDue = false;
406 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
407 dropReason = DROP_REASON_APP_SWITCH;
408 }
409 }
410 if (dropReason == DROP_REASON_NOT_DROPPED
411 && isStaleEventLocked(currentTime, typedEntry)) {
412 dropReason = DROP_REASON_STALE;
413 }
414 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
415 dropReason = DROP_REASON_BLOCKED;
416 }
417 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
418 break;
419 }
420
421 case EventEntry::TYPE_MOTION: {
422 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
423 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
424 dropReason = DROP_REASON_APP_SWITCH;
425 }
426 if (dropReason == DROP_REASON_NOT_DROPPED
427 && isStaleEventLocked(currentTime, typedEntry)) {
428 dropReason = DROP_REASON_STALE;
429 }
430 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
431 dropReason = DROP_REASON_BLOCKED;
432 }
433 done = dispatchMotionLocked(currentTime, typedEntry,
434 &dropReason, nextWakeupTime);
435 break;
436 }
437
438 default:
439 ALOG_ASSERT(false);
440 break;
441 }
442
443 if (done) {
444 if (dropReason != DROP_REASON_NOT_DROPPED) {
445 dropInboundEventLocked(mPendingEvent, dropReason);
446 }
Michael Wright3a981722015-06-10 15:26:13 +0100447 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448
449 releasePendingEventLocked();
450 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
451 }
452}
453
454bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
455 bool needWake = mInboundQueue.isEmpty();
456 mInboundQueue.enqueueAtTail(entry);
457 traceInboundQueueLengthLocked();
458
459 switch (entry->type) {
460 case EventEntry::TYPE_KEY: {
461 // Optimize app switch latency.
462 // If the application takes too long to catch up then we drop all events preceding
463 // the app switch key.
464 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
465 if (isAppSwitchKeyEventLocked(keyEntry)) {
466 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
467 mAppSwitchSawKeyDown = true;
468 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
469 if (mAppSwitchSawKeyDown) {
470#if DEBUG_APP_SWITCH
471 ALOGD("App switch is pending!");
472#endif
473 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
474 mAppSwitchSawKeyDown = false;
475 needWake = true;
476 }
477 }
478 }
479 break;
480 }
481
482 case EventEntry::TYPE_MOTION: {
483 // Optimize case where the current application is unresponsive and the user
484 // decides to touch a window in a different application.
485 // If the application takes too long to catch up then we drop all events preceding
486 // the touch into the other window.
487 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
488 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
489 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
490 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Yi Kong9b14ac62018-07-17 13:48:38 -0700491 && mInputTargetWaitApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492 int32_t displayId = motionEntry->displayId;
493 int32_t x = int32_t(motionEntry->pointerCoords[0].
494 getAxisValue(AMOTION_EVENT_AXIS_X));
495 int32_t y = int32_t(motionEntry->pointerCoords[0].
496 getAxisValue(AMOTION_EVENT_AXIS_Y));
497 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700498 if (touchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499 && touchedWindowHandle->inputApplicationHandle
500 != mInputTargetWaitApplicationHandle) {
501 // User touched a different application than the one we are waiting on.
502 // Flag the event, and start pruning the input queue.
503 mNextUnblockedEvent = motionEntry;
504 needWake = true;
505 }
506 }
507 break;
508 }
509 }
510
511 return needWake;
512}
513
514void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
515 entry->refCount += 1;
516 mRecentQueue.enqueueAtTail(entry);
517 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
518 mRecentQueue.dequeueAtHead()->release();
519 }
520}
521
522sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
523 int32_t x, int32_t y) {
524 // Traverse windows from front to back to find touched window.
Arthur Hungb92218b2018-08-14 12:00:21 +0800525 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
526 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800528 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529 const InputWindowInfo* windowInfo = windowHandle->getInfo();
530 if (windowInfo->displayId == displayId) {
531 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532
533 if (windowInfo->visible) {
534 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
535 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
536 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
537 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
538 // Found window.
539 return windowHandle;
540 }
541 }
542 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 }
544 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700545 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546}
547
548void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
549 const char* reason;
550 switch (dropReason) {
551 case DROP_REASON_POLICY:
552#if DEBUG_INBOUND_EVENT_DETAILS
553 ALOGD("Dropped event because policy consumed it.");
554#endif
555 reason = "inbound event was dropped because the policy consumed it";
556 break;
557 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100558 if (mLastDropReason != DROP_REASON_DISABLED) {
559 ALOGI("Dropped event because input dispatch is disabled.");
560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561 reason = "inbound event was dropped because input dispatch is disabled";
562 break;
563 case DROP_REASON_APP_SWITCH:
564 ALOGI("Dropped event because of pending overdue app switch.");
565 reason = "inbound event was dropped because of pending overdue app switch";
566 break;
567 case DROP_REASON_BLOCKED:
568 ALOGI("Dropped event because the current application is not responding and the user "
569 "has started interacting with a different application.");
570 reason = "inbound event was dropped because the current application is not responding "
571 "and the user has started interacting with a different application";
572 break;
573 case DROP_REASON_STALE:
574 ALOGI("Dropped event because it is stale.");
575 reason = "inbound event was dropped because it is stale";
576 break;
577 default:
578 ALOG_ASSERT(false);
579 return;
580 }
581
582 switch (entry->type) {
583 case EventEntry::TYPE_KEY: {
584 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
585 synthesizeCancelationEventsForAllConnectionsLocked(options);
586 break;
587 }
588 case EventEntry::TYPE_MOTION: {
589 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
590 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
591 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
592 synthesizeCancelationEventsForAllConnectionsLocked(options);
593 } else {
594 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
595 synthesizeCancelationEventsForAllConnectionsLocked(options);
596 }
597 break;
598 }
599 }
600}
601
602bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
603 return keyCode == AKEYCODE_HOME
604 || keyCode == AKEYCODE_ENDCALL
605 || keyCode == AKEYCODE_APP_SWITCH;
606}
607
608bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
609 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
610 && isAppSwitchKeyCode(keyEntry->keyCode)
611 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
612 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
613}
614
615bool InputDispatcher::isAppSwitchPendingLocked() {
616 return mAppSwitchDueTime != LONG_LONG_MAX;
617}
618
619void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
620 mAppSwitchDueTime = LONG_LONG_MAX;
621
622#if DEBUG_APP_SWITCH
623 if (handled) {
624 ALOGD("App switch has arrived.");
625 } else {
626 ALOGD("App switch was abandoned.");
627 }
628#endif
629}
630
631bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
632 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
633}
634
635bool InputDispatcher::haveCommandsLocked() const {
636 return !mCommandQueue.isEmpty();
637}
638
639bool InputDispatcher::runCommandsLockedInterruptible() {
640 if (mCommandQueue.isEmpty()) {
641 return false;
642 }
643
644 do {
645 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
646
647 Command command = commandEntry->command;
648 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
649
650 commandEntry->connection.clear();
651 delete commandEntry;
652 } while (! mCommandQueue.isEmpty());
653 return true;
654}
655
656InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
657 CommandEntry* commandEntry = new CommandEntry(command);
658 mCommandQueue.enqueueAtTail(commandEntry);
659 return commandEntry;
660}
661
662void InputDispatcher::drainInboundQueueLocked() {
663 while (! mInboundQueue.isEmpty()) {
664 EventEntry* entry = mInboundQueue.dequeueAtHead();
665 releaseInboundEventLocked(entry);
666 }
667 traceInboundQueueLengthLocked();
668}
669
670void InputDispatcher::releasePendingEventLocked() {
671 if (mPendingEvent) {
672 resetANRTimeoutsLocked();
673 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700674 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 }
676}
677
678void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
679 InjectionState* injectionState = entry->injectionState;
680 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
681#if DEBUG_DISPATCH_CYCLE
682 ALOGD("Injected inbound event was dropped.");
683#endif
684 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
685 }
686 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700687 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800688 }
689 addRecentEventLocked(entry);
690 entry->release();
691}
692
693void InputDispatcher::resetKeyRepeatLocked() {
694 if (mKeyRepeatState.lastKeyEntry) {
695 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700696 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 }
698}
699
700InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
701 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
702
703 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700704 uint32_t policyFlags = entry->policyFlags &
705 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800706 if (entry->refCount == 1) {
707 entry->recycle();
708 entry->eventTime = currentTime;
709 entry->policyFlags = policyFlags;
710 entry->repeatCount += 1;
711 } else {
712 KeyEntry* newEntry = new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100713 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714 entry->action, entry->flags, entry->keyCode, entry->scanCode,
715 entry->metaState, entry->repeatCount + 1, entry->downTime);
716
717 mKeyRepeatState.lastKeyEntry = newEntry;
718 entry->release();
719
720 entry = newEntry;
721 }
722 entry->syntheticRepeat = true;
723
724 // Increment reference count since we keep a reference to the event in
725 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
726 entry->refCount += 1;
727
728 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
729 return entry;
730}
731
732bool InputDispatcher::dispatchConfigurationChangedLocked(
733 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
734#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700735 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736#endif
737
738 // Reset key repeating in case a keyboard device was added or removed or something.
739 resetKeyRepeatLocked();
740
741 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
742 CommandEntry* commandEntry = postCommandLocked(
743 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
744 commandEntry->eventTime = entry->eventTime;
745 return true;
746}
747
748bool InputDispatcher::dispatchDeviceResetLocked(
749 nsecs_t currentTime, DeviceResetEntry* entry) {
750#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700751 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
752 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753#endif
754
755 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
756 "device was reset");
757 options.deviceId = entry->deviceId;
758 synthesizeCancelationEventsForAllConnectionsLocked(options);
759 return true;
760}
761
762bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
763 DropReason* dropReason, nsecs_t* nextWakeupTime) {
764 // Preprocessing.
765 if (! entry->dispatchInProgress) {
766 if (entry->repeatCount == 0
767 && entry->action == AKEY_EVENT_ACTION_DOWN
768 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
769 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
770 if (mKeyRepeatState.lastKeyEntry
771 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
772 // We have seen two identical key downs in a row which indicates that the device
773 // driver is automatically generating key repeats itself. We take note of the
774 // repeat here, but we disable our own next key repeat timer since it is clear that
775 // we will not need to synthesize key repeats ourselves.
776 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
777 resetKeyRepeatLocked();
778 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
779 } else {
780 // Not a repeat. Save key down state in case we do see a repeat later.
781 resetKeyRepeatLocked();
782 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
783 }
784 mKeyRepeatState.lastKeyEntry = entry;
785 entry->refCount += 1;
786 } else if (! entry->syntheticRepeat) {
787 resetKeyRepeatLocked();
788 }
789
790 if (entry->repeatCount == 1) {
791 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
792 } else {
793 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
794 }
795
796 entry->dispatchInProgress = true;
797
798 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
799 }
800
801 // Handle case where the policy asked us to try again later last time.
802 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
803 if (currentTime < entry->interceptKeyWakeupTime) {
804 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
805 *nextWakeupTime = entry->interceptKeyWakeupTime;
806 }
807 return false; // wait until next wakeup
808 }
809 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
810 entry->interceptKeyWakeupTime = 0;
811 }
812
813 // Give the policy a chance to intercept the key.
814 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
815 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
816 CommandEntry* commandEntry = postCommandLocked(
817 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800818 sp<InputWindowHandle> focusedWindowHandle =
819 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
820 if (focusedWindowHandle != nullptr) {
821 commandEntry->inputWindowHandle = focusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 }
823 commandEntry->keyEntry = entry;
824 entry->refCount += 1;
825 return false; // wait for the command to run
826 } else {
827 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
828 }
829 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
830 if (*dropReason == DROP_REASON_NOT_DROPPED) {
831 *dropReason = DROP_REASON_POLICY;
832 }
833 }
834
835 // Clean up if dropping the event.
836 if (*dropReason != DROP_REASON_NOT_DROPPED) {
837 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
838 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
839 return true;
840 }
841
842 // Identify targets.
843 Vector<InputTarget> inputTargets;
844 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
845 entry, inputTargets, nextWakeupTime);
846 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
847 return false;
848 }
849
850 setInjectionResultLocked(entry, injectionResult);
851 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
852 return true;
853 }
854
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800855 // Add monitor channels from event's or focused display.
856 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857
858 // Dispatch the key.
859 dispatchEventLocked(currentTime, entry, inputTargets);
860 return true;
861}
862
863void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
864#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100865 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
866 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800867 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100869 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800871 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872#endif
873}
874
875bool InputDispatcher::dispatchMotionLocked(
876 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
877 // Preprocessing.
878 if (! entry->dispatchInProgress) {
879 entry->dispatchInProgress = true;
880
881 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
882 }
883
884 // Clean up if dropping the event.
885 if (*dropReason != DROP_REASON_NOT_DROPPED) {
886 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
887 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
888 return true;
889 }
890
891 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
892
893 // Identify targets.
894 Vector<InputTarget> inputTargets;
895
896 bool conflictingPointerActions = false;
897 int32_t injectionResult;
898 if (isPointerEvent) {
899 // Pointer event. (eg. touchscreen)
900 injectionResult = findTouchedWindowTargetsLocked(currentTime,
901 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
902 } else {
903 // Non touch event. (eg. trackball)
904 injectionResult = findFocusedWindowTargetsLocked(currentTime,
905 entry, inputTargets, nextWakeupTime);
906 }
907 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
908 return false;
909 }
910
911 setInjectionResultLocked(entry, injectionResult);
912 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100913 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
914 CancelationOptions::Mode mode(isPointerEvent ?
915 CancelationOptions::CANCEL_POINTER_EVENTS :
916 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
917 CancelationOptions options(mode, "input event injection failed");
918 synthesizeCancelationEventsForMonitorsLocked(options);
919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800920 return true;
921 }
922
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800923 // Add monitor channels from event's or focused display.
924 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925
926 // Dispatch the motion.
927 if (conflictingPointerActions) {
928 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
929 "conflicting pointer actions");
930 synthesizeCancelationEventsForAllConnectionsLocked(options);
931 }
932 dispatchEventLocked(currentTime, entry, inputTargets);
933 return true;
934}
935
936
937void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
938#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800939 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
940 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100941 "action=0x%x, actionButton=0x%x, flags=0x%x, "
942 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800943 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800945 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100946 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 entry->metaState, entry->buttonState,
948 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800949 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950
951 for (uint32_t i = 0; i < entry->pointerCount; i++) {
952 ALOGD(" Pointer %d: id=%d, toolType=%d, "
953 "x=%f, y=%f, pressure=%f, size=%f, "
954 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800955 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956 i, entry->pointerProperties[i].id,
957 entry->pointerProperties[i].toolType,
958 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
959 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
960 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
961 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
962 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
963 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
964 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
965 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800966 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967 }
968#endif
969}
970
971void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
972 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
973#if DEBUG_DISPATCH_CYCLE
974 ALOGD("dispatchEventToCurrentInputTargets");
975#endif
976
977 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
978
979 pokeUserActivityLocked(eventEntry);
980
981 for (size_t i = 0; i < inputTargets.size(); i++) {
982 const InputTarget& inputTarget = inputTargets.itemAt(i);
983
984 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
985 if (connectionIndex >= 0) {
986 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
987 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
988 } else {
989#if DEBUG_FOCUS
990 ALOGD("Dropping event delivery to target with channel '%s' because it "
991 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800992 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993#endif
994 }
995 }
996}
997
998int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
999 const EventEntry* entry,
1000 const sp<InputApplicationHandle>& applicationHandle,
1001 const sp<InputWindowHandle>& windowHandle,
1002 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001003 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001004 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1005#if DEBUG_FOCUS
1006 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1007#endif
1008 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1009 mInputTargetWaitStartTime = currentTime;
1010 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1011 mInputTargetWaitTimeoutExpired = false;
1012 mInputTargetWaitApplicationHandle.clear();
1013 }
1014 } else {
1015 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1016#if DEBUG_FOCUS
1017 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001018 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 reason);
1020#endif
1021 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001022 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001024 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 timeout = applicationHandle->getDispatchingTimeout(
1026 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1027 } else {
1028 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1029 }
1030
1031 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1032 mInputTargetWaitStartTime = currentTime;
1033 mInputTargetWaitTimeoutTime = currentTime + timeout;
1034 mInputTargetWaitTimeoutExpired = false;
1035 mInputTargetWaitApplicationHandle.clear();
1036
Yi Kong9b14ac62018-07-17 13:48:38 -07001037 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
1039 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001040 if (mInputTargetWaitApplicationHandle == nullptr && applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 mInputTargetWaitApplicationHandle = applicationHandle;
1042 }
1043 }
1044 }
1045
1046 if (mInputTargetWaitTimeoutExpired) {
1047 return INPUT_EVENT_INJECTION_TIMED_OUT;
1048 }
1049
1050 if (currentTime >= mInputTargetWaitTimeoutTime) {
1051 onANRLocked(currentTime, applicationHandle, windowHandle,
1052 entry->eventTime, mInputTargetWaitStartTime, reason);
1053
1054 // Force poll loop to wake up immediately on next iteration once we get the
1055 // ANR response back from the policy.
1056 *nextWakeupTime = LONG_LONG_MIN;
1057 return INPUT_EVENT_INJECTION_PENDING;
1058 } else {
1059 // Force poll loop to wake up when timeout is due.
1060 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1061 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1062 }
1063 return INPUT_EVENT_INJECTION_PENDING;
1064 }
1065}
1066
1067void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1068 const sp<InputChannel>& inputChannel) {
1069 if (newTimeout > 0) {
1070 // Extend the timeout.
1071 mInputTargetWaitTimeoutTime = now() + newTimeout;
1072 } else {
1073 // Give up.
1074 mInputTargetWaitTimeoutExpired = true;
1075
1076 // Input state will not be realistic. Mark it out of sync.
1077 if (inputChannel.get()) {
1078 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1079 if (connectionIndex >= 0) {
1080 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1081 sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
1082
Yi Kong9b14ac62018-07-17 13:48:38 -07001083 if (windowHandle != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001084 const InputWindowInfo* info = windowHandle->getInfo();
1085 if (info) {
1086 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(info->displayId);
1087 if (stateIndex >= 0) {
1088 mTouchStatesByDisplay.editValueAt(stateIndex).removeWindow(
1089 windowHandle);
1090 }
1091 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 }
1093
1094 if (connection->status == Connection::STATUS_NORMAL) {
1095 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1096 "application not responding");
1097 synthesizeCancelationEventsForConnectionLocked(connection, options);
1098 }
1099 }
1100 }
1101 }
1102}
1103
1104nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1105 nsecs_t currentTime) {
1106 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1107 return currentTime - mInputTargetWaitStartTime;
1108 }
1109 return 0;
1110}
1111
1112void InputDispatcher::resetANRTimeoutsLocked() {
1113#if DEBUG_FOCUS
1114 ALOGD("Resetting ANR timeouts.");
1115#endif
1116
1117 // Reset input target wait timeout.
1118 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
1119 mInputTargetWaitApplicationHandle.clear();
1120}
1121
Tiger Huang721e26f2018-07-24 22:26:19 +08001122/**
1123 * Get the display id that the given event should go to. If this event specifies a valid display id,
1124 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1125 * Focused display is the display that the user most recently interacted with.
1126 */
1127int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1128 int32_t displayId;
1129 switch (entry->type) {
1130 case EventEntry::TYPE_KEY: {
1131 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1132 displayId = typedEntry->displayId;
1133 break;
1134 }
1135 case EventEntry::TYPE_MOTION: {
1136 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1137 displayId = typedEntry->displayId;
1138 break;
1139 }
1140 default: {
1141 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1142 return ADISPLAY_ID_NONE;
1143 }
1144 }
1145 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1146}
1147
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1149 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1150 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001151 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152
Tiger Huang721e26f2018-07-24 22:26:19 +08001153 int32_t displayId = getTargetDisplayId(entry);
1154 sp<InputWindowHandle> focusedWindowHandle =
1155 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1156 sp<InputApplicationHandle> focusedApplicationHandle =
1157 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1158
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159 // If there is no currently focused window and no focused application
1160 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001161 if (focusedWindowHandle == nullptr) {
1162 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001164 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165 "Waiting because no window has focus but there is a "
1166 "focused application that may eventually add a window "
1167 "when it finishes starting up.");
1168 goto Unresponsive;
1169 }
1170
Arthur Hung3b413f22018-10-26 18:05:34 +08001171 ALOGI("Dropping event because there is no focused window or focused application in display "
1172 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1174 goto Failed;
1175 }
1176
1177 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001178 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1180 goto Failed;
1181 }
1182
Jeff Brownffb49772014-10-10 19:01:34 -07001183 // Check whether the window is ready for more input.
1184 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001185 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001186 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001188 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189 goto Unresponsive;
1190 }
1191
1192 // Success! Output targets.
1193 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001194 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1196 inputTargets);
1197
1198 // Done.
1199Failed:
1200Unresponsive:
1201 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1202 updateDispatchStatisticsLocked(currentTime, entry,
1203 injectionResult, timeSpentWaitingForApplication);
1204#if DEBUG_FOCUS
1205 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1206 "timeSpentWaitingForApplication=%0.1fms",
1207 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1208#endif
1209 return injectionResult;
1210}
1211
1212int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1213 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1214 bool* outConflictingPointerActions) {
1215 enum InjectionPermission {
1216 INJECTION_PERMISSION_UNKNOWN,
1217 INJECTION_PERMISSION_GRANTED,
1218 INJECTION_PERMISSION_DENIED
1219 };
1220
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 // For security reasons, we defer updating the touch state until we are sure that
1222 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 int32_t displayId = entry->displayId;
1224 int32_t action = entry->action;
1225 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1226
1227 // Update the touch state as needed based on the properties of the touch event.
1228 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1229 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1230 sp<InputWindowHandle> newHoverWindowHandle;
1231
Jeff Brownf086ddb2014-02-11 14:28:48 -08001232 // Copy current touch state into mTempTouchState.
1233 // This state is always reset at the end of this function, so if we don't find state
1234 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001235 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001236 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1237 if (oldStateIndex >= 0) {
1238 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1239 mTempTouchState.copyFrom(*oldState);
1240 }
1241
1242 bool isSplit = mTempTouchState.split;
1243 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1244 && (mTempTouchState.deviceId != entry->deviceId
1245 || mTempTouchState.source != entry->source
1246 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001247 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1248 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1249 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1250 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1251 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1252 || isHoverAction);
1253 bool wrongDevice = false;
1254 if (newGesture) {
1255 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001256 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001258 ALOGD("Dropping event because a pointer for a different device is already down "
1259 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001261 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1263 switchedDevice = false;
1264 wrongDevice = true;
1265 goto Failed;
1266 }
1267 mTempTouchState.reset();
1268 mTempTouchState.down = down;
1269 mTempTouchState.deviceId = entry->deviceId;
1270 mTempTouchState.source = entry->source;
1271 mTempTouchState.displayId = displayId;
1272 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001273 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1274#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001275 ALOGI("Dropping move event because a pointer for a different device is already active "
1276 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001277#endif
1278 // TODO: test multiple simultaneous input streams.
1279 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1280 switchedDevice = false;
1281 wrongDevice = true;
1282 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 }
1284
1285 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1286 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1287
1288 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1289 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1290 getAxisValue(AMOTION_EVENT_AXIS_X));
1291 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1292 getAxisValue(AMOTION_EVENT_AXIS_Y));
1293 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294 bool isTouchModal = false;
1295
1296 // Traverse windows from front to back to find touched window and outside targets.
Arthur Hungb92218b2018-08-14 12:00:21 +08001297 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1298 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001300 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001301 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1302 if (windowInfo->displayId != displayId) {
1303 continue; // wrong display
1304 }
1305
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 int32_t flags = windowInfo->layoutParamsFlags;
1307 if (windowInfo->visible) {
1308 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1309 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1310 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1311 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001312 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 break; // found touched window, exit window loop
1314 }
1315 }
1316
1317 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1318 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001320 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321 }
1322 }
1323 }
1324
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001326 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001327 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1328 // New window supports splitting.
1329 isSplit = true;
1330 } else if (isSplit) {
1331 // New window does not support splitting but we have already split events.
1332 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001333 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001334 }
1335
1336 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001337 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 // Try to assign the pointer to the first foreground window we find, if there is one.
1339 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001340 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001341 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1342 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1344 goto Failed;
1345 }
1346 }
1347
1348 // Set target flags.
1349 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1350 if (isSplit) {
1351 targetFlags |= InputTarget::FLAG_SPLIT;
1352 }
1353 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1354 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001355 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1356 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001357 }
1358
1359 // Update hover state.
1360 if (isHoverAction) {
1361 newHoverWindowHandle = newTouchedWindowHandle;
1362 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1363 newHoverWindowHandle = mLastHoverWindowHandle;
1364 }
1365
1366 // Update the temporary touch state.
1367 BitSet32 pointerIds;
1368 if (isSplit) {
1369 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1370 pointerIds.markBit(pointerId);
1371 }
1372 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1373 } else {
1374 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1375
1376 // If the pointer is not currently down, then ignore the event.
1377 if (! mTempTouchState.down) {
1378#if DEBUG_FOCUS
1379 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001380 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001381#endif
1382 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1383 goto Failed;
1384 }
1385
1386 // Check whether touches should slip outside of the current foreground window.
1387 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1388 && entry->pointerCount == 1
1389 && mTempTouchState.isSlippery()) {
1390 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1391 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1392
1393 sp<InputWindowHandle> oldTouchedWindowHandle =
1394 mTempTouchState.getFirstForegroundWindowHandle();
1395 sp<InputWindowHandle> newTouchedWindowHandle =
1396 findTouchedWindowAtLocked(displayId, x, y);
1397 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001398 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001399#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001400 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001401 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001402 newTouchedWindowHandle->getName().c_str(),
1403 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404#endif
1405 // Make a slippery exit from the old window.
1406 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1407 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1408
1409 // Make a slippery entrance into the new window.
1410 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1411 isSplit = true;
1412 }
1413
1414 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1415 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1416 if (isSplit) {
1417 targetFlags |= InputTarget::FLAG_SPLIT;
1418 }
1419 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1420 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1421 }
1422
1423 BitSet32 pointerIds;
1424 if (isSplit) {
1425 pointerIds.markBit(entry->pointerProperties[0].id);
1426 }
1427 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1428 }
1429 }
1430 }
1431
1432 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1433 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001434 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435#if DEBUG_HOVER
1436 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001437 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438#endif
1439 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1440 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1441 }
1442
1443 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001444 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445#if DEBUG_HOVER
1446 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001447 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448#endif
1449 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1450 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1451 }
1452 }
1453
1454 // Check permission to inject into all touched foreground windows and ensure there
1455 // is at least one touched foreground window.
1456 {
1457 bool haveForegroundWindow = false;
1458 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1459 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1460 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1461 haveForegroundWindow = true;
1462 if (! checkInjectionPermission(touchedWindow.windowHandle,
1463 entry->injectionState)) {
1464 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1465 injectionPermission = INJECTION_PERMISSION_DENIED;
1466 goto Failed;
1467 }
1468 }
1469 }
1470 if (! haveForegroundWindow) {
1471#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001472 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1473 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474#endif
1475 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1476 goto Failed;
1477 }
1478
1479 // Permission granted to injection into all touched foreground windows.
1480 injectionPermission = INJECTION_PERMISSION_GRANTED;
1481 }
1482
1483 // Check whether windows listening for outside touches are owned by the same UID. If it is
1484 // set the policy flag that we will not reveal coordinate information to this window.
1485 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1486 sp<InputWindowHandle> foregroundWindowHandle =
1487 mTempTouchState.getFirstForegroundWindowHandle();
1488 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1489 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1490 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1491 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1492 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1493 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1494 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1495 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1496 }
1497 }
1498 }
1499 }
1500
1501 // Ensure all touched foreground windows are ready for new input.
1502 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1503 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1504 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001505 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001506 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001507 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001508 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001510 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 goto Unresponsive;
1512 }
1513 }
1514 }
1515
1516 // If this is the first pointer going down and the touched window has a wallpaper
1517 // then also add the touched wallpaper windows so they are locked in for the duration
1518 // of the touch gesture.
1519 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1520 // engine only supports touch events. We would need to add a mechanism similar
1521 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1522 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1523 sp<InputWindowHandle> foregroundWindowHandle =
1524 mTempTouchState.getFirstForegroundWindowHandle();
1525 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001526 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1527 size_t numWindows = windowHandles.size();
1528 for (size_t i = 0; i < numWindows; i++) {
1529 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 const InputWindowInfo* info = windowHandle->getInfo();
1531 if (info->displayId == displayId
1532 && windowHandle->getInfo()->layoutParamsType
1533 == InputWindowInfo::TYPE_WALLPAPER) {
1534 mTempTouchState.addOrUpdateWindow(windowHandle,
1535 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001536 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 | InputTarget::FLAG_DISPATCH_AS_IS,
1538 BitSet32(0));
1539 }
1540 }
1541 }
1542 }
1543
1544 // Success! Output targets.
1545 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1546
1547 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1548 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1549 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1550 touchedWindow.pointerIds, inputTargets);
1551 }
1552
1553 // Drop the outside or hover touch windows since we will not care about them
1554 // in the next iteration.
1555 mTempTouchState.filterNonAsIsTouchWindows();
1556
1557Failed:
1558 // Check injection permission once and for all.
1559 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001560 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 injectionPermission = INJECTION_PERMISSION_GRANTED;
1562 } else {
1563 injectionPermission = INJECTION_PERMISSION_DENIED;
1564 }
1565 }
1566
1567 // Update final pieces of touch state if the injector had permission.
1568 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1569 if (!wrongDevice) {
1570 if (switchedDevice) {
1571#if DEBUG_FOCUS
1572 ALOGD("Conflicting pointer actions: Switched to a different device.");
1573#endif
1574 *outConflictingPointerActions = true;
1575 }
1576
1577 if (isHoverAction) {
1578 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001579 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580#if DEBUG_FOCUS
1581 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1582#endif
1583 *outConflictingPointerActions = true;
1584 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001585 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001586 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1587 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001588 mTempTouchState.deviceId = entry->deviceId;
1589 mTempTouchState.source = entry->source;
1590 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 }
1592 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1593 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1594 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001595 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1597 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001598 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599#if DEBUG_FOCUS
1600 ALOGD("Conflicting pointer actions: Down received while already down.");
1601#endif
1602 *outConflictingPointerActions = true;
1603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1605 // One pointer went up.
1606 if (isSplit) {
1607 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1608 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1609
1610 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1611 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1612 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1613 touchedWindow.pointerIds.clearBit(pointerId);
1614 if (touchedWindow.pointerIds.isEmpty()) {
1615 mTempTouchState.windows.removeAt(i);
1616 continue;
1617 }
1618 }
1619 i += 1;
1620 }
1621 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001622 }
1623
1624 // Save changes unless the action was scroll in which case the temporary touch
1625 // state was only valid for this one action.
1626 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1627 if (mTempTouchState.displayId >= 0) {
1628 if (oldStateIndex >= 0) {
1629 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1630 } else {
1631 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1632 }
1633 } else if (oldStateIndex >= 0) {
1634 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1635 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 }
1637
1638 // Update hover state.
1639 mLastHoverWindowHandle = newHoverWindowHandle;
1640 }
1641 } else {
1642#if DEBUG_FOCUS
1643 ALOGD("Not updating touch focus because injection was denied.");
1644#endif
1645 }
1646
1647Unresponsive:
1648 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1649 mTempTouchState.reset();
1650
1651 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1652 updateDispatchStatisticsLocked(currentTime, entry,
1653 injectionResult, timeSpentWaitingForApplication);
1654#if DEBUG_FOCUS
1655 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1656 "timeSpentWaitingForApplication=%0.1fms",
1657 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1658#endif
1659 return injectionResult;
1660}
1661
1662void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1663 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
1664 inputTargets.push();
1665
1666 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1667 InputTarget& target = inputTargets.editTop();
1668 target.inputChannel = windowInfo->inputChannel;
1669 target.flags = targetFlags;
1670 target.xOffset = - windowInfo->frameLeft;
1671 target.yOffset = - windowInfo->frameTop;
1672 target.scaleFactor = windowInfo->scaleFactor;
1673 target.pointerIds = pointerIds;
1674}
1675
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001676void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets,
1677 int32_t displayId) {
1678 std::unordered_map<int32_t, Vector<sp<InputChannel>>>::const_iterator it =
1679 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001681 if (it != mMonitoringChannelsByDisplay.end()) {
1682 const Vector<sp<InputChannel>>& monitoringChannels = it->second;
1683 const size_t numChannels = monitoringChannels.size();
1684 for (size_t i = 0; i < numChannels; i++) {
1685 inputTargets.push();
1686
1687 InputTarget& target = inputTargets.editTop();
1688 target.inputChannel = monitoringChannels[i];
1689 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1690 target.xOffset = 0;
1691 target.yOffset = 0;
1692 target.pointerIds.clear();
1693 target.scaleFactor = 1.0f;
1694 }
1695 } else {
1696 // If there is no monitor channel registered or all monitor channel unregistered,
1697 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001698 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001699 }
1700}
1701
1702bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1703 const InjectionState* injectionState) {
1704 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001705 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001706 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1707 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001708 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1710 "owned by uid %d",
1711 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001712 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 windowHandle->getInfo()->ownerUid);
1714 } else {
1715 ALOGW("Permission denied: injecting event from pid %d uid %d",
1716 injectionState->injectorPid, injectionState->injectorUid);
1717 }
1718 return false;
1719 }
1720 return true;
1721}
1722
1723bool InputDispatcher::isWindowObscuredAtPointLocked(
1724 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1725 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001726 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1727 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001729 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 if (otherHandle == windowHandle) {
1731 break;
1732 }
1733
1734 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1735 if (otherInfo->displayId == displayId
1736 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1737 && otherInfo->frameContainsPoint(x, y)) {
1738 return true;
1739 }
1740 }
1741 return false;
1742}
1743
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001744
1745bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1746 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001747 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001748 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hungb92218b2018-08-14 12:00:21 +08001749 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001750 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001751 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001752 if (otherHandle == windowHandle) {
1753 break;
1754 }
1755
1756 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1757 if (otherInfo->displayId == displayId
1758 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1759 && otherInfo->overlaps(windowInfo)) {
1760 return true;
1761 }
1762 }
1763 return false;
1764}
1765
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001766std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001767 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1768 const char* targetType) {
1769 // If the window is paused then keep waiting.
1770 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001771 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001772 }
1773
1774 // If the window's connection is not registered then keep waiting.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001775 ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
Jeff Brownffb49772014-10-10 19:01:34 -07001776 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001777 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001778 "registered with the input dispatcher. The window may be in the process "
1779 "of being removed.", targetType);
1780 }
1781
1782 // If the connection is dead then keep waiting.
1783 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1784 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001785 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001786 "The window may be in the process of being removed.", targetType,
1787 connection->getStatusLabel());
1788 }
1789
1790 // If the connection is backed up then keep waiting.
1791 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001792 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001793 "Outbound queue length: %d. Wait queue length: %d.",
1794 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1795 }
1796
1797 // Ensure that the dispatch queues aren't too far backed up for this event.
1798 if (eventEntry->type == EventEntry::TYPE_KEY) {
1799 // If the event is a key event, then we must wait for all previous events to
1800 // complete before delivering it because previous events may have the
1801 // side-effect of transferring focus to a different window and we want to
1802 // ensure that the following keys are sent to the new window.
1803 //
1804 // Suppose the user touches a button in a window then immediately presses "A".
1805 // If the button causes a pop-up window to appear then we want to ensure that
1806 // the "A" key is delivered to the new pop-up window. This is because users
1807 // often anticipate pending UI changes when typing on a keyboard.
1808 // To obtain this behavior, we must serialize key events with respect to all
1809 // prior input events.
1810 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001811 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001812 "finished processing all of the input events that were previously "
1813 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1814 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815 }
Jeff Brownffb49772014-10-10 19:01:34 -07001816 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001817 // Touch events can always be sent to a window immediately because the user intended
1818 // to touch whatever was visible at the time. Even if focus changes or a new
1819 // window appears moments later, the touch event was meant to be delivered to
1820 // whatever window happened to be on screen at the time.
1821 //
1822 // Generic motion events, such as trackball or joystick events are a little trickier.
1823 // Like key events, generic motion events are delivered to the focused window.
1824 // Unlike key events, generic motion events don't tend to transfer focus to other
1825 // windows and it is not important for them to be serialized. So we prefer to deliver
1826 // generic motion events as soon as possible to improve efficiency and reduce lag
1827 // through batching.
1828 //
1829 // The one case where we pause input event delivery is when the wait queue is piling
1830 // up with lots of events because the application is not responding.
1831 // This condition ensures that ANRs are detected reliably.
1832 if (!connection->waitQueue.isEmpty()
1833 && currentTime >= connection->waitQueue.head->deliveryTime
1834 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001835 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001836 "finished processing certain input events that were delivered to it over "
1837 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1838 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1839 connection->waitQueue.count(),
1840 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 }
1842 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001843 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844}
1845
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001846std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 const sp<InputApplicationHandle>& applicationHandle,
1848 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001849 if (applicationHandle != nullptr) {
1850 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001851 std::string label(applicationHandle->getName());
1852 label += " - ";
1853 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 return label;
1855 } else {
1856 return applicationHandle->getName();
1857 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001858 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 return windowHandle->getName();
1860 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001861 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862 }
1863}
1864
1865void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001866 int32_t displayId = getTargetDisplayId(eventEntry);
1867 sp<InputWindowHandle> focusedWindowHandle =
1868 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1869 if (focusedWindowHandle != nullptr) {
1870 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001871 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1872#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001873 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874#endif
1875 return;
1876 }
1877 }
1878
1879 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1880 switch (eventEntry->type) {
1881 case EventEntry::TYPE_MOTION: {
1882 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1883 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1884 return;
1885 }
1886
1887 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1888 eventType = USER_ACTIVITY_EVENT_TOUCH;
1889 }
1890 break;
1891 }
1892 case EventEntry::TYPE_KEY: {
1893 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1894 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1895 return;
1896 }
1897 eventType = USER_ACTIVITY_EVENT_BUTTON;
1898 break;
1899 }
1900 }
1901
1902 CommandEntry* commandEntry = postCommandLocked(
1903 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1904 commandEntry->eventTime = eventEntry->eventTime;
1905 commandEntry->userActivityEventType = eventType;
1906}
1907
1908void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1909 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1910#if DEBUG_DISPATCH_CYCLE
1911 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
1912 "xOffset=%f, yOffset=%f, scaleFactor=%f, "
1913 "pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001914 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 inputTarget->xOffset, inputTarget->yOffset,
1916 inputTarget->scaleFactor, inputTarget->pointerIds.value);
1917#endif
1918
1919 // Skip this event if the connection status is not normal.
1920 // We don't want to enqueue additional outbound events if the connection is broken.
1921 if (connection->status != Connection::STATUS_NORMAL) {
1922#if DEBUG_DISPATCH_CYCLE
1923 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001924 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925#endif
1926 return;
1927 }
1928
1929 // Split a motion event if needed.
1930 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1931 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1932
1933 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1934 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1935 MotionEntry* splitMotionEntry = splitMotionEvent(
1936 originalMotionEntry, inputTarget->pointerIds);
1937 if (!splitMotionEntry) {
1938 return; // split event was dropped
1939 }
1940#if DEBUG_FOCUS
1941 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001942 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1944#endif
1945 enqueueDispatchEntriesLocked(currentTime, connection,
1946 splitMotionEntry, inputTarget);
1947 splitMotionEntry->release();
1948 return;
1949 }
1950 }
1951
1952 // Not splitting. Enqueue dispatch entries for the event as is.
1953 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1954}
1955
1956void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1957 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1958 bool wasEmpty = connection->outboundQueue.isEmpty();
1959
1960 // Enqueue dispatch entries for the requested modes.
1961 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1962 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1963 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1964 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1965 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1966 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1967 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1968 InputTarget::FLAG_DISPATCH_AS_IS);
1969 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1970 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1971 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1972 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1973
1974 // If the outbound queue was previously empty, start the dispatch cycle going.
1975 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1976 startDispatchCycleLocked(currentTime, connection);
1977 }
1978}
1979
1980void InputDispatcher::enqueueDispatchEntryLocked(
1981 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1982 int32_t dispatchMode) {
1983 int32_t inputTargetFlags = inputTarget->flags;
1984 if (!(inputTargetFlags & dispatchMode)) {
1985 return;
1986 }
1987 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1988
1989 // This is a new event.
1990 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1991 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1992 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
1993 inputTarget->scaleFactor);
1994
1995 // Apply target flags and update the connection's input state.
1996 switch (eventEntry->type) {
1997 case EventEntry::TYPE_KEY: {
1998 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
1999 dispatchEntry->resolvedAction = keyEntry->action;
2000 dispatchEntry->resolvedFlags = keyEntry->flags;
2001
2002 if (!connection->inputState.trackKey(keyEntry,
2003 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2004#if DEBUG_DISPATCH_CYCLE
2005 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002006 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007#endif
2008 delete dispatchEntry;
2009 return; // skip the inconsistent event
2010 }
2011 break;
2012 }
2013
2014 case EventEntry::TYPE_MOTION: {
2015 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2016 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2017 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2018 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2019 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2020 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2021 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2022 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2023 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2024 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2025 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2026 } else {
2027 dispatchEntry->resolvedAction = motionEntry->action;
2028 }
2029 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2030 && !connection->inputState.isHovering(
2031 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2032#if DEBUG_DISPATCH_CYCLE
2033 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002034 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035#endif
2036 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2037 }
2038
2039 dispatchEntry->resolvedFlags = motionEntry->flags;
2040 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2041 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2042 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002043 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2044 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2045 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002046
2047 if (!connection->inputState.trackMotion(motionEntry,
2048 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2049#if DEBUG_DISPATCH_CYCLE
2050 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002051 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052#endif
2053 delete dispatchEntry;
2054 return; // skip the inconsistent event
2055 }
2056 break;
2057 }
2058 }
2059
2060 // Remember that we are waiting for this dispatch to complete.
2061 if (dispatchEntry->hasForegroundTarget()) {
2062 incrementPendingForegroundDispatchesLocked(eventEntry);
2063 }
2064
2065 // Enqueue the dispatch entry.
2066 connection->outboundQueue.enqueueAtTail(dispatchEntry);
2067 traceOutboundQueueLengthLocked(connection);
2068}
2069
2070void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2071 const sp<Connection>& connection) {
2072#if DEBUG_DISPATCH_CYCLE
2073 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002074 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075#endif
2076
2077 while (connection->status == Connection::STATUS_NORMAL
2078 && !connection->outboundQueue.isEmpty()) {
2079 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2080 dispatchEntry->deliveryTime = currentTime;
2081
2082 // Publish the event.
2083 status_t status;
2084 EventEntry* eventEntry = dispatchEntry->eventEntry;
2085 switch (eventEntry->type) {
2086 case EventEntry::TYPE_KEY: {
2087 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2088
2089 // Publish the key event.
2090 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002091 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2093 keyEntry->keyCode, keyEntry->scanCode,
2094 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2095 keyEntry->eventTime);
2096 break;
2097 }
2098
2099 case EventEntry::TYPE_MOTION: {
2100 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2101
2102 PointerCoords scaledCoords[MAX_POINTERS];
2103 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2104
2105 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002106 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2108 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002109 float scaleFactor = dispatchEntry->scaleFactor;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 xOffset = dispatchEntry->xOffset * scaleFactor;
2111 yOffset = dispatchEntry->yOffset * scaleFactor;
2112 if (scaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002113 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002114 scaledCoords[i] = motionEntry->pointerCoords[i];
2115 scaledCoords[i].scale(scaleFactor);
2116 }
2117 usingCoords = scaledCoords;
2118 }
2119 } else {
2120 xOffset = 0.0f;
2121 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122
2123 // We don't want the dispatch target to know.
2124 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002125 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 scaledCoords[i].clear();
2127 }
2128 usingCoords = scaledCoords;
2129 }
2130 }
2131
2132 // Publish the motion event.
2133 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002134 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002135 dispatchEntry->resolvedAction, motionEntry->actionButton,
2136 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2137 motionEntry->metaState, motionEntry->buttonState,
2138 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139 motionEntry->downTime, motionEntry->eventTime,
2140 motionEntry->pointerCount, motionEntry->pointerProperties,
2141 usingCoords);
2142 break;
2143 }
2144
2145 default:
2146 ALOG_ASSERT(false);
2147 return;
2148 }
2149
2150 // Check the result.
2151 if (status) {
2152 if (status == WOULD_BLOCK) {
2153 if (connection->waitQueue.isEmpty()) {
2154 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2155 "This is unexpected because the wait queue is empty, so the pipe "
2156 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002157 "event to it, status=%d", connection->getInputChannelName().c_str(),
2158 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2160 } else {
2161 // Pipe is full and we are waiting for the app to finish process some events
2162 // before sending more events to it.
2163#if DEBUG_DISPATCH_CYCLE
2164 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2165 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002166 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167#endif
2168 connection->inputPublisherBlocked = true;
2169 }
2170 } else {
2171 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002172 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2174 }
2175 return;
2176 }
2177
2178 // Re-enqueue the event on the wait queue.
2179 connection->outboundQueue.dequeue(dispatchEntry);
2180 traceOutboundQueueLengthLocked(connection);
2181 connection->waitQueue.enqueueAtTail(dispatchEntry);
2182 traceWaitQueueLengthLocked(connection);
2183 }
2184}
2185
2186void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2187 const sp<Connection>& connection, uint32_t seq, bool handled) {
2188#if DEBUG_DISPATCH_CYCLE
2189 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002190 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191#endif
2192
2193 connection->inputPublisherBlocked = false;
2194
2195 if (connection->status == Connection::STATUS_BROKEN
2196 || connection->status == Connection::STATUS_ZOMBIE) {
2197 return;
2198 }
2199
2200 // Notify other system components and prepare to start the next dispatch cycle.
2201 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2202}
2203
2204void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2205 const sp<Connection>& connection, bool notify) {
2206#if DEBUG_DISPATCH_CYCLE
2207 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002208 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209#endif
2210
2211 // Clear the dispatch queues.
2212 drainDispatchQueueLocked(&connection->outboundQueue);
2213 traceOutboundQueueLengthLocked(connection);
2214 drainDispatchQueueLocked(&connection->waitQueue);
2215 traceWaitQueueLengthLocked(connection);
2216
2217 // The connection appears to be unrecoverably broken.
2218 // Ignore already broken or zombie connections.
2219 if (connection->status == Connection::STATUS_NORMAL) {
2220 connection->status = Connection::STATUS_BROKEN;
2221
2222 if (notify) {
2223 // Notify other system components.
2224 onDispatchCycleBrokenLocked(currentTime, connection);
2225 }
2226 }
2227}
2228
2229void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2230 while (!queue->isEmpty()) {
2231 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2232 releaseDispatchEntryLocked(dispatchEntry);
2233 }
2234}
2235
2236void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2237 if (dispatchEntry->hasForegroundTarget()) {
2238 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2239 }
2240 delete dispatchEntry;
2241}
2242
2243int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2244 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2245
2246 { // acquire lock
2247 AutoMutex _l(d->mLock);
2248
2249 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2250 if (connectionIndex < 0) {
2251 ALOGE("Received spurious receive callback for unknown input channel. "
2252 "fd=%d, events=0x%x", fd, events);
2253 return 0; // remove the callback
2254 }
2255
2256 bool notify;
2257 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2258 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2259 if (!(events & ALOOPER_EVENT_INPUT)) {
2260 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002261 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262 return 1;
2263 }
2264
2265 nsecs_t currentTime = now();
2266 bool gotOne = false;
2267 status_t status;
2268 for (;;) {
2269 uint32_t seq;
2270 bool handled;
2271 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2272 if (status) {
2273 break;
2274 }
2275 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2276 gotOne = true;
2277 }
2278 if (gotOne) {
2279 d->runCommandsLockedInterruptible();
2280 if (status == WOULD_BLOCK) {
2281 return 1;
2282 }
2283 }
2284
2285 notify = status != DEAD_OBJECT || !connection->monitor;
2286 if (notify) {
2287 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002288 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 }
2290 } else {
2291 // Monitor channels are never explicitly unregistered.
2292 // We do it automatically when the remote endpoint is closed so don't warn
2293 // about them.
2294 notify = !connection->monitor;
2295 if (notify) {
2296 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002297 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 }
2299 }
2300
2301 // Unregister the channel.
2302 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2303 return 0; // remove the callback
2304 } // release lock
2305}
2306
2307void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2308 const CancelationOptions& options) {
2309 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2310 synthesizeCancelationEventsForConnectionLocked(
2311 mConnectionsByFd.valueAt(i), options);
2312 }
2313}
2314
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002315void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2316 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002317 for (auto& it : mMonitoringChannelsByDisplay) {
2318 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
2319 const size_t numChannels = monitoringChannels.size();
2320 for (size_t i = 0; i < numChannels; i++) {
2321 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2322 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002323 }
2324}
2325
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2327 const sp<InputChannel>& channel, const CancelationOptions& options) {
2328 ssize_t index = getConnectionIndexLocked(channel);
2329 if (index >= 0) {
2330 synthesizeCancelationEventsForConnectionLocked(
2331 mConnectionsByFd.valueAt(index), options);
2332 }
2333}
2334
2335void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2336 const sp<Connection>& connection, const CancelationOptions& options) {
2337 if (connection->status == Connection::STATUS_BROKEN) {
2338 return;
2339 }
2340
2341 nsecs_t currentTime = now();
2342
2343 Vector<EventEntry*> cancelationEvents;
2344 connection->inputState.synthesizeCancelationEvents(currentTime,
2345 cancelationEvents, options);
2346
2347 if (!cancelationEvents.isEmpty()) {
2348#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002349 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002351 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 options.reason, options.mode);
2353#endif
2354 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2355 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2356 switch (cancelationEventEntry->type) {
2357 case EventEntry::TYPE_KEY:
2358 logOutboundKeyDetailsLocked("cancel - ",
2359 static_cast<KeyEntry*>(cancelationEventEntry));
2360 break;
2361 case EventEntry::TYPE_MOTION:
2362 logOutboundMotionDetailsLocked("cancel - ",
2363 static_cast<MotionEntry*>(cancelationEventEntry));
2364 break;
2365 }
2366
2367 InputTarget target;
2368 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07002369 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2371 target.xOffset = -windowInfo->frameLeft;
2372 target.yOffset = -windowInfo->frameTop;
2373 target.scaleFactor = windowInfo->scaleFactor;
2374 } else {
2375 target.xOffset = 0;
2376 target.yOffset = 0;
2377 target.scaleFactor = 1.0f;
2378 }
2379 target.inputChannel = connection->inputChannel;
2380 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2381
2382 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2383 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2384
2385 cancelationEventEntry->release();
2386 }
2387
2388 startDispatchCycleLocked(currentTime, connection);
2389 }
2390}
2391
2392InputDispatcher::MotionEntry*
2393InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2394 ALOG_ASSERT(pointerIds.value != 0);
2395
2396 uint32_t splitPointerIndexMap[MAX_POINTERS];
2397 PointerProperties splitPointerProperties[MAX_POINTERS];
2398 PointerCoords splitPointerCoords[MAX_POINTERS];
2399
2400 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2401 uint32_t splitPointerCount = 0;
2402
2403 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2404 originalPointerIndex++) {
2405 const PointerProperties& pointerProperties =
2406 originalMotionEntry->pointerProperties[originalPointerIndex];
2407 uint32_t pointerId = uint32_t(pointerProperties.id);
2408 if (pointerIds.hasBit(pointerId)) {
2409 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2410 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2411 splitPointerCoords[splitPointerCount].copyFrom(
2412 originalMotionEntry->pointerCoords[originalPointerIndex]);
2413 splitPointerCount += 1;
2414 }
2415 }
2416
2417 if (splitPointerCount != pointerIds.count()) {
2418 // This is bad. We are missing some of the pointers that we expected to deliver.
2419 // Most likely this indicates that we received an ACTION_MOVE events that has
2420 // different pointer ids than we expected based on the previous ACTION_DOWN
2421 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2422 // in this way.
2423 ALOGW("Dropping split motion event because the pointer count is %d but "
2424 "we expected there to be %d pointers. This probably means we received "
2425 "a broken sequence of pointer ids from the input device.",
2426 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002427 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428 }
2429
2430 int32_t action = originalMotionEntry->action;
2431 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2432 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2433 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2434 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2435 const PointerProperties& pointerProperties =
2436 originalMotionEntry->pointerProperties[originalPointerIndex];
2437 uint32_t pointerId = uint32_t(pointerProperties.id);
2438 if (pointerIds.hasBit(pointerId)) {
2439 if (pointerIds.count() == 1) {
2440 // The first/last pointer went down/up.
2441 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2442 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2443 } else {
2444 // A secondary pointer went down/up.
2445 uint32_t splitPointerIndex = 0;
2446 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2447 splitPointerIndex += 1;
2448 }
2449 action = maskedAction | (splitPointerIndex
2450 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2451 }
2452 } else {
2453 // An unrelated pointer changed.
2454 action = AMOTION_EVENT_ACTION_MOVE;
2455 }
2456 }
2457
2458 MotionEntry* splitMotionEntry = new MotionEntry(
2459 originalMotionEntry->eventTime,
2460 originalMotionEntry->deviceId,
2461 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002462 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 originalMotionEntry->policyFlags,
2464 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002465 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 originalMotionEntry->flags,
2467 originalMotionEntry->metaState,
2468 originalMotionEntry->buttonState,
2469 originalMotionEntry->edgeFlags,
2470 originalMotionEntry->xPrecision,
2471 originalMotionEntry->yPrecision,
2472 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002473 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474
2475 if (originalMotionEntry->injectionState) {
2476 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2477 splitMotionEntry->injectionState->refCount += 1;
2478 }
2479
2480 return splitMotionEntry;
2481}
2482
2483void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2484#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002485 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486#endif
2487
2488 bool needWake;
2489 { // acquire lock
2490 AutoMutex _l(mLock);
2491
2492 ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
2493 needWake = enqueueInboundEventLocked(newEntry);
2494 } // release lock
2495
2496 if (needWake) {
2497 mLooper->wake();
2498 }
2499}
2500
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002501/**
2502 * If one of the meta shortcuts is detected, process them here:
2503 * Meta + Backspace -> generate BACK
2504 * Meta + Enter -> generate HOME
2505 * This will potentially overwrite keyCode and metaState.
2506 */
2507void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2508 int32_t& keyCode, int32_t& metaState) {
2509 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2510 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2511 if (keyCode == AKEYCODE_DEL) {
2512 newKeyCode = AKEYCODE_BACK;
2513 } else if (keyCode == AKEYCODE_ENTER) {
2514 newKeyCode = AKEYCODE_HOME;
2515 }
2516 if (newKeyCode != AKEYCODE_UNKNOWN) {
2517 AutoMutex _l(mLock);
2518 struct KeyReplacement replacement = {keyCode, deviceId};
2519 mReplacedKeys.add(replacement, newKeyCode);
2520 keyCode = newKeyCode;
2521 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2522 }
2523 } else if (action == AKEY_EVENT_ACTION_UP) {
2524 // In order to maintain a consistent stream of up and down events, check to see if the key
2525 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2526 // even if the modifier was released between the down and the up events.
2527 AutoMutex _l(mLock);
2528 struct KeyReplacement replacement = {keyCode, deviceId};
2529 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2530 if (index >= 0) {
2531 keyCode = mReplacedKeys.valueAt(index);
2532 mReplacedKeys.removeItemsAt(index);
2533 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2534 }
2535 }
2536}
2537
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2539#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002540 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002541 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002542 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002543 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002544 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002545 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546#endif
2547 if (!validateKeyEvent(args->action)) {
2548 return;
2549 }
2550
2551 uint32_t policyFlags = args->policyFlags;
2552 int32_t flags = args->flags;
2553 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002554 // InputDispatcher tracks and generates key repeats on behalf of
2555 // whatever notifies it, so repeatCount should always be set to 0
2556 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2558 policyFlags |= POLICY_FLAG_VIRTUAL;
2559 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2560 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 if (policyFlags & POLICY_FLAG_FUNCTION) {
2562 metaState |= AMETA_FUNCTION_ON;
2563 }
2564
2565 policyFlags |= POLICY_FLAG_TRUSTED;
2566
Michael Wright78f24442014-08-06 15:55:28 -07002567 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002568 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002569
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002571 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002572 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 args->downTime, args->eventTime);
2574
Michael Wright2b3c3302018-03-02 17:19:13 +00002575 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002577 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2578 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2579 std::to_string(t.duration().count()).c_str());
2580 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 bool needWake;
2583 { // acquire lock
2584 mLock.lock();
2585
2586 if (shouldSendKeyToInputFilterLocked(args)) {
2587 mLock.unlock();
2588
2589 policyFlags |= POLICY_FLAG_FILTERED;
2590 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2591 return; // event was consumed by the filter
2592 }
2593
2594 mLock.lock();
2595 }
2596
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 KeyEntry* newEntry = new KeyEntry(args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002598 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002599 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 metaState, repeatCount, args->downTime);
2601
2602 needWake = enqueueInboundEventLocked(newEntry);
2603 mLock.unlock();
2604 } // release lock
2605
2606 if (needWake) {
2607 mLooper->wake();
2608 }
2609}
2610
2611bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2612 return mInputFilterEnabled;
2613}
2614
2615void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2616#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002617 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2618 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002619 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002620 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2621 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002622 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002623 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624 for (uint32_t i = 0; i < args->pointerCount; i++) {
2625 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2626 "x=%f, y=%f, pressure=%f, size=%f, "
2627 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2628 "orientation=%f",
2629 i, args->pointerProperties[i].id,
2630 args->pointerProperties[i].toolType,
2631 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2632 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2633 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2634 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2635 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2636 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2637 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2638 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2639 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2640 }
2641#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002642 if (!validateMotionEvent(args->action, args->actionButton,
2643 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002644 return;
2645 }
2646
2647 uint32_t policyFlags = args->policyFlags;
2648 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002649
2650 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002652 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2653 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2654 std::to_string(t.duration().count()).c_str());
2655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656
2657 bool needWake;
2658 { // acquire lock
2659 mLock.lock();
2660
2661 if (shouldSendMotionToInputFilterLocked(args)) {
2662 mLock.unlock();
2663
2664 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002665 event.initialize(args->deviceId, args->source, args->displayId,
2666 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002667 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2668 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 args->downTime, args->eventTime,
2670 args->pointerCount, args->pointerProperties, args->pointerCoords);
2671
2672 policyFlags |= POLICY_FLAG_FILTERED;
2673 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2674 return; // event was consumed by the filter
2675 }
2676
2677 mLock.lock();
2678 }
2679
2680 // Just enqueue a new motion event.
2681 MotionEntry* newEntry = new MotionEntry(args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002682 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002683 args->action, args->actionButton, args->flags,
2684 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002686 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687
2688 needWake = enqueueInboundEventLocked(newEntry);
2689 mLock.unlock();
2690 } // release lock
2691
2692 if (needWake) {
2693 mLooper->wake();
2694 }
2695}
2696
2697bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2698 // TODO: support sending secondary display events to input filter
2699 return mInputFilterEnabled && isMainDisplay(args->displayId);
2700}
2701
2702void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2703#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002704 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2705 "switchMask=0x%08x",
2706 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707#endif
2708
2709 uint32_t policyFlags = args->policyFlags;
2710 policyFlags |= POLICY_FLAG_TRUSTED;
2711 mPolicy->notifySwitch(args->eventTime,
2712 args->switchValues, args->switchMask, policyFlags);
2713}
2714
2715void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2716#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002717 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718 args->eventTime, args->deviceId);
2719#endif
2720
2721 bool needWake;
2722 { // acquire lock
2723 AutoMutex _l(mLock);
2724
2725 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2726 needWake = enqueueInboundEventLocked(newEntry);
2727 } // release lock
2728
2729 if (needWake) {
2730 mLooper->wake();
2731 }
2732}
2733
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002734int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2736 uint32_t policyFlags) {
2737#if DEBUG_INBOUND_EVENT_DETAILS
2738 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002739 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2740 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741#endif
2742
2743 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2744
2745 policyFlags |= POLICY_FLAG_INJECTED;
2746 if (hasInjectionPermission(injectorPid, injectorUid)) {
2747 policyFlags |= POLICY_FLAG_TRUSTED;
2748 }
2749
2750 EventEntry* firstInjectedEntry;
2751 EventEntry* lastInjectedEntry;
2752 switch (event->getType()) {
2753 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002754 KeyEvent keyEvent;
2755 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2756 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 if (! validateKeyEvent(action)) {
2758 return INPUT_EVENT_INJECTION_FAILED;
2759 }
2760
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002761 int32_t flags = keyEvent.getFlags();
2762 int32_t keyCode = keyEvent.getKeyCode();
2763 int32_t metaState = keyEvent.getMetaState();
2764 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2765 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002766 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002767 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002768 keyEvent.getDownTime(), keyEvent.getEventTime());
2769
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2771 policyFlags |= POLICY_FLAG_VIRTUAL;
2772 }
2773
2774 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002775 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002776 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002777 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2778 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2779 std::to_string(t.duration().count()).c_str());
2780 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781 }
2782
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783 mLock.lock();
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002784 firstInjectedEntry = new KeyEntry(keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002785 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002787 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2788 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789 lastInjectedEntry = firstInjectedEntry;
2790 break;
2791 }
2792
2793 case AINPUT_EVENT_TYPE_MOTION: {
2794 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 int32_t action = motionEvent->getAction();
2796 size_t pointerCount = motionEvent->getPointerCount();
2797 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002798 int32_t actionButton = motionEvent->getActionButton();
2799 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800 return INPUT_EVENT_INJECTION_FAILED;
2801 }
2802
2803 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2804 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002805 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002807 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2808 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2809 std::to_string(t.duration().count()).c_str());
2810 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811 }
2812
2813 mLock.lock();
2814 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2815 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2816 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002817 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2818 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002819 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 motionEvent->getMetaState(), motionEvent->getButtonState(),
2821 motionEvent->getEdgeFlags(),
2822 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002823 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002824 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2825 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 lastInjectedEntry = firstInjectedEntry;
2827 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2828 sampleEventTimes += 1;
2829 samplePointerCoords += pointerCount;
2830 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002831 motionEvent->getDeviceId(), motionEvent->getSource(),
2832 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002833 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 motionEvent->getMetaState(), motionEvent->getButtonState(),
2835 motionEvent->getEdgeFlags(),
2836 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002837 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002838 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2839 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840 lastInjectedEntry->next = nextInjectedEntry;
2841 lastInjectedEntry = nextInjectedEntry;
2842 }
2843 break;
2844 }
2845
2846 default:
2847 ALOGW("Cannot inject event of type %d", event->getType());
2848 return INPUT_EVENT_INJECTION_FAILED;
2849 }
2850
2851 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2852 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2853 injectionState->injectionIsAsync = true;
2854 }
2855
2856 injectionState->refCount += 1;
2857 lastInjectedEntry->injectionState = injectionState;
2858
2859 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002860 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 EventEntry* nextEntry = entry->next;
2862 needWake |= enqueueInboundEventLocked(entry);
2863 entry = nextEntry;
2864 }
2865
2866 mLock.unlock();
2867
2868 if (needWake) {
2869 mLooper->wake();
2870 }
2871
2872 int32_t injectionResult;
2873 { // acquire lock
2874 AutoMutex _l(mLock);
2875
2876 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2877 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2878 } else {
2879 for (;;) {
2880 injectionResult = injectionState->injectionResult;
2881 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2882 break;
2883 }
2884
2885 nsecs_t remainingTimeout = endTime - now();
2886 if (remainingTimeout <= 0) {
2887#if DEBUG_INJECTION
2888 ALOGD("injectInputEvent - Timed out waiting for injection result "
2889 "to become available.");
2890#endif
2891 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2892 break;
2893 }
2894
2895 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2896 }
2897
2898 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2899 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2900 while (injectionState->pendingForegroundDispatches != 0) {
2901#if DEBUG_INJECTION
2902 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2903 injectionState->pendingForegroundDispatches);
2904#endif
2905 nsecs_t remainingTimeout = endTime - now();
2906 if (remainingTimeout <= 0) {
2907#if DEBUG_INJECTION
2908 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2909 "dispatches to finish.");
2910#endif
2911 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2912 break;
2913 }
2914
2915 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2916 }
2917 }
2918 }
2919
2920 injectionState->release();
2921 } // release lock
2922
2923#if DEBUG_INJECTION
2924 ALOGD("injectInputEvent - Finished with result %d. "
2925 "injectorPid=%d, injectorUid=%d",
2926 injectionResult, injectorPid, injectorUid);
2927#endif
2928
2929 return injectionResult;
2930}
2931
2932bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2933 return injectorUid == 0
2934 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2935}
2936
2937void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2938 InjectionState* injectionState = entry->injectionState;
2939 if (injectionState) {
2940#if DEBUG_INJECTION
2941 ALOGD("Setting input event injection result to %d. "
2942 "injectorPid=%d, injectorUid=%d",
2943 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2944#endif
2945
2946 if (injectionState->injectionIsAsync
2947 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2948 // Log the outcome since the injector did not wait for the injection result.
2949 switch (injectionResult) {
2950 case INPUT_EVENT_INJECTION_SUCCEEDED:
2951 ALOGV("Asynchronous input event injection succeeded.");
2952 break;
2953 case INPUT_EVENT_INJECTION_FAILED:
2954 ALOGW("Asynchronous input event injection failed.");
2955 break;
2956 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2957 ALOGW("Asynchronous input event injection permission denied.");
2958 break;
2959 case INPUT_EVENT_INJECTION_TIMED_OUT:
2960 ALOGW("Asynchronous input event injection timed out.");
2961 break;
2962 }
2963 }
2964
2965 injectionState->injectionResult = injectionResult;
2966 mInjectionResultAvailableCondition.broadcast();
2967 }
2968}
2969
2970void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2971 InjectionState* injectionState = entry->injectionState;
2972 if (injectionState) {
2973 injectionState->pendingForegroundDispatches += 1;
2974 }
2975}
2976
2977void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2978 InjectionState* injectionState = entry->injectionState;
2979 if (injectionState) {
2980 injectionState->pendingForegroundDispatches -= 1;
2981
2982 if (injectionState->pendingForegroundDispatches == 0) {
2983 mInjectionSyncFinishedCondition.broadcast();
2984 }
2985 }
2986}
2987
Arthur Hungb92218b2018-08-14 12:00:21 +08002988Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
2989 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
2990 mWindowHandlesByDisplay.find(displayId);
2991 if(it != mWindowHandlesByDisplay.end()) {
2992 return it->second;
2993 }
2994
2995 // Return an empty one if nothing found.
2996 return Vector<sp<InputWindowHandle>>();
2997}
2998
Michael Wrightd02c5b62014-02-10 15:10:22 -08002999sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3000 const sp<InputChannel>& inputChannel) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003001 for (auto& it : mWindowHandlesByDisplay) {
3002 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3003 size_t numWindows = windowHandles.size();
3004 for (size_t i = 0; i < numWindows; i++) {
3005 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3006 if (windowHandle->getInputChannel() == inputChannel) {
3007 return windowHandle;
3008 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003009 }
3010 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003011 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012}
3013
3014bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003015 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003016 for (auto& it : mWindowHandlesByDisplay) {
3017 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3018 size_t numWindows = windowHandles.size();
3019 for (size_t i = 0; i < numWindows; i++) {
3020 if (windowHandles.itemAt(i) == windowHandle) {
3021 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003022 ALOGE("Found window %s in display %" PRId32
3023 ", but it should belong to display %" PRId32,
3024 windowHandle->getName().c_str(), it.first,
3025 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003026 }
3027 return true;
3028 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 }
3030 }
3031 return false;
3032}
3033
Arthur Hungb92218b2018-08-14 12:00:21 +08003034/**
3035 * Called from InputManagerService, update window handle list by displayId that can receive input.
3036 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3037 * If set an empty list, remove all handles from the specific display.
3038 * For focused handle, check if need to change and send a cancel event to previous one.
3039 * For removed handle, check if need to send a cancel event if already in touch.
3040 */
3041void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3042 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003043#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003044 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003045#endif
3046 { // acquire lock
3047 AutoMutex _l(mLock);
3048
Arthur Hungb92218b2018-08-14 12:00:21 +08003049 // Copy old handles for release if they are no longer present.
3050 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003051
Tiger Huang721e26f2018-07-24 22:26:19 +08003052 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003053 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003054
3055 if (inputWindowHandles.isEmpty()) {
3056 // Remove all handles on a display if there are no windows left.
3057 mWindowHandlesByDisplay.erase(displayId);
3058 } else {
3059 size_t numWindows = inputWindowHandles.size();
3060 for (size_t i = 0; i < numWindows; i++) {
3061 const sp<InputWindowHandle>& windowHandle = inputWindowHandles.itemAt(i);
3062 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == nullptr) {
3063 continue;
3064 }
3065
3066 if (windowHandle->getInfo()->displayId != displayId) {
3067 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3068 windowHandle->getName().c_str(), displayId,
3069 windowHandle->getInfo()->displayId);
3070 continue;
3071 }
3072
3073 if (windowHandle->getInfo()->hasFocus) {
3074 newFocusedWindowHandle = windowHandle;
3075 }
3076 if (windowHandle == mLastHoverWindowHandle) {
3077 foundHoveredWindow = true;
3078 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003079 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003080
3081 // Insert or replace
3082 mWindowHandlesByDisplay[displayId] = inputWindowHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003083 }
3084
3085 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003086 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087 }
3088
Tiger Huang721e26f2018-07-24 22:26:19 +08003089 sp<InputWindowHandle> oldFocusedWindowHandle =
3090 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3091
3092 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3093 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003095 ALOGD("Focus left window: %s in display %" PRId32,
3096 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003098 sp<InputChannel> focusedInputChannel = oldFocusedWindowHandle->getInputChannel();
Yi Kong9b14ac62018-07-17 13:48:38 -07003099 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3101 "focus left window");
3102 synthesizeCancelationEventsForInputChannelLocked(
3103 focusedInputChannel, options);
3104 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003105 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003107 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003108#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003109 ALOGD("Focus entered window: %s in display %" PRId32,
3110 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003112 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003113 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114 }
3115
Arthur Hungb92218b2018-08-14 12:00:21 +08003116 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3117 if (stateIndex >= 0) {
3118 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003119 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003120 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003121 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003123 ALOGD("Touched window was removed: %s in display %" PRId32,
3124 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003126 sp<InputChannel> touchedInputChannel =
3127 touchedWindow.windowHandle->getInputChannel();
Yi Kong9b14ac62018-07-17 13:48:38 -07003128 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003129 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3130 "touched window was removed");
3131 synthesizeCancelationEventsForInputChannelLocked(
3132 touchedInputChannel, options);
3133 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003134 state.windows.removeAt(i);
3135 } else {
3136 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003137 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 }
3139 }
3140
3141 // Release information for windows that are no longer present.
3142 // This ensures that unused input channels are released promptly.
3143 // Otherwise, they might stick around until the window handle is destroyed
3144 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003145 size_t numWindows = oldWindowHandles.size();
3146 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003148 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003150 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003152 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003153 }
3154 }
3155 } // release lock
3156
3157 // Wake up poll loop since it may need to make new input dispatching choices.
3158 mLooper->wake();
3159}
3160
3161void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003162 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003164 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165#endif
3166 { // acquire lock
3167 AutoMutex _l(mLock);
3168
Tiger Huang721e26f2018-07-24 22:26:19 +08003169 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3170 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003171 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003172 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3173 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003175 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003177 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003179 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003181 oldFocusedApplicationHandle->releaseInfo();
3182 oldFocusedApplicationHandle.clear();
3183 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 }
3185
3186#if DEBUG_FOCUS
3187 //logDispatchStateLocked();
3188#endif
3189 } // release lock
3190
3191 // Wake up poll loop since it may need to make new input dispatching choices.
3192 mLooper->wake();
3193}
3194
Tiger Huang721e26f2018-07-24 22:26:19 +08003195/**
3196 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3197 * the display not specified.
3198 *
3199 * We track any unreleased events for each window. If a window loses the ability to receive the
3200 * released event, we will send a cancel event to it. So when the focused display is changed, we
3201 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3202 * display. The display-specified events won't be affected.
3203 */
3204void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3205#if DEBUG_FOCUS
3206 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3207#endif
3208 { // acquire lock
3209 AutoMutex _l(mLock);
3210
3211 if (mFocusedDisplayId != displayId) {
3212 sp<InputWindowHandle> oldFocusedWindowHandle =
3213 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3214 if (oldFocusedWindowHandle != nullptr) {
3215 sp<InputChannel> inputChannel = oldFocusedWindowHandle->getInputChannel();
3216 if (inputChannel != nullptr) {
3217 CancelationOptions options(
3218 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3219 "The display which contains this window no longer has focus.");
3220 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3221 }
3222 }
3223 mFocusedDisplayId = displayId;
3224
3225 // Sanity check
3226 sp<InputWindowHandle> newFocusedWindowHandle =
3227 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3228 if (newFocusedWindowHandle == nullptr) {
3229 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3230 if (!mFocusedWindowHandlesByDisplay.empty()) {
3231 ALOGE("But another display has a focused window:");
3232 for (auto& it : mFocusedWindowHandlesByDisplay) {
3233 const int32_t displayId = it.first;
3234 const sp<InputWindowHandle>& windowHandle = it.second;
3235 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3236 displayId, windowHandle->getName().c_str());
3237 }
3238 }
3239 }
3240 }
3241
3242#if DEBUG_FOCUS
3243 logDispatchStateLocked();
3244#endif
3245 } // release lock
3246
3247 // Wake up poll loop since it may need to make new input dispatching choices.
3248 mLooper->wake();
3249}
3250
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3252#if DEBUG_FOCUS
3253 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3254#endif
3255
3256 bool changed;
3257 { // acquire lock
3258 AutoMutex _l(mLock);
3259
3260 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3261 if (mDispatchFrozen && !frozen) {
3262 resetANRTimeoutsLocked();
3263 }
3264
3265 if (mDispatchEnabled && !enabled) {
3266 resetAndDropEverythingLocked("dispatcher is being disabled");
3267 }
3268
3269 mDispatchEnabled = enabled;
3270 mDispatchFrozen = frozen;
3271 changed = true;
3272 } else {
3273 changed = false;
3274 }
3275
3276#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003277 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278#endif
3279 } // release lock
3280
3281 if (changed) {
3282 // Wake up poll loop since it may need to make new input dispatching choices.
3283 mLooper->wake();
3284 }
3285}
3286
3287void InputDispatcher::setInputFilterEnabled(bool enabled) {
3288#if DEBUG_FOCUS
3289 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3290#endif
3291
3292 { // acquire lock
3293 AutoMutex _l(mLock);
3294
3295 if (mInputFilterEnabled == enabled) {
3296 return;
3297 }
3298
3299 mInputFilterEnabled = enabled;
3300 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3301 } // release lock
3302
3303 // Wake up poll loop since there might be work to do to drop everything.
3304 mLooper->wake();
3305}
3306
3307bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3308 const sp<InputChannel>& toChannel) {
3309#if DEBUG_FOCUS
3310 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003311 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312#endif
3313 { // acquire lock
3314 AutoMutex _l(mLock);
3315
3316 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3317 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07003318 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319#if DEBUG_FOCUS
3320 ALOGD("Cannot transfer focus because from or to window not found.");
3321#endif
3322 return false;
3323 }
3324 if (fromWindowHandle == toWindowHandle) {
3325#if DEBUG_FOCUS
3326 ALOGD("Trivial transfer to same window.");
3327#endif
3328 return true;
3329 }
3330 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3331#if DEBUG_FOCUS
3332 ALOGD("Cannot transfer focus because windows are on different displays.");
3333#endif
3334 return false;
3335 }
3336
3337 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003338 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3339 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3340 for (size_t i = 0; i < state.windows.size(); i++) {
3341 const TouchedWindow& touchedWindow = state.windows[i];
3342 if (touchedWindow.windowHandle == fromWindowHandle) {
3343 int32_t oldTargetFlags = touchedWindow.targetFlags;
3344 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345
Jeff Brownf086ddb2014-02-11 14:28:48 -08003346 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347
Jeff Brownf086ddb2014-02-11 14:28:48 -08003348 int32_t newTargetFlags = oldTargetFlags
3349 & (InputTarget::FLAG_FOREGROUND
3350 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3351 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352
Jeff Brownf086ddb2014-02-11 14:28:48 -08003353 found = true;
3354 goto Found;
3355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356 }
3357 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003358Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359
3360 if (! found) {
3361#if DEBUG_FOCUS
3362 ALOGD("Focus transfer failed because from window did not have focus.");
3363#endif
3364 return false;
3365 }
3366
3367 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3368 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3369 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3370 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3371 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3372
3373 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3374 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3375 "transferring touch focus from this window to another window");
3376 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3377 }
3378
3379#if DEBUG_FOCUS
3380 logDispatchStateLocked();
3381#endif
3382 } // release lock
3383
3384 // Wake up poll loop since it may need to make new input dispatching choices.
3385 mLooper->wake();
3386 return true;
3387}
3388
3389void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3390#if DEBUG_FOCUS
3391 ALOGD("Resetting and dropping all events (%s).", reason);
3392#endif
3393
3394 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3395 synthesizeCancelationEventsForAllConnectionsLocked(options);
3396
3397 resetKeyRepeatLocked();
3398 releasePendingEventLocked();
3399 drainInboundQueueLocked();
3400 resetANRTimeoutsLocked();
3401
Jeff Brownf086ddb2014-02-11 14:28:48 -08003402 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003404 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405}
3406
3407void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003408 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 dumpDispatchStateLocked(dump);
3410
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003411 std::istringstream stream(dump);
3412 std::string line;
3413
3414 while (std::getline(stream, line, '\n')) {
3415 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 }
3417}
3418
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003419void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3420 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3421 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003422 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423
Tiger Huang721e26f2018-07-24 22:26:19 +08003424 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3425 dump += StringPrintf(INDENT "FocusedApplications:\n");
3426 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3427 const int32_t displayId = it.first;
3428 const sp<InputApplicationHandle>& applicationHandle = it.second;
3429 dump += StringPrintf(
3430 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3431 displayId,
3432 applicationHandle->getName().c_str(),
3433 applicationHandle->getDispatchingTimeout(
3434 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003437 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003439
3440 if (!mFocusedWindowHandlesByDisplay.empty()) {
3441 dump += StringPrintf(INDENT "FocusedWindows:\n");
3442 for (auto& it : mFocusedWindowHandlesByDisplay) {
3443 const int32_t displayId = it.first;
3444 const sp<InputWindowHandle>& windowHandle = it.second;
3445 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3446 displayId, windowHandle->getName().c_str());
3447 }
3448 } else {
3449 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451
Jeff Brownf086ddb2014-02-11 14:28:48 -08003452 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003453 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003454 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3455 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003456 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003457 state.displayId, toString(state.down), toString(state.split),
3458 state.deviceId, state.source);
3459 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003460 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003461 for (size_t i = 0; i < state.windows.size(); i++) {
3462 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003463 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3464 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003465 touchedWindow.pointerIds.value,
3466 touchedWindow.targetFlags);
3467 }
3468 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003469 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003470 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 }
3472 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003473 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 }
3475
Arthur Hungb92218b2018-08-14 12:00:21 +08003476 if (!mWindowHandlesByDisplay.empty()) {
3477 for (auto& it : mWindowHandlesByDisplay) {
3478 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003479 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003480 if (!windowHandles.isEmpty()) {
3481 dump += INDENT2 "Windows:\n";
3482 for (size_t i = 0; i < windowHandles.size(); i++) {
3483 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3484 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485
Arthur Hungb92218b2018-08-14 12:00:21 +08003486 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3487 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3488 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3489 "frame=[%d,%d][%d,%d], scale=%f, "
3490 "touchableRegion=",
3491 i, windowInfo->name.c_str(), windowInfo->displayId,
3492 toString(windowInfo->paused),
3493 toString(windowInfo->hasFocus),
3494 toString(windowInfo->hasWallpaper),
3495 toString(windowInfo->visible),
3496 toString(windowInfo->canReceiveKeys),
3497 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3498 windowInfo->layer,
3499 windowInfo->frameLeft, windowInfo->frameTop,
3500 windowInfo->frameRight, windowInfo->frameBottom,
3501 windowInfo->scaleFactor);
3502 dumpRegion(dump, windowInfo->touchableRegion);
3503 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3504 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3505 windowInfo->ownerPid, windowInfo->ownerUid,
3506 windowInfo->dispatchingTimeout / 1000000.0);
3507 }
3508 } else {
3509 dump += INDENT2 "Windows: <none>\n";
3510 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 }
3512 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003513 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514 }
3515
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003516 if (!mMonitoringChannelsByDisplay.empty()) {
3517 for (auto& it : mMonitoringChannelsByDisplay) {
3518 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003519 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003520 const size_t numChannels = monitoringChannels.size();
3521 for (size_t i = 0; i < numChannels; i++) {
3522 const sp<InputChannel>& channel = monitoringChannels[i];
3523 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3524 }
3525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003527 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 }
3529
3530 nsecs_t currentTime = now();
3531
3532 // Dump recently dispatched or dropped events from oldest to newest.
3533 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003534 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003536 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003538 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 (currentTime - entry->eventTime) * 0.000001f);
3540 }
3541 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003542 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543 }
3544
3545 // Dump event currently being dispatched.
3546 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003547 dump += INDENT "PendingEvent:\n";
3548 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003550 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3552 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003553 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554 }
3555
3556 // Dump inbound events from oldest to newest.
3557 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003558 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003560 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003562 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563 (currentTime - entry->eventTime) * 0.000001f);
3564 }
3565 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003566 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 }
3568
Michael Wright78f24442014-08-06 15:55:28 -07003569 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003570 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003571 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3572 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3573 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003574 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003575 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3576 }
3577 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003578 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003579 }
3580
Michael Wrightd02c5b62014-02-10 15:10:22 -08003581 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003582 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3584 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003585 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003587 i, connection->getInputChannelName().c_str(),
3588 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003589 connection->getStatusLabel(), toString(connection->monitor),
3590 toString(connection->inputPublisherBlocked));
3591
3592 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003593 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 connection->outboundQueue.count());
3595 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3596 entry = entry->next) {
3597 dump.append(INDENT4);
3598 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003599 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 entry->targetFlags, entry->resolvedAction,
3601 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3602 }
3603 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003604 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 }
3606
3607 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003608 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 connection->waitQueue.count());
3610 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3611 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003612 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003614 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 "age=%0.1fms, wait=%0.1fms\n",
3616 entry->targetFlags, entry->resolvedAction,
3617 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3618 (currentTime - entry->deliveryTime) * 0.000001f);
3619 }
3620 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003621 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 }
3623 }
3624 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003625 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
3627
3628 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003629 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 (mAppSwitchDueTime - now()) / 1000000.0);
3631 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003632 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 }
3634
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003635 dump += INDENT "Configuration:\n";
3636 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003638 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003639 mConfig.keyRepeatTimeout * 0.000001f);
3640}
3641
3642status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003643 const sp<InputWindowHandle>& inputWindowHandle, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003645 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3646 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647#endif
3648
3649 { // acquire lock
3650 AutoMutex _l(mLock);
3651
3652 if (getConnectionIndexLocked(inputChannel) >= 0) {
3653 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003654 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655 return BAD_VALUE;
3656 }
3657
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003658 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3659 // treat inputChannel as monitor channel for displayId.
3660 bool monitor = inputWindowHandle == nullptr && displayId != ADISPLAY_ID_NONE;
3661
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3663
3664 int fd = inputChannel->getFd();
3665 mConnectionsByFd.add(fd, connection);
3666
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003667 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003669 Vector<sp<InputChannel>>& monitoringChannels =
3670 mMonitoringChannelsByDisplay[displayId];
3671 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 }
3673
3674 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3675 } // release lock
3676
3677 // Wake the looper because some connections have changed.
3678 mLooper->wake();
3679 return OK;
3680}
3681
3682status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3683#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003684 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685#endif
3686
3687 { // acquire lock
3688 AutoMutex _l(mLock);
3689
3690 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3691 if (status) {
3692 return status;
3693 }
3694 } // release lock
3695
3696 // Wake the poll loop because removing the connection may have changed the current
3697 // synchronization state.
3698 mLooper->wake();
3699 return OK;
3700}
3701
3702status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3703 bool notify) {
3704 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3705 if (connectionIndex < 0) {
3706 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003707 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 return BAD_VALUE;
3709 }
3710
3711 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3712 mConnectionsByFd.removeItemsAt(connectionIndex);
3713
3714 if (connection->monitor) {
3715 removeMonitorChannelLocked(inputChannel);
3716 }
3717
3718 mLooper->removeFd(inputChannel->getFd());
3719
3720 nsecs_t currentTime = now();
3721 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3722
3723 connection->status = Connection::STATUS_ZOMBIE;
3724 return OK;
3725}
3726
3727void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003728 for (auto it = mMonitoringChannelsByDisplay.begin();
3729 it != mMonitoringChannelsByDisplay.end(); ) {
3730 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3731 const size_t numChannels = monitoringChannels.size();
3732 for (size_t i = 0; i < numChannels; i++) {
3733 if (monitoringChannels[i] == inputChannel) {
3734 monitoringChannels.removeAt(i);
3735 break;
3736 }
3737 }
3738 if (monitoringChannels.empty()) {
3739 it = mMonitoringChannelsByDisplay.erase(it);
3740 } else {
3741 ++it;
3742 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 }
3744}
3745
3746ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003747 if (!inputChannel) {
3748 return -1;
3749 }
3750
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3752 if (connectionIndex >= 0) {
3753 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3754 if (connection->inputChannel.get() == inputChannel.get()) {
3755 return connectionIndex;
3756 }
3757 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 return -1;
3759}
3760
3761void InputDispatcher::onDispatchCycleFinishedLocked(
3762 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3763 CommandEntry* commandEntry = postCommandLocked(
3764 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3765 commandEntry->connection = connection;
3766 commandEntry->eventTime = currentTime;
3767 commandEntry->seq = seq;
3768 commandEntry->handled = handled;
3769}
3770
3771void InputDispatcher::onDispatchCycleBrokenLocked(
3772 nsecs_t currentTime, const sp<Connection>& connection) {
3773 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003774 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775
3776 CommandEntry* commandEntry = postCommandLocked(
3777 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3778 commandEntry->connection = connection;
3779}
3780
3781void InputDispatcher::onANRLocked(
3782 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3783 const sp<InputWindowHandle>& windowHandle,
3784 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3785 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3786 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3787 ALOGI("Application is not responding: %s. "
3788 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003789 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 dispatchLatency, waitDuration, reason);
3791
3792 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003793 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 struct tm tm;
3795 localtime_r(&t, &tm);
3796 char timestr[64];
3797 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3798 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003799 mLastANRState += INDENT "ANR:\n";
3800 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3801 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3802 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3803 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3804 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3805 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003806 dumpDispatchStateLocked(mLastANRState);
3807
3808 CommandEntry* commandEntry = postCommandLocked(
3809 & InputDispatcher::doNotifyANRLockedInterruptible);
3810 commandEntry->inputApplicationHandle = applicationHandle;
3811 commandEntry->inputWindowHandle = windowHandle;
3812 commandEntry->reason = reason;
3813}
3814
3815void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3816 CommandEntry* commandEntry) {
3817 mLock.unlock();
3818
3819 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3820
3821 mLock.lock();
3822}
3823
3824void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3825 CommandEntry* commandEntry) {
3826 sp<Connection> connection = commandEntry->connection;
3827
3828 if (connection->status != Connection::STATUS_ZOMBIE) {
3829 mLock.unlock();
3830
3831 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3832
3833 mLock.lock();
3834 }
3835}
3836
3837void InputDispatcher::doNotifyANRLockedInterruptible(
3838 CommandEntry* commandEntry) {
3839 mLock.unlock();
3840
3841 nsecs_t newTimeout = mPolicy->notifyANR(
3842 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3843 commandEntry->reason);
3844
3845 mLock.lock();
3846
3847 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Yi Kong9b14ac62018-07-17 13:48:38 -07003848 commandEntry->inputWindowHandle != nullptr
3849 ? commandEntry->inputWindowHandle->getInputChannel() : nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850}
3851
3852void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3853 CommandEntry* commandEntry) {
3854 KeyEntry* entry = commandEntry->keyEntry;
3855
3856 KeyEvent event;
3857 initializeKeyEvent(&event, entry);
3858
3859 mLock.unlock();
3860
Michael Wright2b3c3302018-03-02 17:19:13 +00003861 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3863 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003864 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3865 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3866 std::to_string(t.duration().count()).c_str());
3867 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003868
3869 mLock.lock();
3870
3871 if (delay < 0) {
3872 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3873 } else if (!delay) {
3874 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3875 } else {
3876 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3877 entry->interceptKeyWakeupTime = now() + delay;
3878 }
3879 entry->release();
3880}
3881
3882void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3883 CommandEntry* commandEntry) {
3884 sp<Connection> connection = commandEntry->connection;
3885 nsecs_t finishTime = commandEntry->eventTime;
3886 uint32_t seq = commandEntry->seq;
3887 bool handled = commandEntry->handled;
3888
3889 // Handle post-event policy actions.
3890 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3891 if (dispatchEntry) {
3892 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3893 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003894 std::string msg =
3895 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003896 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003898 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 }
3900
3901 bool restartEvent;
3902 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3903 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3904 restartEvent = afterKeyEventLockedInterruptible(connection,
3905 dispatchEntry, keyEntry, handled);
3906 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3907 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3908 restartEvent = afterMotionEventLockedInterruptible(connection,
3909 dispatchEntry, motionEntry, handled);
3910 } else {
3911 restartEvent = false;
3912 }
3913
3914 // Dequeue the event and start the next cycle.
3915 // Note that because the lock might have been released, it is possible that the
3916 // contents of the wait queue to have been drained, so we need to double-check
3917 // a few things.
3918 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3919 connection->waitQueue.dequeue(dispatchEntry);
3920 traceWaitQueueLengthLocked(connection);
3921 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3922 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3923 traceOutboundQueueLengthLocked(connection);
3924 } else {
3925 releaseDispatchEntryLocked(dispatchEntry);
3926 }
3927 }
3928
3929 // Start the next dispatch cycle for this connection.
3930 startDispatchCycleLocked(now(), connection);
3931 }
3932}
3933
3934bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3935 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3936 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3937 // Get the fallback key state.
3938 // Clear it out after dispatching the UP.
3939 int32_t originalKeyCode = keyEntry->keyCode;
3940 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3941 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3942 connection->inputState.removeFallbackKey(originalKeyCode);
3943 }
3944
3945 if (handled || !dispatchEntry->hasForegroundTarget()) {
3946 // If the application handles the original key for which we previously
3947 // generated a fallback or if the window is not a foreground window,
3948 // then cancel the associated fallback key, if any.
3949 if (fallbackKeyCode != -1) {
3950 // Dispatch the unhandled key to the policy with the cancel flag.
3951#if DEBUG_OUTBOUND_EVENT_DETAILS
3952 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3953 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3954 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3955 keyEntry->policyFlags);
3956#endif
3957 KeyEvent event;
3958 initializeKeyEvent(&event, keyEntry);
3959 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3960
3961 mLock.unlock();
3962
3963 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3964 &event, keyEntry->policyFlags, &event);
3965
3966 mLock.lock();
3967
3968 // Cancel the fallback key.
3969 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3970 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3971 "application handled the original non-fallback key "
3972 "or is no longer a foreground target, "
3973 "canceling previously dispatched fallback key");
3974 options.keyCode = fallbackKeyCode;
3975 synthesizeCancelationEventsForConnectionLocked(connection, options);
3976 }
3977 connection->inputState.removeFallbackKey(originalKeyCode);
3978 }
3979 } else {
3980 // If the application did not handle a non-fallback key, first check
3981 // that we are in a good state to perform unhandled key event processing
3982 // Then ask the policy what to do with it.
3983 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3984 && keyEntry->repeatCount == 0;
3985 if (fallbackKeyCode == -1 && !initialDown) {
3986#if DEBUG_OUTBOUND_EVENT_DETAILS
3987 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3988 "since this is not an initial down. "
3989 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3990 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3991 keyEntry->policyFlags);
3992#endif
3993 return false;
3994 }
3995
3996 // Dispatch the unhandled key to the policy.
3997#if DEBUG_OUTBOUND_EVENT_DETAILS
3998 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
3999 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4000 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4001 keyEntry->policyFlags);
4002#endif
4003 KeyEvent event;
4004 initializeKeyEvent(&event, keyEntry);
4005
4006 mLock.unlock();
4007
4008 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
4009 &event, keyEntry->policyFlags, &event);
4010
4011 mLock.lock();
4012
4013 if (connection->status != Connection::STATUS_NORMAL) {
4014 connection->inputState.removeFallbackKey(originalKeyCode);
4015 return false;
4016 }
4017
4018 // Latch the fallback keycode for this key on an initial down.
4019 // The fallback keycode cannot change at any other point in the lifecycle.
4020 if (initialDown) {
4021 if (fallback) {
4022 fallbackKeyCode = event.getKeyCode();
4023 } else {
4024 fallbackKeyCode = AKEYCODE_UNKNOWN;
4025 }
4026 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4027 }
4028
4029 ALOG_ASSERT(fallbackKeyCode != -1);
4030
4031 // Cancel the fallback key if the policy decides not to send it anymore.
4032 // We will continue to dispatch the key to the policy but we will no
4033 // longer dispatch a fallback key to the application.
4034 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4035 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4036#if DEBUG_OUTBOUND_EVENT_DETAILS
4037 if (fallback) {
4038 ALOGD("Unhandled key event: Policy requested to send key %d"
4039 "as a fallback for %d, but on the DOWN it had requested "
4040 "to send %d instead. Fallback canceled.",
4041 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4042 } else {
4043 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4044 "but on the DOWN it had requested to send %d. "
4045 "Fallback canceled.",
4046 originalKeyCode, fallbackKeyCode);
4047 }
4048#endif
4049
4050 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4051 "canceling fallback, policy no longer desires it");
4052 options.keyCode = fallbackKeyCode;
4053 synthesizeCancelationEventsForConnectionLocked(connection, options);
4054
4055 fallback = false;
4056 fallbackKeyCode = AKEYCODE_UNKNOWN;
4057 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4058 connection->inputState.setFallbackKey(originalKeyCode,
4059 fallbackKeyCode);
4060 }
4061 }
4062
4063#if DEBUG_OUTBOUND_EVENT_DETAILS
4064 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004065 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4067 connection->inputState.getFallbackKeys();
4068 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004069 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 fallbackKeys.valueAt(i));
4071 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07004072 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004073 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 }
4075#endif
4076
4077 if (fallback) {
4078 // Restart the dispatch cycle using the fallback key.
4079 keyEntry->eventTime = event.getEventTime();
4080 keyEntry->deviceId = event.getDeviceId();
4081 keyEntry->source = event.getSource();
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004082 keyEntry->displayId = event.getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004083 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4084 keyEntry->keyCode = fallbackKeyCode;
4085 keyEntry->scanCode = event.getScanCode();
4086 keyEntry->metaState = event.getMetaState();
4087 keyEntry->repeatCount = event.getRepeatCount();
4088 keyEntry->downTime = event.getDownTime();
4089 keyEntry->syntheticRepeat = false;
4090
4091#if DEBUG_OUTBOUND_EVENT_DETAILS
4092 ALOGD("Unhandled key event: Dispatching fallback key. "
4093 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4094 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4095#endif
4096 return true; // restart the event
4097 } else {
4098#if DEBUG_OUTBOUND_EVENT_DETAILS
4099 ALOGD("Unhandled key event: No fallback key.");
4100#endif
4101 }
4102 }
4103 }
4104 return false;
4105}
4106
4107bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4108 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4109 return false;
4110}
4111
4112void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4113 mLock.unlock();
4114
4115 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4116
4117 mLock.lock();
4118}
4119
4120void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004121 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4123 entry->downTime, entry->eventTime);
4124}
4125
4126void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4127 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4128 // TODO Write some statistics about how long we spend waiting.
4129}
4130
4131void InputDispatcher::traceInboundQueueLengthLocked() {
4132 if (ATRACE_ENABLED()) {
4133 ATRACE_INT("iq", mInboundQueue.count());
4134 }
4135}
4136
4137void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4138 if (ATRACE_ENABLED()) {
4139 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004140 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 ATRACE_INT(counterName, connection->outboundQueue.count());
4142 }
4143}
4144
4145void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4146 if (ATRACE_ENABLED()) {
4147 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004148 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 ATRACE_INT(counterName, connection->waitQueue.count());
4150 }
4151}
4152
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004153void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 AutoMutex _l(mLock);
4155
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004156 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 dumpDispatchStateLocked(dump);
4158
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004159 if (!mLastANRState.empty()) {
4160 dump += "\nInput Dispatcher State at time of last ANR:\n";
4161 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 }
4163}
4164
4165void InputDispatcher::monitor() {
4166 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4167 mLock.lock();
4168 mLooper->wake();
4169 mDispatcherIsAliveCondition.wait(mLock);
4170 mLock.unlock();
4171}
4172
4173
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174// --- InputDispatcher::InjectionState ---
4175
4176InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4177 refCount(1),
4178 injectorPid(injectorPid), injectorUid(injectorUid),
4179 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4180 pendingForegroundDispatches(0) {
4181}
4182
4183InputDispatcher::InjectionState::~InjectionState() {
4184}
4185
4186void InputDispatcher::InjectionState::release() {
4187 refCount -= 1;
4188 if (refCount == 0) {
4189 delete this;
4190 } else {
4191 ALOG_ASSERT(refCount > 0);
4192 }
4193}
4194
4195
4196// --- InputDispatcher::EventEntry ---
4197
4198InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4199 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
Yi Kong9b14ac62018-07-17 13:48:38 -07004200 injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201}
4202
4203InputDispatcher::EventEntry::~EventEntry() {
4204 releaseInjectionState();
4205}
4206
4207void InputDispatcher::EventEntry::release() {
4208 refCount -= 1;
4209 if (refCount == 0) {
4210 delete this;
4211 } else {
4212 ALOG_ASSERT(refCount > 0);
4213 }
4214}
4215
4216void InputDispatcher::EventEntry::releaseInjectionState() {
4217 if (injectionState) {
4218 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004219 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 }
4221}
4222
4223
4224// --- InputDispatcher::ConfigurationChangedEntry ---
4225
4226InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4227 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4228}
4229
4230InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4231}
4232
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004233void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4234 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235}
4236
4237
4238// --- InputDispatcher::DeviceResetEntry ---
4239
4240InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4241 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4242 deviceId(deviceId) {
4243}
4244
4245InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4246}
4247
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004248void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4249 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 deviceId, policyFlags);
4251}
4252
4253
4254// --- InputDispatcher::KeyEntry ---
4255
4256InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004257 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4259 int32_t repeatCount, nsecs_t downTime) :
4260 EventEntry(TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004261 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4263 repeatCount(repeatCount), downTime(downTime),
4264 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4265 interceptKeyWakeupTime(0) {
4266}
4267
4268InputDispatcher::KeyEntry::~KeyEntry() {
4269}
4270
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004271void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004272 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4274 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004275 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004276 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277}
4278
4279void InputDispatcher::KeyEntry::recycle() {
4280 releaseInjectionState();
4281
4282 dispatchInProgress = false;
4283 syntheticRepeat = false;
4284 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4285 interceptKeyWakeupTime = 0;
4286}
4287
4288
4289// --- InputDispatcher::MotionEntry ---
4290
Michael Wright7b159c92015-05-14 14:48:03 +01004291InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004292 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4293 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004294 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4295 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004296 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004297 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4298 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4300 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004301 deviceId(deviceId), source(source), displayId(displayId), action(action),
4302 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004303 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004304 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 for (uint32_t i = 0; i < pointerCount; i++) {
4306 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4307 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004308 if (xOffset || yOffset) {
4309 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4310 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 }
4312}
4313
4314InputDispatcher::MotionEntry::~MotionEntry() {
4315}
4316
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004317void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004318 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004319 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004320 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004321 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4322 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4323
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 for (uint32_t i = 0; i < pointerCount; i++) {
4325 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004326 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004328 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 pointerCoords[i].getX(), pointerCoords[i].getY());
4330 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004331 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332}
4333
4334
4335// --- InputDispatcher::DispatchEntry ---
4336
4337volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4338
4339InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4340 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4341 seq(nextSeq()),
4342 eventEntry(eventEntry), targetFlags(targetFlags),
4343 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4344 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4345 eventEntry->refCount += 1;
4346}
4347
4348InputDispatcher::DispatchEntry::~DispatchEntry() {
4349 eventEntry->release();
4350}
4351
4352uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4353 // Sequence number 0 is reserved and will never be returned.
4354 uint32_t seq;
4355 do {
4356 seq = android_atomic_inc(&sNextSeqAtomic);
4357 } while (!seq);
4358 return seq;
4359}
4360
4361
4362// --- InputDispatcher::InputState ---
4363
4364InputDispatcher::InputState::InputState() {
4365}
4366
4367InputDispatcher::InputState::~InputState() {
4368}
4369
4370bool InputDispatcher::InputState::isNeutral() const {
4371 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4372}
4373
4374bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4375 int32_t displayId) const {
4376 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4377 const MotionMemento& memento = mMotionMementos.itemAt(i);
4378 if (memento.deviceId == deviceId
4379 && memento.source == source
4380 && memento.displayId == displayId
4381 && memento.hovering) {
4382 return true;
4383 }
4384 }
4385 return false;
4386}
4387
4388bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4389 int32_t action, int32_t flags) {
4390 switch (action) {
4391 case AKEY_EVENT_ACTION_UP: {
4392 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4393 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4394 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4395 mFallbackKeys.removeItemsAt(i);
4396 } else {
4397 i += 1;
4398 }
4399 }
4400 }
4401 ssize_t index = findKeyMemento(entry);
4402 if (index >= 0) {
4403 mKeyMementos.removeAt(index);
4404 return true;
4405 }
4406 /* FIXME: We can't just drop the key up event because that prevents creating
4407 * popup windows that are automatically shown when a key is held and then
4408 * dismissed when the key is released. The problem is that the popup will
4409 * not have received the original key down, so the key up will be considered
4410 * to be inconsistent with its observed state. We could perhaps handle this
4411 * by synthesizing a key down but that will cause other problems.
4412 *
4413 * So for now, allow inconsistent key up events to be dispatched.
4414 *
4415#if DEBUG_OUTBOUND_EVENT_DETAILS
4416 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4417 "keyCode=%d, scanCode=%d",
4418 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4419#endif
4420 return false;
4421 */
4422 return true;
4423 }
4424
4425 case AKEY_EVENT_ACTION_DOWN: {
4426 ssize_t index = findKeyMemento(entry);
4427 if (index >= 0) {
4428 mKeyMementos.removeAt(index);
4429 }
4430 addKeyMemento(entry, flags);
4431 return true;
4432 }
4433
4434 default:
4435 return true;
4436 }
4437}
4438
4439bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4440 int32_t action, int32_t flags) {
4441 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4442 switch (actionMasked) {
4443 case AMOTION_EVENT_ACTION_UP:
4444 case AMOTION_EVENT_ACTION_CANCEL: {
4445 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4446 if (index >= 0) {
4447 mMotionMementos.removeAt(index);
4448 return true;
4449 }
4450#if DEBUG_OUTBOUND_EVENT_DETAILS
4451 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004452 "displayId=%" PRId32 ", actionMasked=%d",
4453 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454#endif
4455 return false;
4456 }
4457
4458 case AMOTION_EVENT_ACTION_DOWN: {
4459 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4460 if (index >= 0) {
4461 mMotionMementos.removeAt(index);
4462 }
4463 addMotionMemento(entry, flags, false /*hovering*/);
4464 return true;
4465 }
4466
4467 case AMOTION_EVENT_ACTION_POINTER_UP:
4468 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4469 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004470 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4471 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4472 // generate cancellation events for these since they're based in relative rather than
4473 // absolute units.
4474 return true;
4475 }
4476
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004478
4479 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4480 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4481 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4482 // other value and we need to track the motion so we can send cancellation events for
4483 // anything generating fallback events (e.g. DPad keys for joystick movements).
4484 if (index >= 0) {
4485 if (entry->pointerCoords[0].isEmpty()) {
4486 mMotionMementos.removeAt(index);
4487 } else {
4488 MotionMemento& memento = mMotionMementos.editItemAt(index);
4489 memento.setPointers(entry);
4490 }
4491 } else if (!entry->pointerCoords[0].isEmpty()) {
4492 addMotionMemento(entry, flags, false /*hovering*/);
4493 }
4494
4495 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4496 return true;
4497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498 if (index >= 0) {
4499 MotionMemento& memento = mMotionMementos.editItemAt(index);
4500 memento.setPointers(entry);
4501 return true;
4502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503#if DEBUG_OUTBOUND_EVENT_DETAILS
4504 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004505 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4506 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507#endif
4508 return false;
4509 }
4510
4511 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4512 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4513 if (index >= 0) {
4514 mMotionMementos.removeAt(index);
4515 return true;
4516 }
4517#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004518 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4519 "displayId=%" PRId32,
4520 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004521#endif
4522 return false;
4523 }
4524
4525 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4526 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4527 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4528 if (index >= 0) {
4529 mMotionMementos.removeAt(index);
4530 }
4531 addMotionMemento(entry, flags, true /*hovering*/);
4532 return true;
4533 }
4534
4535 default:
4536 return true;
4537 }
4538}
4539
4540ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4541 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4542 const KeyMemento& memento = mKeyMementos.itemAt(i);
4543 if (memento.deviceId == entry->deviceId
4544 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004545 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 && memento.keyCode == entry->keyCode
4547 && memento.scanCode == entry->scanCode) {
4548 return i;
4549 }
4550 }
4551 return -1;
4552}
4553
4554ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4555 bool hovering) const {
4556 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4557 const MotionMemento& memento = mMotionMementos.itemAt(i);
4558 if (memento.deviceId == entry->deviceId
4559 && memento.source == entry->source
4560 && memento.displayId == entry->displayId
4561 && memento.hovering == hovering) {
4562 return i;
4563 }
4564 }
4565 return -1;
4566}
4567
4568void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4569 mKeyMementos.push();
4570 KeyMemento& memento = mKeyMementos.editTop();
4571 memento.deviceId = entry->deviceId;
4572 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004573 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574 memento.keyCode = entry->keyCode;
4575 memento.scanCode = entry->scanCode;
4576 memento.metaState = entry->metaState;
4577 memento.flags = flags;
4578 memento.downTime = entry->downTime;
4579 memento.policyFlags = entry->policyFlags;
4580}
4581
4582void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4583 int32_t flags, bool hovering) {
4584 mMotionMementos.push();
4585 MotionMemento& memento = mMotionMementos.editTop();
4586 memento.deviceId = entry->deviceId;
4587 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004588 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589 memento.flags = flags;
4590 memento.xPrecision = entry->xPrecision;
4591 memento.yPrecision = entry->yPrecision;
4592 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 memento.setPointers(entry);
4594 memento.hovering = hovering;
4595 memento.policyFlags = entry->policyFlags;
4596}
4597
4598void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4599 pointerCount = entry->pointerCount;
4600 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4601 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4602 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4603 }
4604}
4605
4606void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4607 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4608 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4609 const KeyMemento& memento = mKeyMementos.itemAt(i);
4610 if (shouldCancelKey(memento, options)) {
4611 outEvents.push(new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004612 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4614 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4615 }
4616 }
4617
4618 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4619 const MotionMemento& memento = mMotionMementos.itemAt(i);
4620 if (shouldCancelMotion(memento, options)) {
4621 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004622 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623 memento.hovering
4624 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4625 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004626 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004628 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4629 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 }
4631 }
4632}
4633
4634void InputDispatcher::InputState::clear() {
4635 mKeyMementos.clear();
4636 mMotionMementos.clear();
4637 mFallbackKeys.clear();
4638}
4639
4640void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4641 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4642 const MotionMemento& memento = mMotionMementos.itemAt(i);
4643 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4644 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4645 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4646 if (memento.deviceId == otherMemento.deviceId
4647 && memento.source == otherMemento.source
4648 && memento.displayId == otherMemento.displayId) {
4649 other.mMotionMementos.removeAt(j);
4650 } else {
4651 j += 1;
4652 }
4653 }
4654 other.mMotionMementos.push(memento);
4655 }
4656 }
4657}
4658
4659int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4660 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4661 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4662}
4663
4664void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4665 int32_t fallbackKeyCode) {
4666 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4667 if (index >= 0) {
4668 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4669 } else {
4670 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4671 }
4672}
4673
4674void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4675 mFallbackKeys.removeItem(originalKeyCode);
4676}
4677
4678bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4679 const CancelationOptions& options) {
4680 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4681 return false;
4682 }
4683
4684 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4685 return false;
4686 }
4687
4688 switch (options.mode) {
4689 case CancelationOptions::CANCEL_ALL_EVENTS:
4690 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4691 return true;
4692 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4693 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004694 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4695 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 default:
4697 return false;
4698 }
4699}
4700
4701bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4702 const CancelationOptions& options) {
4703 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4704 return false;
4705 }
4706
4707 switch (options.mode) {
4708 case CancelationOptions::CANCEL_ALL_EVENTS:
4709 return true;
4710 case CancelationOptions::CANCEL_POINTER_EVENTS:
4711 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4712 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4713 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004714 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4715 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 default:
4717 return false;
4718 }
4719}
4720
4721
4722// --- InputDispatcher::Connection ---
4723
4724InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4725 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4726 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4727 monitor(monitor),
4728 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4729}
4730
4731InputDispatcher::Connection::~Connection() {
4732}
4733
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004734const std::string InputDispatcher::Connection::getWindowName() const {
Yi Kong9b14ac62018-07-17 13:48:38 -07004735 if (inputWindowHandle != nullptr) {
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004736 return inputWindowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737 }
4738 if (monitor) {
4739 return "monitor";
4740 }
4741 return "?";
4742}
4743
4744const char* InputDispatcher::Connection::getStatusLabel() const {
4745 switch (status) {
4746 case STATUS_NORMAL:
4747 return "NORMAL";
4748
4749 case STATUS_BROKEN:
4750 return "BROKEN";
4751
4752 case STATUS_ZOMBIE:
4753 return "ZOMBIE";
4754
4755 default:
4756 return "UNKNOWN";
4757 }
4758}
4759
4760InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004761 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762 if (entry->seq == seq) {
4763 return entry;
4764 }
4765 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004766 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767}
4768
4769
4770// --- InputDispatcher::CommandEntry ---
4771
4772InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004773 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004774 seq(0), handled(false) {
4775}
4776
4777InputDispatcher::CommandEntry::~CommandEntry() {
4778}
4779
4780
4781// --- InputDispatcher::TouchState ---
4782
4783InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004784 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785}
4786
4787InputDispatcher::TouchState::~TouchState() {
4788}
4789
4790void InputDispatcher::TouchState::reset() {
4791 down = false;
4792 split = false;
4793 deviceId = -1;
4794 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004795 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796 windows.clear();
4797}
4798
4799void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4800 down = other.down;
4801 split = other.split;
4802 deviceId = other.deviceId;
4803 source = other.source;
4804 displayId = other.displayId;
4805 windows = other.windows;
4806}
4807
4808void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4809 int32_t targetFlags, BitSet32 pointerIds) {
4810 if (targetFlags & InputTarget::FLAG_SPLIT) {
4811 split = true;
4812 }
4813
4814 for (size_t i = 0; i < windows.size(); i++) {
4815 TouchedWindow& touchedWindow = windows.editItemAt(i);
4816 if (touchedWindow.windowHandle == windowHandle) {
4817 touchedWindow.targetFlags |= targetFlags;
4818 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4819 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4820 }
4821 touchedWindow.pointerIds.value |= pointerIds.value;
4822 return;
4823 }
4824 }
4825
4826 windows.push();
4827
4828 TouchedWindow& touchedWindow = windows.editTop();
4829 touchedWindow.windowHandle = windowHandle;
4830 touchedWindow.targetFlags = targetFlags;
4831 touchedWindow.pointerIds = pointerIds;
4832}
4833
4834void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4835 for (size_t i = 0; i < windows.size(); i++) {
4836 if (windows.itemAt(i).windowHandle == windowHandle) {
4837 windows.removeAt(i);
4838 return;
4839 }
4840 }
4841}
4842
4843void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4844 for (size_t i = 0 ; i < windows.size(); ) {
4845 TouchedWindow& window = windows.editItemAt(i);
4846 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4847 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4848 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4849 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4850 i += 1;
4851 } else {
4852 windows.removeAt(i);
4853 }
4854 }
4855}
4856
4857sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4858 for (size_t i = 0; i < windows.size(); i++) {
4859 const TouchedWindow& window = windows.itemAt(i);
4860 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4861 return window.windowHandle;
4862 }
4863 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004864 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865}
4866
4867bool InputDispatcher::TouchState::isSlippery() const {
4868 // Must have exactly one foreground window.
4869 bool haveSlipperyForegroundWindow = false;
4870 for (size_t i = 0; i < windows.size(); i++) {
4871 const TouchedWindow& window = windows.itemAt(i);
4872 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4873 if (haveSlipperyForegroundWindow
4874 || !(window.windowHandle->getInfo()->layoutParamsFlags
4875 & InputWindowInfo::FLAG_SLIPPERY)) {
4876 return false;
4877 }
4878 haveSlipperyForegroundWindow = true;
4879 }
4880 }
4881 return haveSlipperyForegroundWindow;
4882}
4883
4884
4885// --- InputDispatcherThread ---
4886
4887InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4888 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4889}
4890
4891InputDispatcherThread::~InputDispatcherThread() {
4892}
4893
4894bool InputDispatcherThread::threadLoop() {
4895 mDispatcher->dispatchOnce();
4896 return true;
4897}
4898
4899} // namespace android