blob: 3f39afd8b090da7433bf3d4df2f9557d87c6c602 [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 Hung3b413f22018-10-26 18:05:34 +0800867 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64 ", displayId=%" PRId32,
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 Hung3b413f22018-10-26 18:05:34 +0800871 entry->repeatCount, entry->downTime, entry->displayId);
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 Hung3b413f22018-10-26 18:05:34 +0800943 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64", displayId=%" PRId32,
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 Hung3b413f22018-10-26 18:05:34 +0800949 entry->downTime, entry->displayId);
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 Hung3b413f22018-10-26 18:05:34 +08002542 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64
2543 ", displayId=%" PRId32,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002544 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung3b413f22018-10-26 18:05:34 +08002546 args->metaState, args->downTime, args->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547#endif
2548 if (!validateKeyEvent(args->action)) {
2549 return;
2550 }
2551
2552 uint32_t policyFlags = args->policyFlags;
2553 int32_t flags = args->flags;
2554 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002555 // InputDispatcher tracks and generates key repeats on behalf of
2556 // whatever notifies it, so repeatCount should always be set to 0
2557 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2559 policyFlags |= POLICY_FLAG_VIRTUAL;
2560 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 if (policyFlags & POLICY_FLAG_FUNCTION) {
2563 metaState |= AMETA_FUNCTION_ON;
2564 }
2565
2566 policyFlags |= POLICY_FLAG_TRUSTED;
2567
Michael Wright78f24442014-08-06 15:55:28 -07002568 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002569 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002570
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002572 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002573 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574 args->downTime, args->eventTime);
2575
Michael Wright2b3c3302018-03-02 17:19:13 +00002576 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002578 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2579 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2580 std::to_string(t.duration().count()).c_str());
2581 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 bool needWake;
2584 { // acquire lock
2585 mLock.lock();
2586
2587 if (shouldSendKeyToInputFilterLocked(args)) {
2588 mLock.unlock();
2589
2590 policyFlags |= POLICY_FLAG_FILTERED;
2591 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2592 return; // event was consumed by the filter
2593 }
2594
2595 mLock.lock();
2596 }
2597
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 KeyEntry* newEntry = new KeyEntry(args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002599 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002600 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 metaState, repeatCount, args->downTime);
2602
2603 needWake = enqueueInboundEventLocked(newEntry);
2604 mLock.unlock();
2605 } // release lock
2606
2607 if (needWake) {
2608 mLooper->wake();
2609 }
2610}
2611
2612bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2613 return mInputFilterEnabled;
2614}
2615
2616void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2617#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002618 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2619 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002620 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung3b413f22018-10-26 18:05:34 +08002621 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", displayId=%" PRId32
2622 , args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002623 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung3b413f22018-10-26 18:05:34 +08002624 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime, args->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 for (uint32_t i = 0; i < args->pointerCount; i++) {
2626 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2627 "x=%f, y=%f, pressure=%f, size=%f, "
2628 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2629 "orientation=%f",
2630 i, args->pointerProperties[i].id,
2631 args->pointerProperties[i].toolType,
2632 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2633 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2634 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2635 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2636 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2637 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2638 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2639 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2640 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2641 }
2642#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002643 if (!validateMotionEvent(args->action, args->actionButton,
2644 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002645 return;
2646 }
2647
2648 uint32_t policyFlags = args->policyFlags;
2649 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002650
2651 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002653 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2654 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2655 std::to_string(t.duration().count()).c_str());
2656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657
2658 bool needWake;
2659 { // acquire lock
2660 mLock.lock();
2661
2662 if (shouldSendMotionToInputFilterLocked(args)) {
2663 mLock.unlock();
2664
2665 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002666 event.initialize(args->deviceId, args->source, args->displayId,
2667 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002668 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2669 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 args->downTime, args->eventTime,
2671 args->pointerCount, args->pointerProperties, args->pointerCoords);
2672
2673 policyFlags |= POLICY_FLAG_FILTERED;
2674 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2675 return; // event was consumed by the filter
2676 }
2677
2678 mLock.lock();
2679 }
2680
2681 // Just enqueue a new motion event.
2682 MotionEntry* newEntry = new MotionEntry(args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002683 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002684 args->action, args->actionButton, args->flags,
2685 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002687 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688
2689 needWake = enqueueInboundEventLocked(newEntry);
2690 mLock.unlock();
2691 } // release lock
2692
2693 if (needWake) {
2694 mLooper->wake();
2695 }
2696}
2697
2698bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2699 // TODO: support sending secondary display events to input filter
2700 return mInputFilterEnabled && isMainDisplay(args->displayId);
2701}
2702
2703void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2704#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002705 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2706 "switchMask=0x%08x",
2707 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708#endif
2709
2710 uint32_t policyFlags = args->policyFlags;
2711 policyFlags |= POLICY_FLAG_TRUSTED;
2712 mPolicy->notifySwitch(args->eventTime,
2713 args->switchValues, args->switchMask, policyFlags);
2714}
2715
2716void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2717#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002718 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719 args->eventTime, args->deviceId);
2720#endif
2721
2722 bool needWake;
2723 { // acquire lock
2724 AutoMutex _l(mLock);
2725
2726 DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
2727 needWake = enqueueInboundEventLocked(newEntry);
2728 } // release lock
2729
2730 if (needWake) {
2731 mLooper->wake();
2732 }
2733}
2734
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002735int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2737 uint32_t policyFlags) {
2738#if DEBUG_INBOUND_EVENT_DETAILS
2739 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002740 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2741 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742#endif
2743
2744 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2745
2746 policyFlags |= POLICY_FLAG_INJECTED;
2747 if (hasInjectionPermission(injectorPid, injectorUid)) {
2748 policyFlags |= POLICY_FLAG_TRUSTED;
2749 }
2750
2751 EventEntry* firstInjectedEntry;
2752 EventEntry* lastInjectedEntry;
2753 switch (event->getType()) {
2754 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002755 KeyEvent keyEvent;
2756 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2757 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 if (! validateKeyEvent(action)) {
2759 return INPUT_EVENT_INJECTION_FAILED;
2760 }
2761
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002762 int32_t flags = keyEvent.getFlags();
2763 int32_t keyCode = keyEvent.getKeyCode();
2764 int32_t metaState = keyEvent.getMetaState();
2765 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2766 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002767 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002768 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002769 keyEvent.getDownTime(), keyEvent.getEventTime());
2770
Michael Wrightd02c5b62014-02-10 15:10:22 -08002771 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2772 policyFlags |= POLICY_FLAG_VIRTUAL;
2773 }
2774
2775 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002776 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002777 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002778 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2779 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2780 std::to_string(t.duration().count()).c_str());
2781 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 }
2783
Michael Wrightd02c5b62014-02-10 15:10:22 -08002784 mLock.lock();
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002785 firstInjectedEntry = new KeyEntry(keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002786 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002788 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2789 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790 lastInjectedEntry = firstInjectedEntry;
2791 break;
2792 }
2793
2794 case AINPUT_EVENT_TYPE_MOTION: {
2795 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 int32_t action = motionEvent->getAction();
2797 size_t pointerCount = motionEvent->getPointerCount();
2798 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002799 int32_t actionButton = motionEvent->getActionButton();
2800 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801 return INPUT_EVENT_INJECTION_FAILED;
2802 }
2803
2804 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2805 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002806 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002808 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2809 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2810 std::to_string(t.duration().count()).c_str());
2811 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 }
2813
2814 mLock.lock();
2815 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2816 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
2817 firstInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002818 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2819 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002820 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 motionEvent->getMetaState(), motionEvent->getButtonState(),
2822 motionEvent->getEdgeFlags(),
2823 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002824 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002825 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2826 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827 lastInjectedEntry = firstInjectedEntry;
2828 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2829 sampleEventTimes += 1;
2830 samplePointerCoords += pointerCount;
2831 MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002832 motionEvent->getDeviceId(), motionEvent->getSource(),
2833 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002834 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835 motionEvent->getMetaState(), motionEvent->getButtonState(),
2836 motionEvent->getEdgeFlags(),
2837 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002838 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002839 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2840 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002841 lastInjectedEntry->next = nextInjectedEntry;
2842 lastInjectedEntry = nextInjectedEntry;
2843 }
2844 break;
2845 }
2846
2847 default:
2848 ALOGW("Cannot inject event of type %d", event->getType());
2849 return INPUT_EVENT_INJECTION_FAILED;
2850 }
2851
2852 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2853 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2854 injectionState->injectionIsAsync = true;
2855 }
2856
2857 injectionState->refCount += 1;
2858 lastInjectedEntry->injectionState = injectionState;
2859
2860 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002861 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862 EventEntry* nextEntry = entry->next;
2863 needWake |= enqueueInboundEventLocked(entry);
2864 entry = nextEntry;
2865 }
2866
2867 mLock.unlock();
2868
2869 if (needWake) {
2870 mLooper->wake();
2871 }
2872
2873 int32_t injectionResult;
2874 { // acquire lock
2875 AutoMutex _l(mLock);
2876
2877 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2878 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2879 } else {
2880 for (;;) {
2881 injectionResult = injectionState->injectionResult;
2882 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2883 break;
2884 }
2885
2886 nsecs_t remainingTimeout = endTime - now();
2887 if (remainingTimeout <= 0) {
2888#if DEBUG_INJECTION
2889 ALOGD("injectInputEvent - Timed out waiting for injection result "
2890 "to become available.");
2891#endif
2892 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2893 break;
2894 }
2895
2896 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2897 }
2898
2899 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2900 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2901 while (injectionState->pendingForegroundDispatches != 0) {
2902#if DEBUG_INJECTION
2903 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2904 injectionState->pendingForegroundDispatches);
2905#endif
2906 nsecs_t remainingTimeout = endTime - now();
2907 if (remainingTimeout <= 0) {
2908#if DEBUG_INJECTION
2909 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2910 "dispatches to finish.");
2911#endif
2912 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2913 break;
2914 }
2915
2916 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2917 }
2918 }
2919 }
2920
2921 injectionState->release();
2922 } // release lock
2923
2924#if DEBUG_INJECTION
2925 ALOGD("injectInputEvent - Finished with result %d. "
2926 "injectorPid=%d, injectorUid=%d",
2927 injectionResult, injectorPid, injectorUid);
2928#endif
2929
2930 return injectionResult;
2931}
2932
2933bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2934 return injectorUid == 0
2935 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2936}
2937
2938void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2939 InjectionState* injectionState = entry->injectionState;
2940 if (injectionState) {
2941#if DEBUG_INJECTION
2942 ALOGD("Setting input event injection result to %d. "
2943 "injectorPid=%d, injectorUid=%d",
2944 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2945#endif
2946
2947 if (injectionState->injectionIsAsync
2948 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2949 // Log the outcome since the injector did not wait for the injection result.
2950 switch (injectionResult) {
2951 case INPUT_EVENT_INJECTION_SUCCEEDED:
2952 ALOGV("Asynchronous input event injection succeeded.");
2953 break;
2954 case INPUT_EVENT_INJECTION_FAILED:
2955 ALOGW("Asynchronous input event injection failed.");
2956 break;
2957 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2958 ALOGW("Asynchronous input event injection permission denied.");
2959 break;
2960 case INPUT_EVENT_INJECTION_TIMED_OUT:
2961 ALOGW("Asynchronous input event injection timed out.");
2962 break;
2963 }
2964 }
2965
2966 injectionState->injectionResult = injectionResult;
2967 mInjectionResultAvailableCondition.broadcast();
2968 }
2969}
2970
2971void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2972 InjectionState* injectionState = entry->injectionState;
2973 if (injectionState) {
2974 injectionState->pendingForegroundDispatches += 1;
2975 }
2976}
2977
2978void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2979 InjectionState* injectionState = entry->injectionState;
2980 if (injectionState) {
2981 injectionState->pendingForegroundDispatches -= 1;
2982
2983 if (injectionState->pendingForegroundDispatches == 0) {
2984 mInjectionSyncFinishedCondition.broadcast();
2985 }
2986 }
2987}
2988
Arthur Hungb92218b2018-08-14 12:00:21 +08002989Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
2990 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
2991 mWindowHandlesByDisplay.find(displayId);
2992 if(it != mWindowHandlesByDisplay.end()) {
2993 return it->second;
2994 }
2995
2996 // Return an empty one if nothing found.
2997 return Vector<sp<InputWindowHandle>>();
2998}
2999
Michael Wrightd02c5b62014-02-10 15:10:22 -08003000sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3001 const sp<InputChannel>& inputChannel) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003002 for (auto& it : mWindowHandlesByDisplay) {
3003 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3004 size_t numWindows = windowHandles.size();
3005 for (size_t i = 0; i < numWindows; i++) {
3006 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3007 if (windowHandle->getInputChannel() == inputChannel) {
3008 return windowHandle;
3009 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003010 }
3011 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003012 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013}
3014
3015bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003016 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003017 for (auto& it : mWindowHandlesByDisplay) {
3018 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3019 size_t numWindows = windowHandles.size();
3020 for (size_t i = 0; i < numWindows; i++) {
3021 if (windowHandles.itemAt(i) == windowHandle) {
3022 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003023 ALOGE("Found window %s in display %" PRId32
3024 ", but it should belong to display %" PRId32,
3025 windowHandle->getName().c_str(), it.first,
3026 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003027 }
3028 return true;
3029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003030 }
3031 }
3032 return false;
3033}
3034
Arthur Hungb92218b2018-08-14 12:00:21 +08003035/**
3036 * Called from InputManagerService, update window handle list by displayId that can receive input.
3037 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3038 * If set an empty list, remove all handles from the specific display.
3039 * For focused handle, check if need to change and send a cancel event to previous one.
3040 * For removed handle, check if need to send a cancel event if already in touch.
3041 */
3042void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3043 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003045 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003046#endif
3047 { // acquire lock
3048 AutoMutex _l(mLock);
3049
Arthur Hungb92218b2018-08-14 12:00:21 +08003050 // Copy old handles for release if they are no longer present.
3051 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052
Tiger Huang721e26f2018-07-24 22:26:19 +08003053 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003055
3056 if (inputWindowHandles.isEmpty()) {
3057 // Remove all handles on a display if there are no windows left.
3058 mWindowHandlesByDisplay.erase(displayId);
3059 } else {
3060 size_t numWindows = inputWindowHandles.size();
3061 for (size_t i = 0; i < numWindows; i++) {
3062 const sp<InputWindowHandle>& windowHandle = inputWindowHandles.itemAt(i);
3063 if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == nullptr) {
3064 continue;
3065 }
3066
3067 if (windowHandle->getInfo()->displayId != displayId) {
3068 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
3069 windowHandle->getName().c_str(), displayId,
3070 windowHandle->getInfo()->displayId);
3071 continue;
3072 }
3073
3074 if (windowHandle->getInfo()->hasFocus) {
3075 newFocusedWindowHandle = windowHandle;
3076 }
3077 if (windowHandle == mLastHoverWindowHandle) {
3078 foundHoveredWindow = true;
3079 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003080 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003081
3082 // Insert or replace
3083 mWindowHandlesByDisplay[displayId] = inputWindowHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003084 }
3085
3086 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003087 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 }
3089
Tiger Huang721e26f2018-07-24 22:26:19 +08003090 sp<InputWindowHandle> oldFocusedWindowHandle =
3091 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3092
3093 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3094 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003095#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003096 ALOGD("Focus left window: %s in display %" PRId32,
3097 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003099 sp<InputChannel> focusedInputChannel = oldFocusedWindowHandle->getInputChannel();
Yi Kong9b14ac62018-07-17 13:48:38 -07003100 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3102 "focus left window");
3103 synthesizeCancelationEventsForInputChannelLocked(
3104 focusedInputChannel, options);
3105 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003106 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003108 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003110 ALOGD("Focus entered window: %s in display %" PRId32,
3111 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003113 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003114 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 }
3116
Arthur Hungb92218b2018-08-14 12:00:21 +08003117 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3118 if (stateIndex >= 0) {
3119 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003120 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003121 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003122 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003123#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003124 ALOGD("Touched window was removed: %s in display %" PRId32,
3125 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003127 sp<InputChannel> touchedInputChannel =
3128 touchedWindow.windowHandle->getInputChannel();
Yi Kong9b14ac62018-07-17 13:48:38 -07003129 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003130 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3131 "touched window was removed");
3132 synthesizeCancelationEventsForInputChannelLocked(
3133 touchedInputChannel, options);
3134 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003135 state.windows.removeAt(i);
3136 } else {
3137 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139 }
3140 }
3141
3142 // Release information for windows that are no longer present.
3143 // This ensures that unused input channels are released promptly.
3144 // Otherwise, they might stick around until the window handle is destroyed
3145 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003146 size_t numWindows = oldWindowHandles.size();
3147 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003149 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003151 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003153 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154 }
3155 }
3156 } // release lock
3157
3158 // Wake up poll loop since it may need to make new input dispatching choices.
3159 mLooper->wake();
3160}
3161
3162void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003163 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003165 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166#endif
3167 { // acquire lock
3168 AutoMutex _l(mLock);
3169
Tiger Huang721e26f2018-07-24 22:26:19 +08003170 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3171 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003172 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003173 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3174 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003176 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003178 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003180 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003182 oldFocusedApplicationHandle->releaseInfo();
3183 oldFocusedApplicationHandle.clear();
3184 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 }
3186
3187#if DEBUG_FOCUS
3188 //logDispatchStateLocked();
3189#endif
3190 } // release lock
3191
3192 // Wake up poll loop since it may need to make new input dispatching choices.
3193 mLooper->wake();
3194}
3195
Tiger Huang721e26f2018-07-24 22:26:19 +08003196/**
3197 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3198 * the display not specified.
3199 *
3200 * We track any unreleased events for each window. If a window loses the ability to receive the
3201 * released event, we will send a cancel event to it. So when the focused display is changed, we
3202 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3203 * display. The display-specified events won't be affected.
3204 */
3205void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3206#if DEBUG_FOCUS
3207 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3208#endif
3209 { // acquire lock
3210 AutoMutex _l(mLock);
3211
3212 if (mFocusedDisplayId != displayId) {
3213 sp<InputWindowHandle> oldFocusedWindowHandle =
3214 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3215 if (oldFocusedWindowHandle != nullptr) {
3216 sp<InputChannel> inputChannel = oldFocusedWindowHandle->getInputChannel();
3217 if (inputChannel != nullptr) {
3218 CancelationOptions options(
3219 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3220 "The display which contains this window no longer has focus.");
3221 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3222 }
3223 }
3224 mFocusedDisplayId = displayId;
3225
3226 // Sanity check
3227 sp<InputWindowHandle> newFocusedWindowHandle =
3228 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3229 if (newFocusedWindowHandle == nullptr) {
3230 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3231 if (!mFocusedWindowHandlesByDisplay.empty()) {
3232 ALOGE("But another display has a focused window:");
3233 for (auto& it : mFocusedWindowHandlesByDisplay) {
3234 const int32_t displayId = it.first;
3235 const sp<InputWindowHandle>& windowHandle = it.second;
3236 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3237 displayId, windowHandle->getName().c_str());
3238 }
3239 }
3240 }
3241 }
3242
3243#if DEBUG_FOCUS
3244 logDispatchStateLocked();
3245#endif
3246 } // release lock
3247
3248 // Wake up poll loop since it may need to make new input dispatching choices.
3249 mLooper->wake();
3250}
3251
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3253#if DEBUG_FOCUS
3254 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3255#endif
3256
3257 bool changed;
3258 { // acquire lock
3259 AutoMutex _l(mLock);
3260
3261 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3262 if (mDispatchFrozen && !frozen) {
3263 resetANRTimeoutsLocked();
3264 }
3265
3266 if (mDispatchEnabled && !enabled) {
3267 resetAndDropEverythingLocked("dispatcher is being disabled");
3268 }
3269
3270 mDispatchEnabled = enabled;
3271 mDispatchFrozen = frozen;
3272 changed = true;
3273 } else {
3274 changed = false;
3275 }
3276
3277#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003278 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279#endif
3280 } // release lock
3281
3282 if (changed) {
3283 // Wake up poll loop since it may need to make new input dispatching choices.
3284 mLooper->wake();
3285 }
3286}
3287
3288void InputDispatcher::setInputFilterEnabled(bool enabled) {
3289#if DEBUG_FOCUS
3290 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3291#endif
3292
3293 { // acquire lock
3294 AutoMutex _l(mLock);
3295
3296 if (mInputFilterEnabled == enabled) {
3297 return;
3298 }
3299
3300 mInputFilterEnabled = enabled;
3301 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3302 } // release lock
3303
3304 // Wake up poll loop since there might be work to do to drop everything.
3305 mLooper->wake();
3306}
3307
3308bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3309 const sp<InputChannel>& toChannel) {
3310#if DEBUG_FOCUS
3311 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003312 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313#endif
3314 { // acquire lock
3315 AutoMutex _l(mLock);
3316
3317 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3318 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07003319 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320#if DEBUG_FOCUS
3321 ALOGD("Cannot transfer focus because from or to window not found.");
3322#endif
3323 return false;
3324 }
3325 if (fromWindowHandle == toWindowHandle) {
3326#if DEBUG_FOCUS
3327 ALOGD("Trivial transfer to same window.");
3328#endif
3329 return true;
3330 }
3331 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3332#if DEBUG_FOCUS
3333 ALOGD("Cannot transfer focus because windows are on different displays.");
3334#endif
3335 return false;
3336 }
3337
3338 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003339 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3340 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3341 for (size_t i = 0; i < state.windows.size(); i++) {
3342 const TouchedWindow& touchedWindow = state.windows[i];
3343 if (touchedWindow.windowHandle == fromWindowHandle) {
3344 int32_t oldTargetFlags = touchedWindow.targetFlags;
3345 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346
Jeff Brownf086ddb2014-02-11 14:28:48 -08003347 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348
Jeff Brownf086ddb2014-02-11 14:28:48 -08003349 int32_t newTargetFlags = oldTargetFlags
3350 & (InputTarget::FLAG_FOREGROUND
3351 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3352 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353
Jeff Brownf086ddb2014-02-11 14:28:48 -08003354 found = true;
3355 goto Found;
3356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 }
3358 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003359Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360
3361 if (! found) {
3362#if DEBUG_FOCUS
3363 ALOGD("Focus transfer failed because from window did not have focus.");
3364#endif
3365 return false;
3366 }
3367
3368 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3369 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3370 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3371 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3372 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3373
3374 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3375 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3376 "transferring touch focus from this window to another window");
3377 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3378 }
3379
3380#if DEBUG_FOCUS
3381 logDispatchStateLocked();
3382#endif
3383 } // release lock
3384
3385 // Wake up poll loop since it may need to make new input dispatching choices.
3386 mLooper->wake();
3387 return true;
3388}
3389
3390void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3391#if DEBUG_FOCUS
3392 ALOGD("Resetting and dropping all events (%s).", reason);
3393#endif
3394
3395 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3396 synthesizeCancelationEventsForAllConnectionsLocked(options);
3397
3398 resetKeyRepeatLocked();
3399 releasePendingEventLocked();
3400 drainInboundQueueLocked();
3401 resetANRTimeoutsLocked();
3402
Jeff Brownf086ddb2014-02-11 14:28:48 -08003403 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003405 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003406}
3407
3408void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003409 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 dumpDispatchStateLocked(dump);
3411
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003412 std::istringstream stream(dump);
3413 std::string line;
3414
3415 while (std::getline(stream, line, '\n')) {
3416 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417 }
3418}
3419
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003420void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3421 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3422 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003423 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424
Tiger Huang721e26f2018-07-24 22:26:19 +08003425 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3426 dump += StringPrintf(INDENT "FocusedApplications:\n");
3427 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3428 const int32_t displayId = it.first;
3429 const sp<InputApplicationHandle>& applicationHandle = it.second;
3430 dump += StringPrintf(
3431 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3432 displayId,
3433 applicationHandle->getName().c_str(),
3434 applicationHandle->getDispatchingTimeout(
3435 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003438 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003440
3441 if (!mFocusedWindowHandlesByDisplay.empty()) {
3442 dump += StringPrintf(INDENT "FocusedWindows:\n");
3443 for (auto& it : mFocusedWindowHandlesByDisplay) {
3444 const int32_t displayId = it.first;
3445 const sp<InputWindowHandle>& windowHandle = it.second;
3446 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3447 displayId, windowHandle->getName().c_str());
3448 }
3449 } else {
3450 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452
Jeff Brownf086ddb2014-02-11 14:28:48 -08003453 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003454 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003455 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3456 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003457 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003458 state.displayId, toString(state.down), toString(state.split),
3459 state.deviceId, state.source);
3460 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003461 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003462 for (size_t i = 0; i < state.windows.size(); i++) {
3463 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003464 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3465 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003466 touchedWindow.pointerIds.value,
3467 touchedWindow.targetFlags);
3468 }
3469 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003470 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003471 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472 }
3473 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003474 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 }
3476
Arthur Hungb92218b2018-08-14 12:00:21 +08003477 if (!mWindowHandlesByDisplay.empty()) {
3478 for (auto& it : mWindowHandlesByDisplay) {
3479 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003480 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003481 if (!windowHandles.isEmpty()) {
3482 dump += INDENT2 "Windows:\n";
3483 for (size_t i = 0; i < windowHandles.size(); i++) {
3484 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3485 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486
Arthur Hungb92218b2018-08-14 12:00:21 +08003487 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3488 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3489 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
3490 "frame=[%d,%d][%d,%d], scale=%f, "
3491 "touchableRegion=",
3492 i, windowInfo->name.c_str(), windowInfo->displayId,
3493 toString(windowInfo->paused),
3494 toString(windowInfo->hasFocus),
3495 toString(windowInfo->hasWallpaper),
3496 toString(windowInfo->visible),
3497 toString(windowInfo->canReceiveKeys),
3498 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3499 windowInfo->layer,
3500 windowInfo->frameLeft, windowInfo->frameTop,
3501 windowInfo->frameRight, windowInfo->frameBottom,
3502 windowInfo->scaleFactor);
3503 dumpRegion(dump, windowInfo->touchableRegion);
3504 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3505 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3506 windowInfo->ownerPid, windowInfo->ownerUid,
3507 windowInfo->dispatchingTimeout / 1000000.0);
3508 }
3509 } else {
3510 dump += INDENT2 "Windows: <none>\n";
3511 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 }
3513 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003514 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515 }
3516
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003517 if (!mMonitoringChannelsByDisplay.empty()) {
3518 for (auto& it : mMonitoringChannelsByDisplay) {
3519 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003520 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003521 const size_t numChannels = monitoringChannels.size();
3522 for (size_t i = 0; i < numChannels; i++) {
3523 const sp<InputChannel>& channel = monitoringChannels[i];
3524 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3525 }
3526 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003528 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 }
3530
3531 nsecs_t currentTime = now();
3532
3533 // Dump recently dispatched or dropped events from oldest to newest.
3534 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003535 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003537 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003539 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 (currentTime - entry->eventTime) * 0.000001f);
3541 }
3542 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003543 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544 }
3545
3546 // Dump event currently being dispatched.
3547 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003548 dump += INDENT "PendingEvent:\n";
3549 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003550 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003551 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3553 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003554 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555 }
3556
3557 // Dump inbound events from oldest to newest.
3558 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003559 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003561 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003563 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 (currentTime - entry->eventTime) * 0.000001f);
3565 }
3566 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003567 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003568 }
3569
Michael Wright78f24442014-08-06 15:55:28 -07003570 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003571 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003572 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3573 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3574 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003575 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003576 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3577 }
3578 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003579 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003580 }
3581
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003583 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3585 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003586 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003588 i, connection->getInputChannelName().c_str(),
3589 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003590 connection->getStatusLabel(), toString(connection->monitor),
3591 toString(connection->inputPublisherBlocked));
3592
3593 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003594 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 connection->outboundQueue.count());
3596 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3597 entry = entry->next) {
3598 dump.append(INDENT4);
3599 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003600 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601 entry->targetFlags, entry->resolvedAction,
3602 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3603 }
3604 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003605 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003606 }
3607
3608 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003609 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 connection->waitQueue.count());
3611 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3612 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003613 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003615 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003616 "age=%0.1fms, wait=%0.1fms\n",
3617 entry->targetFlags, entry->resolvedAction,
3618 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3619 (currentTime - entry->deliveryTime) * 0.000001f);
3620 }
3621 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003622 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 }
3624 }
3625 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003626 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 }
3628
3629 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003630 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 (mAppSwitchDueTime - now()) / 1000000.0);
3632 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003633 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 }
3635
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003636 dump += INDENT "Configuration:\n";
3637 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003639 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 mConfig.keyRepeatTimeout * 0.000001f);
3641}
3642
3643status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003644 const sp<InputWindowHandle>& inputWindowHandle, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003646 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3647 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648#endif
3649
3650 { // acquire lock
3651 AutoMutex _l(mLock);
3652
3653 if (getConnectionIndexLocked(inputChannel) >= 0) {
3654 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003655 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656 return BAD_VALUE;
3657 }
3658
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003659 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3660 // treat inputChannel as monitor channel for displayId.
3661 bool monitor = inputWindowHandle == nullptr && displayId != ADISPLAY_ID_NONE;
3662
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
3664
3665 int fd = inputChannel->getFd();
3666 mConnectionsByFd.add(fd, connection);
3667
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003668 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003670 Vector<sp<InputChannel>>& monitoringChannels =
3671 mMonitoringChannelsByDisplay[displayId];
3672 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673 }
3674
3675 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3676 } // release lock
3677
3678 // Wake the looper because some connections have changed.
3679 mLooper->wake();
3680 return OK;
3681}
3682
3683status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3684#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003685 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686#endif
3687
3688 { // acquire lock
3689 AutoMutex _l(mLock);
3690
3691 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3692 if (status) {
3693 return status;
3694 }
3695 } // release lock
3696
3697 // Wake the poll loop because removing the connection may have changed the current
3698 // synchronization state.
3699 mLooper->wake();
3700 return OK;
3701}
3702
3703status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3704 bool notify) {
3705 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3706 if (connectionIndex < 0) {
3707 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003708 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 return BAD_VALUE;
3710 }
3711
3712 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3713 mConnectionsByFd.removeItemsAt(connectionIndex);
3714
3715 if (connection->monitor) {
3716 removeMonitorChannelLocked(inputChannel);
3717 }
3718
3719 mLooper->removeFd(inputChannel->getFd());
3720
3721 nsecs_t currentTime = now();
3722 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3723
3724 connection->status = Connection::STATUS_ZOMBIE;
3725 return OK;
3726}
3727
3728void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003729 for (auto it = mMonitoringChannelsByDisplay.begin();
3730 it != mMonitoringChannelsByDisplay.end(); ) {
3731 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3732 const size_t numChannels = monitoringChannels.size();
3733 for (size_t i = 0; i < numChannels; i++) {
3734 if (monitoringChannels[i] == inputChannel) {
3735 monitoringChannels.removeAt(i);
3736 break;
3737 }
3738 }
3739 if (monitoringChannels.empty()) {
3740 it = mMonitoringChannelsByDisplay.erase(it);
3741 } else {
3742 ++it;
3743 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 }
3745}
3746
3747ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003748 if (!inputChannel) {
3749 return -1;
3750 }
3751
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752 ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
3753 if (connectionIndex >= 0) {
3754 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3755 if (connection->inputChannel.get() == inputChannel.get()) {
3756 return connectionIndex;
3757 }
3758 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 return -1;
3760}
3761
3762void InputDispatcher::onDispatchCycleFinishedLocked(
3763 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3764 CommandEntry* commandEntry = postCommandLocked(
3765 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3766 commandEntry->connection = connection;
3767 commandEntry->eventTime = currentTime;
3768 commandEntry->seq = seq;
3769 commandEntry->handled = handled;
3770}
3771
3772void InputDispatcher::onDispatchCycleBrokenLocked(
3773 nsecs_t currentTime, const sp<Connection>& connection) {
3774 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003775 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776
3777 CommandEntry* commandEntry = postCommandLocked(
3778 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3779 commandEntry->connection = connection;
3780}
3781
3782void InputDispatcher::onANRLocked(
3783 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3784 const sp<InputWindowHandle>& windowHandle,
3785 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3786 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3787 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3788 ALOGI("Application is not responding: %s. "
3789 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003790 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 dispatchLatency, waitDuration, reason);
3792
3793 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003794 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 struct tm tm;
3796 localtime_r(&t, &tm);
3797 char timestr[64];
3798 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3799 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003800 mLastANRState += INDENT "ANR:\n";
3801 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3802 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3803 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3804 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3805 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3806 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003807 dumpDispatchStateLocked(mLastANRState);
3808
3809 CommandEntry* commandEntry = postCommandLocked(
3810 & InputDispatcher::doNotifyANRLockedInterruptible);
3811 commandEntry->inputApplicationHandle = applicationHandle;
3812 commandEntry->inputWindowHandle = windowHandle;
3813 commandEntry->reason = reason;
3814}
3815
3816void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3817 CommandEntry* commandEntry) {
3818 mLock.unlock();
3819
3820 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3821
3822 mLock.lock();
3823}
3824
3825void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3826 CommandEntry* commandEntry) {
3827 sp<Connection> connection = commandEntry->connection;
3828
3829 if (connection->status != Connection::STATUS_ZOMBIE) {
3830 mLock.unlock();
3831
3832 mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
3833
3834 mLock.lock();
3835 }
3836}
3837
3838void InputDispatcher::doNotifyANRLockedInterruptible(
3839 CommandEntry* commandEntry) {
3840 mLock.unlock();
3841
3842 nsecs_t newTimeout = mPolicy->notifyANR(
3843 commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle,
3844 commandEntry->reason);
3845
3846 mLock.lock();
3847
3848 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Yi Kong9b14ac62018-07-17 13:48:38 -07003849 commandEntry->inputWindowHandle != nullptr
3850 ? commandEntry->inputWindowHandle->getInputChannel() : nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851}
3852
3853void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3854 CommandEntry* commandEntry) {
3855 KeyEntry* entry = commandEntry->keyEntry;
3856
3857 KeyEvent event;
3858 initializeKeyEvent(&event, entry);
3859
3860 mLock.unlock();
3861
Michael Wright2b3c3302018-03-02 17:19:13 +00003862 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
3864 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003865 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3866 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3867 std::to_string(t.duration().count()).c_str());
3868 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003869
3870 mLock.lock();
3871
3872 if (delay < 0) {
3873 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3874 } else if (!delay) {
3875 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3876 } else {
3877 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3878 entry->interceptKeyWakeupTime = now() + delay;
3879 }
3880 entry->release();
3881}
3882
3883void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3884 CommandEntry* commandEntry) {
3885 sp<Connection> connection = commandEntry->connection;
3886 nsecs_t finishTime = commandEntry->eventTime;
3887 uint32_t seq = commandEntry->seq;
3888 bool handled = commandEntry->handled;
3889
3890 // Handle post-event policy actions.
3891 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3892 if (dispatchEntry) {
3893 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3894 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003895 std::string msg =
3896 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003897 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003899 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 }
3901
3902 bool restartEvent;
3903 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3904 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3905 restartEvent = afterKeyEventLockedInterruptible(connection,
3906 dispatchEntry, keyEntry, handled);
3907 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3908 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3909 restartEvent = afterMotionEventLockedInterruptible(connection,
3910 dispatchEntry, motionEntry, handled);
3911 } else {
3912 restartEvent = false;
3913 }
3914
3915 // Dequeue the event and start the next cycle.
3916 // Note that because the lock might have been released, it is possible that the
3917 // contents of the wait queue to have been drained, so we need to double-check
3918 // a few things.
3919 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
3920 connection->waitQueue.dequeue(dispatchEntry);
3921 traceWaitQueueLengthLocked(connection);
3922 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
3923 connection->outboundQueue.enqueueAtHead(dispatchEntry);
3924 traceOutboundQueueLengthLocked(connection);
3925 } else {
3926 releaseDispatchEntryLocked(dispatchEntry);
3927 }
3928 }
3929
3930 // Start the next dispatch cycle for this connection.
3931 startDispatchCycleLocked(now(), connection);
3932 }
3933}
3934
3935bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
3936 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
3937 if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
3938 // Get the fallback key state.
3939 // Clear it out after dispatching the UP.
3940 int32_t originalKeyCode = keyEntry->keyCode;
3941 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
3942 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
3943 connection->inputState.removeFallbackKey(originalKeyCode);
3944 }
3945
3946 if (handled || !dispatchEntry->hasForegroundTarget()) {
3947 // If the application handles the original key for which we previously
3948 // generated a fallback or if the window is not a foreground window,
3949 // then cancel the associated fallback key, if any.
3950 if (fallbackKeyCode != -1) {
3951 // Dispatch the unhandled key to the policy with the cancel flag.
3952#if DEBUG_OUTBOUND_EVENT_DETAILS
3953 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
3954 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3955 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
3956 keyEntry->policyFlags);
3957#endif
3958 KeyEvent event;
3959 initializeKeyEvent(&event, keyEntry);
3960 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
3961
3962 mLock.unlock();
3963
3964 mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
3965 &event, keyEntry->policyFlags, &event);
3966
3967 mLock.lock();
3968
3969 // Cancel the fallback key.
3970 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
3971 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
3972 "application handled the original non-fallback key "
3973 "or is no longer a foreground target, "
3974 "canceling previously dispatched fallback key");
3975 options.keyCode = fallbackKeyCode;
3976 synthesizeCancelationEventsForConnectionLocked(connection, options);
3977 }
3978 connection->inputState.removeFallbackKey(originalKeyCode);
3979 }
3980 } else {
3981 // If the application did not handle a non-fallback key, first check
3982 // that we are in a good state to perform unhandled key event processing
3983 // Then ask the policy what to do with it.
3984 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
3985 && keyEntry->repeatCount == 0;
3986 if (fallbackKeyCode == -1 && !initialDown) {
3987#if DEBUG_OUTBOUND_EVENT_DETAILS
3988 ALOGD("Unhandled key event: Skipping unhandled key event processing "
3989 "since this is not an initial down. "
3990 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
3991 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
3992 keyEntry->policyFlags);
3993#endif
3994 return false;
3995 }
3996
3997 // Dispatch the unhandled key to the policy.
3998#if DEBUG_OUTBOUND_EVENT_DETAILS
3999 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4000 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4001 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4002 keyEntry->policyFlags);
4003#endif
4004 KeyEvent event;
4005 initializeKeyEvent(&event, keyEntry);
4006
4007 mLock.unlock();
4008
4009 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
4010 &event, keyEntry->policyFlags, &event);
4011
4012 mLock.lock();
4013
4014 if (connection->status != Connection::STATUS_NORMAL) {
4015 connection->inputState.removeFallbackKey(originalKeyCode);
4016 return false;
4017 }
4018
4019 // Latch the fallback keycode for this key on an initial down.
4020 // The fallback keycode cannot change at any other point in the lifecycle.
4021 if (initialDown) {
4022 if (fallback) {
4023 fallbackKeyCode = event.getKeyCode();
4024 } else {
4025 fallbackKeyCode = AKEYCODE_UNKNOWN;
4026 }
4027 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4028 }
4029
4030 ALOG_ASSERT(fallbackKeyCode != -1);
4031
4032 // Cancel the fallback key if the policy decides not to send it anymore.
4033 // We will continue to dispatch the key to the policy but we will no
4034 // longer dispatch a fallback key to the application.
4035 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4036 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4037#if DEBUG_OUTBOUND_EVENT_DETAILS
4038 if (fallback) {
4039 ALOGD("Unhandled key event: Policy requested to send key %d"
4040 "as a fallback for %d, but on the DOWN it had requested "
4041 "to send %d instead. Fallback canceled.",
4042 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4043 } else {
4044 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4045 "but on the DOWN it had requested to send %d. "
4046 "Fallback canceled.",
4047 originalKeyCode, fallbackKeyCode);
4048 }
4049#endif
4050
4051 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4052 "canceling fallback, policy no longer desires it");
4053 options.keyCode = fallbackKeyCode;
4054 synthesizeCancelationEventsForConnectionLocked(connection, options);
4055
4056 fallback = false;
4057 fallbackKeyCode = AKEYCODE_UNKNOWN;
4058 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4059 connection->inputState.setFallbackKey(originalKeyCode,
4060 fallbackKeyCode);
4061 }
4062 }
4063
4064#if DEBUG_OUTBOUND_EVENT_DETAILS
4065 {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004066 std::string msg;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4068 connection->inputState.getFallbackKeys();
4069 for (size_t i = 0; i < fallbackKeys.size(); i++) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004070 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 fallbackKeys.valueAt(i));
4072 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07004073 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004074 fallbackKeys.size(), msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004075 }
4076#endif
4077
4078 if (fallback) {
4079 // Restart the dispatch cycle using the fallback key.
4080 keyEntry->eventTime = event.getEventTime();
4081 keyEntry->deviceId = event.getDeviceId();
4082 keyEntry->source = event.getSource();
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004083 keyEntry->displayId = event.getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004084 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4085 keyEntry->keyCode = fallbackKeyCode;
4086 keyEntry->scanCode = event.getScanCode();
4087 keyEntry->metaState = event.getMetaState();
4088 keyEntry->repeatCount = event.getRepeatCount();
4089 keyEntry->downTime = event.getDownTime();
4090 keyEntry->syntheticRepeat = false;
4091
4092#if DEBUG_OUTBOUND_EVENT_DETAILS
4093 ALOGD("Unhandled key event: Dispatching fallback key. "
4094 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4095 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4096#endif
4097 return true; // restart the event
4098 } else {
4099#if DEBUG_OUTBOUND_EVENT_DETAILS
4100 ALOGD("Unhandled key event: No fallback key.");
4101#endif
4102 }
4103 }
4104 }
4105 return false;
4106}
4107
4108bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4109 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4110 return false;
4111}
4112
4113void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4114 mLock.unlock();
4115
4116 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4117
4118 mLock.lock();
4119}
4120
4121void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004122 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4124 entry->downTime, entry->eventTime);
4125}
4126
4127void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4128 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4129 // TODO Write some statistics about how long we spend waiting.
4130}
4131
4132void InputDispatcher::traceInboundQueueLengthLocked() {
4133 if (ATRACE_ENABLED()) {
4134 ATRACE_INT("iq", mInboundQueue.count());
4135 }
4136}
4137
4138void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4139 if (ATRACE_ENABLED()) {
4140 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004141 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 ATRACE_INT(counterName, connection->outboundQueue.count());
4143 }
4144}
4145
4146void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4147 if (ATRACE_ENABLED()) {
4148 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004149 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150 ATRACE_INT(counterName, connection->waitQueue.count());
4151 }
4152}
4153
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004154void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 AutoMutex _l(mLock);
4156
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004157 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 dumpDispatchStateLocked(dump);
4159
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004160 if (!mLastANRState.empty()) {
4161 dump += "\nInput Dispatcher State at time of last ANR:\n";
4162 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 }
4164}
4165
4166void InputDispatcher::monitor() {
4167 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4168 mLock.lock();
4169 mLooper->wake();
4170 mDispatcherIsAliveCondition.wait(mLock);
4171 mLock.unlock();
4172}
4173
4174
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175// --- InputDispatcher::InjectionState ---
4176
4177InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4178 refCount(1),
4179 injectorPid(injectorPid), injectorUid(injectorUid),
4180 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4181 pendingForegroundDispatches(0) {
4182}
4183
4184InputDispatcher::InjectionState::~InjectionState() {
4185}
4186
4187void InputDispatcher::InjectionState::release() {
4188 refCount -= 1;
4189 if (refCount == 0) {
4190 delete this;
4191 } else {
4192 ALOG_ASSERT(refCount > 0);
4193 }
4194}
4195
4196
4197// --- InputDispatcher::EventEntry ---
4198
4199InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
4200 refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
Yi Kong9b14ac62018-07-17 13:48:38 -07004201 injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202}
4203
4204InputDispatcher::EventEntry::~EventEntry() {
4205 releaseInjectionState();
4206}
4207
4208void InputDispatcher::EventEntry::release() {
4209 refCount -= 1;
4210 if (refCount == 0) {
4211 delete this;
4212 } else {
4213 ALOG_ASSERT(refCount > 0);
4214 }
4215}
4216
4217void InputDispatcher::EventEntry::releaseInjectionState() {
4218 if (injectionState) {
4219 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004220 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 }
4222}
4223
4224
4225// --- InputDispatcher::ConfigurationChangedEntry ---
4226
4227InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
4228 EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
4229}
4230
4231InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4232}
4233
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004234void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4235 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236}
4237
4238
4239// --- InputDispatcher::DeviceResetEntry ---
4240
4241InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
4242 EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
4243 deviceId(deviceId) {
4244}
4245
4246InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4247}
4248
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004249void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4250 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 deviceId, policyFlags);
4252}
4253
4254
4255// --- InputDispatcher::KeyEntry ---
4256
4257InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004258 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4260 int32_t repeatCount, nsecs_t downTime) :
4261 EventEntry(TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004262 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4264 repeatCount(repeatCount), downTime(downTime),
4265 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4266 interceptKeyWakeupTime(0) {
4267}
4268
4269InputDispatcher::KeyEntry::~KeyEntry() {
4270}
4271
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004272void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004273 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4275 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004276 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004277 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278}
4279
4280void InputDispatcher::KeyEntry::recycle() {
4281 releaseInjectionState();
4282
4283 dispatchInProgress = false;
4284 syntheticRepeat = false;
4285 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4286 interceptKeyWakeupTime = 0;
4287}
4288
4289
4290// --- InputDispatcher::MotionEntry ---
4291
Michael Wright7b159c92015-05-14 14:48:03 +01004292InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004293 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4294 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004295 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4296 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004297 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004298 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4299 float xOffset, float yOffset) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300 EventEntry(TYPE_MOTION, eventTime, policyFlags),
4301 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004302 deviceId(deviceId), source(source), displayId(displayId), action(action),
4303 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004304 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004305 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306 for (uint32_t i = 0; i < pointerCount; i++) {
4307 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4308 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004309 if (xOffset || yOffset) {
4310 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312 }
4313}
4314
4315InputDispatcher::MotionEntry::~MotionEntry() {
4316}
4317
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004318void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004319 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004320 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004321 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004322 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4323 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4324
Michael Wrightd02c5b62014-02-10 15:10:22 -08004325 for (uint32_t i = 0; i < pointerCount; i++) {
4326 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004327 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004329 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 pointerCoords[i].getX(), pointerCoords[i].getY());
4331 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004332 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333}
4334
4335
4336// --- InputDispatcher::DispatchEntry ---
4337
4338volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4339
4340InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
4341 int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
4342 seq(nextSeq()),
4343 eventEntry(eventEntry), targetFlags(targetFlags),
4344 xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
4345 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4346 eventEntry->refCount += 1;
4347}
4348
4349InputDispatcher::DispatchEntry::~DispatchEntry() {
4350 eventEntry->release();
4351}
4352
4353uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4354 // Sequence number 0 is reserved and will never be returned.
4355 uint32_t seq;
4356 do {
4357 seq = android_atomic_inc(&sNextSeqAtomic);
4358 } while (!seq);
4359 return seq;
4360}
4361
4362
4363// --- InputDispatcher::InputState ---
4364
4365InputDispatcher::InputState::InputState() {
4366}
4367
4368InputDispatcher::InputState::~InputState() {
4369}
4370
4371bool InputDispatcher::InputState::isNeutral() const {
4372 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4373}
4374
4375bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4376 int32_t displayId) const {
4377 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4378 const MotionMemento& memento = mMotionMementos.itemAt(i);
4379 if (memento.deviceId == deviceId
4380 && memento.source == source
4381 && memento.displayId == displayId
4382 && memento.hovering) {
4383 return true;
4384 }
4385 }
4386 return false;
4387}
4388
4389bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4390 int32_t action, int32_t flags) {
4391 switch (action) {
4392 case AKEY_EVENT_ACTION_UP: {
4393 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4394 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4395 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4396 mFallbackKeys.removeItemsAt(i);
4397 } else {
4398 i += 1;
4399 }
4400 }
4401 }
4402 ssize_t index = findKeyMemento(entry);
4403 if (index >= 0) {
4404 mKeyMementos.removeAt(index);
4405 return true;
4406 }
4407 /* FIXME: We can't just drop the key up event because that prevents creating
4408 * popup windows that are automatically shown when a key is held and then
4409 * dismissed when the key is released. The problem is that the popup will
4410 * not have received the original key down, so the key up will be considered
4411 * to be inconsistent with its observed state. We could perhaps handle this
4412 * by synthesizing a key down but that will cause other problems.
4413 *
4414 * So for now, allow inconsistent key up events to be dispatched.
4415 *
4416#if DEBUG_OUTBOUND_EVENT_DETAILS
4417 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4418 "keyCode=%d, scanCode=%d",
4419 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4420#endif
4421 return false;
4422 */
4423 return true;
4424 }
4425
4426 case AKEY_EVENT_ACTION_DOWN: {
4427 ssize_t index = findKeyMemento(entry);
4428 if (index >= 0) {
4429 mKeyMementos.removeAt(index);
4430 }
4431 addKeyMemento(entry, flags);
4432 return true;
4433 }
4434
4435 default:
4436 return true;
4437 }
4438}
4439
4440bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4441 int32_t action, int32_t flags) {
4442 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4443 switch (actionMasked) {
4444 case AMOTION_EVENT_ACTION_UP:
4445 case AMOTION_EVENT_ACTION_CANCEL: {
4446 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4447 if (index >= 0) {
4448 mMotionMementos.removeAt(index);
4449 return true;
4450 }
4451#if DEBUG_OUTBOUND_EVENT_DETAILS
4452 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004453 "displayId=%" PRId32 ", actionMasked=%d",
4454 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455#endif
4456 return false;
4457 }
4458
4459 case AMOTION_EVENT_ACTION_DOWN: {
4460 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4461 if (index >= 0) {
4462 mMotionMementos.removeAt(index);
4463 }
4464 addMotionMemento(entry, flags, false /*hovering*/);
4465 return true;
4466 }
4467
4468 case AMOTION_EVENT_ACTION_POINTER_UP:
4469 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4470 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004471 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4472 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4473 // generate cancellation events for these since they're based in relative rather than
4474 // absolute units.
4475 return true;
4476 }
4477
Michael Wrightd02c5b62014-02-10 15:10:22 -08004478 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004479
4480 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4481 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4482 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4483 // other value and we need to track the motion so we can send cancellation events for
4484 // anything generating fallback events (e.g. DPad keys for joystick movements).
4485 if (index >= 0) {
4486 if (entry->pointerCoords[0].isEmpty()) {
4487 mMotionMementos.removeAt(index);
4488 } else {
4489 MotionMemento& memento = mMotionMementos.editItemAt(index);
4490 memento.setPointers(entry);
4491 }
4492 } else if (!entry->pointerCoords[0].isEmpty()) {
4493 addMotionMemento(entry, flags, false /*hovering*/);
4494 }
4495
4496 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4497 return true;
4498 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499 if (index >= 0) {
4500 MotionMemento& memento = mMotionMementos.editItemAt(index);
4501 memento.setPointers(entry);
4502 return true;
4503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004504#if DEBUG_OUTBOUND_EVENT_DETAILS
4505 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004506 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4507 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004508#endif
4509 return false;
4510 }
4511
4512 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4513 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4514 if (index >= 0) {
4515 mMotionMementos.removeAt(index);
4516 return true;
4517 }
4518#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004519 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4520 "displayId=%" PRId32,
4521 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522#endif
4523 return false;
4524 }
4525
4526 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4527 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4528 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4529 if (index >= 0) {
4530 mMotionMementos.removeAt(index);
4531 }
4532 addMotionMemento(entry, flags, true /*hovering*/);
4533 return true;
4534 }
4535
4536 default:
4537 return true;
4538 }
4539}
4540
4541ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4542 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4543 const KeyMemento& memento = mKeyMementos.itemAt(i);
4544 if (memento.deviceId == entry->deviceId
4545 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004546 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004547 && memento.keyCode == entry->keyCode
4548 && memento.scanCode == entry->scanCode) {
4549 return i;
4550 }
4551 }
4552 return -1;
4553}
4554
4555ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4556 bool hovering) const {
4557 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4558 const MotionMemento& memento = mMotionMementos.itemAt(i);
4559 if (memento.deviceId == entry->deviceId
4560 && memento.source == entry->source
4561 && memento.displayId == entry->displayId
4562 && memento.hovering == hovering) {
4563 return i;
4564 }
4565 }
4566 return -1;
4567}
4568
4569void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4570 mKeyMementos.push();
4571 KeyMemento& memento = mKeyMementos.editTop();
4572 memento.deviceId = entry->deviceId;
4573 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004574 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575 memento.keyCode = entry->keyCode;
4576 memento.scanCode = entry->scanCode;
4577 memento.metaState = entry->metaState;
4578 memento.flags = flags;
4579 memento.downTime = entry->downTime;
4580 memento.policyFlags = entry->policyFlags;
4581}
4582
4583void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4584 int32_t flags, bool hovering) {
4585 mMotionMementos.push();
4586 MotionMemento& memento = mMotionMementos.editTop();
4587 memento.deviceId = entry->deviceId;
4588 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004589 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004590 memento.flags = flags;
4591 memento.xPrecision = entry->xPrecision;
4592 memento.yPrecision = entry->yPrecision;
4593 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004594 memento.setPointers(entry);
4595 memento.hovering = hovering;
4596 memento.policyFlags = entry->policyFlags;
4597}
4598
4599void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4600 pointerCount = entry->pointerCount;
4601 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4602 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4603 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4604 }
4605}
4606
4607void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4608 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4609 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4610 const KeyMemento& memento = mKeyMementos.itemAt(i);
4611 if (shouldCancelKey(memento, options)) {
4612 outEvents.push(new KeyEntry(currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004613 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4615 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4616 }
4617 }
4618
4619 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4620 const MotionMemento& memento = mMotionMementos.itemAt(i);
4621 if (shouldCancelMotion(memento, options)) {
4622 outEvents.push(new MotionEntry(currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004623 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 memento.hovering
4625 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4626 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004627 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004629 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4630 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631 }
4632 }
4633}
4634
4635void InputDispatcher::InputState::clear() {
4636 mKeyMementos.clear();
4637 mMotionMementos.clear();
4638 mFallbackKeys.clear();
4639}
4640
4641void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4642 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4643 const MotionMemento& memento = mMotionMementos.itemAt(i);
4644 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4645 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4646 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4647 if (memento.deviceId == otherMemento.deviceId
4648 && memento.source == otherMemento.source
4649 && memento.displayId == otherMemento.displayId) {
4650 other.mMotionMementos.removeAt(j);
4651 } else {
4652 j += 1;
4653 }
4654 }
4655 other.mMotionMementos.push(memento);
4656 }
4657 }
4658}
4659
4660int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4661 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4662 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4663}
4664
4665void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4666 int32_t fallbackKeyCode) {
4667 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4668 if (index >= 0) {
4669 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4670 } else {
4671 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4672 }
4673}
4674
4675void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4676 mFallbackKeys.removeItem(originalKeyCode);
4677}
4678
4679bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4680 const CancelationOptions& options) {
4681 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4682 return false;
4683 }
4684
4685 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4686 return false;
4687 }
4688
4689 switch (options.mode) {
4690 case CancelationOptions::CANCEL_ALL_EVENTS:
4691 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4692 return true;
4693 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4694 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004695 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4696 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697 default:
4698 return false;
4699 }
4700}
4701
4702bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4703 const CancelationOptions& options) {
4704 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4705 return false;
4706 }
4707
4708 switch (options.mode) {
4709 case CancelationOptions::CANCEL_ALL_EVENTS:
4710 return true;
4711 case CancelationOptions::CANCEL_POINTER_EVENTS:
4712 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4713 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4714 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004715 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4716 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 default:
4718 return false;
4719 }
4720}
4721
4722
4723// --- InputDispatcher::Connection ---
4724
4725InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
4726 const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
4727 status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
4728 monitor(monitor),
4729 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4730}
4731
4732InputDispatcher::Connection::~Connection() {
4733}
4734
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004735const std::string InputDispatcher::Connection::getWindowName() const {
Yi Kong9b14ac62018-07-17 13:48:38 -07004736 if (inputWindowHandle != nullptr) {
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004737 return inputWindowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738 }
4739 if (monitor) {
4740 return "monitor";
4741 }
4742 return "?";
4743}
4744
4745const char* InputDispatcher::Connection::getStatusLabel() const {
4746 switch (status) {
4747 case STATUS_NORMAL:
4748 return "NORMAL";
4749
4750 case STATUS_BROKEN:
4751 return "BROKEN";
4752
4753 case STATUS_ZOMBIE:
4754 return "ZOMBIE";
4755
4756 default:
4757 return "UNKNOWN";
4758 }
4759}
4760
4761InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004762 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763 if (entry->seq == seq) {
4764 return entry;
4765 }
4766 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004767 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768}
4769
4770
4771// --- InputDispatcher::CommandEntry ---
4772
4773InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004774 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 seq(0), handled(false) {
4776}
4777
4778InputDispatcher::CommandEntry::~CommandEntry() {
4779}
4780
4781
4782// --- InputDispatcher::TouchState ---
4783
4784InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004785 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786}
4787
4788InputDispatcher::TouchState::~TouchState() {
4789}
4790
4791void InputDispatcher::TouchState::reset() {
4792 down = false;
4793 split = false;
4794 deviceId = -1;
4795 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004796 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 windows.clear();
4798}
4799
4800void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4801 down = other.down;
4802 split = other.split;
4803 deviceId = other.deviceId;
4804 source = other.source;
4805 displayId = other.displayId;
4806 windows = other.windows;
4807}
4808
4809void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4810 int32_t targetFlags, BitSet32 pointerIds) {
4811 if (targetFlags & InputTarget::FLAG_SPLIT) {
4812 split = true;
4813 }
4814
4815 for (size_t i = 0; i < windows.size(); i++) {
4816 TouchedWindow& touchedWindow = windows.editItemAt(i);
4817 if (touchedWindow.windowHandle == windowHandle) {
4818 touchedWindow.targetFlags |= targetFlags;
4819 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4820 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4821 }
4822 touchedWindow.pointerIds.value |= pointerIds.value;
4823 return;
4824 }
4825 }
4826
4827 windows.push();
4828
4829 TouchedWindow& touchedWindow = windows.editTop();
4830 touchedWindow.windowHandle = windowHandle;
4831 touchedWindow.targetFlags = targetFlags;
4832 touchedWindow.pointerIds = pointerIds;
4833}
4834
4835void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4836 for (size_t i = 0; i < windows.size(); i++) {
4837 if (windows.itemAt(i).windowHandle == windowHandle) {
4838 windows.removeAt(i);
4839 return;
4840 }
4841 }
4842}
4843
4844void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4845 for (size_t i = 0 ; i < windows.size(); ) {
4846 TouchedWindow& window = windows.editItemAt(i);
4847 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4848 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4849 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4850 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4851 i += 1;
4852 } else {
4853 windows.removeAt(i);
4854 }
4855 }
4856}
4857
4858sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4859 for (size_t i = 0; i < windows.size(); i++) {
4860 const TouchedWindow& window = windows.itemAt(i);
4861 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4862 return window.windowHandle;
4863 }
4864 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004865 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866}
4867
4868bool InputDispatcher::TouchState::isSlippery() const {
4869 // Must have exactly one foreground window.
4870 bool haveSlipperyForegroundWindow = false;
4871 for (size_t i = 0; i < windows.size(); i++) {
4872 const TouchedWindow& window = windows.itemAt(i);
4873 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4874 if (haveSlipperyForegroundWindow
4875 || !(window.windowHandle->getInfo()->layoutParamsFlags
4876 & InputWindowInfo::FLAG_SLIPPERY)) {
4877 return false;
4878 }
4879 haveSlipperyForegroundWindow = true;
4880 }
4881 }
4882 return haveSlipperyForegroundWindow;
4883}
4884
4885
4886// --- InputDispatcherThread ---
4887
4888InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4889 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4890}
4891
4892InputDispatcherThread::~InputDispatcherThread() {
4893}
4894
4895bool InputDispatcherThread::threadLoop() {
4896 mDispatcher->dispatchOnce();
4897 return true;
4898}
4899
4900} // namespace android