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