blob: 7fa9cb60d634f4c910be6f0551b3e2697dda5ed4 [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
Prabir Pradhan42611e02018-11-27 14:04:02 -0800100// Sequence number for synthesized or injected events.
101constexpr uint32_t SYNTHESIZED_EVENT_SEQUENCE_NUM = 0;
102
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
104static inline nsecs_t now() {
105 return systemTime(SYSTEM_TIME_MONOTONIC);
106}
107
108static inline const char* toString(bool value) {
109 return value ? "true" : "false";
110}
111
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800112static std::string motionActionToString(int32_t action) {
113 // Convert MotionEvent action to string
114 switch(action & AMOTION_EVENT_ACTION_MASK) {
115 case AMOTION_EVENT_ACTION_DOWN:
116 return "DOWN";
117 case AMOTION_EVENT_ACTION_MOVE:
118 return "MOVE";
119 case AMOTION_EVENT_ACTION_UP:
120 return "UP";
121 case AMOTION_EVENT_ACTION_POINTER_DOWN:
122 return "POINTER_DOWN";
123 case AMOTION_EVENT_ACTION_POINTER_UP:
124 return "POINTER_UP";
125 }
126 return StringPrintf("%" PRId32, action);
127}
128
129static std::string keyActionToString(int32_t action) {
130 // Convert KeyEvent action to string
131 switch(action) {
132 case AKEY_EVENT_ACTION_DOWN:
133 return "DOWN";
134 case AKEY_EVENT_ACTION_UP:
135 return "UP";
136 case AKEY_EVENT_ACTION_MULTIPLE:
137 return "MULTIPLE";
138 }
139 return StringPrintf("%" PRId32, action);
140}
141
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
143 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
144 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
145}
146
147static bool isValidKeyAction(int32_t action) {
148 switch (action) {
149 case AKEY_EVENT_ACTION_DOWN:
150 case AKEY_EVENT_ACTION_UP:
151 return true;
152 default:
153 return false;
154 }
155}
156
157static bool validateKeyEvent(int32_t action) {
158 if (! isValidKeyAction(action)) {
159 ALOGE("Key event has invalid action code 0x%x", action);
160 return false;
161 }
162 return true;
163}
164
Michael Wright7b159c92015-05-14 14:48:03 +0100165static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 switch (action & AMOTION_EVENT_ACTION_MASK) {
167 case AMOTION_EVENT_ACTION_DOWN:
168 case AMOTION_EVENT_ACTION_UP:
169 case AMOTION_EVENT_ACTION_CANCEL:
170 case AMOTION_EVENT_ACTION_MOVE:
171 case AMOTION_EVENT_ACTION_OUTSIDE:
172 case AMOTION_EVENT_ACTION_HOVER_ENTER:
173 case AMOTION_EVENT_ACTION_HOVER_MOVE:
174 case AMOTION_EVENT_ACTION_HOVER_EXIT:
175 case AMOTION_EVENT_ACTION_SCROLL:
176 return true;
177 case AMOTION_EVENT_ACTION_POINTER_DOWN:
178 case AMOTION_EVENT_ACTION_POINTER_UP: {
179 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800180 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 }
Michael Wright7b159c92015-05-14 14:48:03 +0100182 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
183 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
184 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 default:
186 return false;
187 }
188}
189
Michael Wright7b159c92015-05-14 14:48:03 +0100190static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100192 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800193 ALOGE("Motion event has invalid action code 0x%x", action);
194 return false;
195 }
196 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000197 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800198 pointerCount, MAX_POINTERS);
199 return false;
200 }
201 BitSet32 pointerIdBits;
202 for (size_t i = 0; i < pointerCount; i++) {
203 int32_t id = pointerProperties[i].id;
204 if (id < 0 || id > MAX_POINTER_ID) {
205 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
206 id, MAX_POINTER_ID);
207 return false;
208 }
209 if (pointerIdBits.hasBit(id)) {
210 ALOGE("Motion event has duplicate pointer id %d", id);
211 return false;
212 }
213 pointerIdBits.markBit(id);
214 }
215 return true;
216}
217
218static bool isMainDisplay(int32_t displayId) {
219 return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
220}
221
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800222static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800224 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800225 return;
226 }
227
228 bool first = true;
229 Region::const_iterator cur = region.begin();
230 Region::const_iterator const tail = region.end();
231 while (cur != tail) {
232 if (first) {
233 first = false;
234 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800235 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800237 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800238 cur++;
239 }
240}
241
Tiger Huang721e26f2018-07-24 22:26:19 +0800242template<typename T, typename U>
243static T getValueByKey(std::unordered_map<U, T>& map, U key) {
244 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
245 return it != map.end() ? it->second : T{};
246}
247
Michael Wrightd02c5b62014-02-10 15:10:22 -0800248
249// --- InputDispatcher ---
250
251InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
252 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700253 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100254 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700255 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800257 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
259 mLooper = new Looper(false);
260
Yi Kong9b14ac62018-07-17 13:48:38 -0700261 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262
263 policy->getDispatcherConfiguration(&mConfig);
264}
265
266InputDispatcher::~InputDispatcher() {
267 { // acquire lock
268 AutoMutex _l(mLock);
269
270 resetKeyRepeatLocked();
271 releasePendingEventLocked();
272 drainInboundQueueLocked();
273 }
274
275 while (mConnectionsByFd.size() != 0) {
276 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
277 }
278}
279
280void InputDispatcher::dispatchOnce() {
281 nsecs_t nextWakeupTime = LONG_LONG_MAX;
282 { // acquire lock
283 AutoMutex _l(mLock);
284 mDispatcherIsAliveCondition.broadcast();
285
286 // Run a dispatch loop if there are no pending commands.
287 // The dispatch loop might enqueue commands to run afterwards.
288 if (!haveCommandsLocked()) {
289 dispatchOnceInnerLocked(&nextWakeupTime);
290 }
291
292 // Run all pending commands if there are any.
293 // If any commands were run then force the next poll to wake up immediately.
294 if (runCommandsLockedInterruptible()) {
295 nextWakeupTime = LONG_LONG_MIN;
296 }
297 } // release lock
298
299 // Wait for callback or timeout or wake. (make sure we round up, not down)
300 nsecs_t currentTime = now();
301 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
302 mLooper->pollOnce(timeoutMillis);
303}
304
305void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
306 nsecs_t currentTime = now();
307
Jeff Browndc5992e2014-04-11 01:27:26 -0700308 // Reset the key repeat timer whenever normal dispatch is suspended while the
309 // device is in a non-interactive state. This is to ensure that we abort a key
310 // repeat if the device is just coming out of sleep.
311 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800312 resetKeyRepeatLocked();
313 }
314
315 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
316 if (mDispatchFrozen) {
317#if DEBUG_FOCUS
318 ALOGD("Dispatch frozen. Waiting some more.");
319#endif
320 return;
321 }
322
323 // Optimize latency of app switches.
324 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
325 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
326 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
327 if (mAppSwitchDueTime < *nextWakeupTime) {
328 *nextWakeupTime = mAppSwitchDueTime;
329 }
330
331 // Ready to start a new event.
332 // If we don't already have a pending event, go grab one.
333 if (! mPendingEvent) {
334 if (mInboundQueue.isEmpty()) {
335 if (isAppSwitchDue) {
336 // The inbound queue is empty so the app switch key we were waiting
337 // for will never arrive. Stop waiting for it.
338 resetPendingAppSwitchLocked(false);
339 isAppSwitchDue = false;
340 }
341
342 // Synthesize a key repeat if appropriate.
343 if (mKeyRepeatState.lastKeyEntry) {
344 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
345 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
346 } else {
347 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
348 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
349 }
350 }
351 }
352
353 // Nothing to do if there is no pending event.
354 if (!mPendingEvent) {
355 return;
356 }
357 } else {
358 // Inbound queue has at least one entry.
359 mPendingEvent = mInboundQueue.dequeueAtHead();
360 traceInboundQueueLengthLocked();
361 }
362
363 // Poke user activity for this event.
364 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
365 pokeUserActivityLocked(mPendingEvent);
366 }
367
368 // Get ready to dispatch the event.
369 resetANRTimeoutsLocked();
370 }
371
372 // Now we have an event to dispatch.
373 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700374 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800375 bool done = false;
376 DropReason dropReason = DROP_REASON_NOT_DROPPED;
377 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
378 dropReason = DROP_REASON_POLICY;
379 } else if (!mDispatchEnabled) {
380 dropReason = DROP_REASON_DISABLED;
381 }
382
383 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700384 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800385 }
386
387 switch (mPendingEvent->type) {
388 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
389 ConfigurationChangedEntry* typedEntry =
390 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
391 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
392 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
393 break;
394 }
395
396 case EventEntry::TYPE_DEVICE_RESET: {
397 DeviceResetEntry* typedEntry =
398 static_cast<DeviceResetEntry*>(mPendingEvent);
399 done = dispatchDeviceResetLocked(currentTime, typedEntry);
400 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
401 break;
402 }
403
404 case EventEntry::TYPE_KEY: {
405 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
406 if (isAppSwitchDue) {
407 if (isAppSwitchKeyEventLocked(typedEntry)) {
408 resetPendingAppSwitchLocked(true);
409 isAppSwitchDue = false;
410 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
411 dropReason = DROP_REASON_APP_SWITCH;
412 }
413 }
414 if (dropReason == DROP_REASON_NOT_DROPPED
415 && isStaleEventLocked(currentTime, typedEntry)) {
416 dropReason = DROP_REASON_STALE;
417 }
418 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
419 dropReason = DROP_REASON_BLOCKED;
420 }
421 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
422 break;
423 }
424
425 case EventEntry::TYPE_MOTION: {
426 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
427 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
428 dropReason = DROP_REASON_APP_SWITCH;
429 }
430 if (dropReason == DROP_REASON_NOT_DROPPED
431 && isStaleEventLocked(currentTime, typedEntry)) {
432 dropReason = DROP_REASON_STALE;
433 }
434 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
435 dropReason = DROP_REASON_BLOCKED;
436 }
437 done = dispatchMotionLocked(currentTime, typedEntry,
438 &dropReason, nextWakeupTime);
439 break;
440 }
441
442 default:
443 ALOG_ASSERT(false);
444 break;
445 }
446
447 if (done) {
448 if (dropReason != DROP_REASON_NOT_DROPPED) {
449 dropInboundEventLocked(mPendingEvent, dropReason);
450 }
Michael Wright3a981722015-06-10 15:26:13 +0100451 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452
453 releasePendingEventLocked();
454 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
455 }
456}
457
458bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
459 bool needWake = mInboundQueue.isEmpty();
460 mInboundQueue.enqueueAtTail(entry);
461 traceInboundQueueLengthLocked();
462
463 switch (entry->type) {
464 case EventEntry::TYPE_KEY: {
465 // Optimize app switch latency.
466 // If the application takes too long to catch up then we drop all events preceding
467 // the app switch key.
468 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
469 if (isAppSwitchKeyEventLocked(keyEntry)) {
470 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
471 mAppSwitchSawKeyDown = true;
472 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
473 if (mAppSwitchSawKeyDown) {
474#if DEBUG_APP_SWITCH
475 ALOGD("App switch is pending!");
476#endif
477 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
478 mAppSwitchSawKeyDown = false;
479 needWake = true;
480 }
481 }
482 }
483 break;
484 }
485
486 case EventEntry::TYPE_MOTION: {
487 // Optimize case where the current application is unresponsive and the user
488 // decides to touch a window in a different application.
489 // If the application takes too long to catch up then we drop all events preceding
490 // the touch into the other window.
491 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
492 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
493 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
494 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Robert Carr740167f2018-10-11 19:03:41 -0700495 && mInputTargetWaitApplicationToken != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496 int32_t displayId = motionEntry->displayId;
497 int32_t x = int32_t(motionEntry->pointerCoords[0].
498 getAxisValue(AMOTION_EVENT_AXIS_X));
499 int32_t y = int32_t(motionEntry->pointerCoords[0].
500 getAxisValue(AMOTION_EVENT_AXIS_Y));
501 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700502 if (touchedWindowHandle != nullptr
Robert Carr740167f2018-10-11 19:03:41 -0700503 && touchedWindowHandle->getApplicationToken()
504 != mInputTargetWaitApplicationToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 // User touched a different application than the one we are waiting on.
506 // Flag the event, and start pruning the input queue.
507 mNextUnblockedEvent = motionEntry;
508 needWake = true;
509 }
510 }
511 break;
512 }
513 }
514
515 return needWake;
516}
517
518void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
519 entry->refCount += 1;
520 mRecentQueue.enqueueAtTail(entry);
521 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
522 mRecentQueue.dequeueAtHead()->release();
523 }
524}
525
526sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
527 int32_t x, int32_t y) {
528 // Traverse windows from front to back to find touched window.
Arthur Hungb92218b2018-08-14 12:00:21 +0800529 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
530 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800532 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533 const InputWindowInfo* windowInfo = windowHandle->getInfo();
534 if (windowInfo->displayId == displayId) {
535 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800536
537 if (windowInfo->visible) {
538 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
539 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
540 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
541 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
542 // Found window.
543 return windowHandle;
544 }
545 }
546 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547 }
548 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700549 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550}
551
552void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
553 const char* reason;
554 switch (dropReason) {
555 case DROP_REASON_POLICY:
556#if DEBUG_INBOUND_EVENT_DETAILS
557 ALOGD("Dropped event because policy consumed it.");
558#endif
559 reason = "inbound event was dropped because the policy consumed it";
560 break;
561 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100562 if (mLastDropReason != DROP_REASON_DISABLED) {
563 ALOGI("Dropped event because input dispatch is disabled.");
564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565 reason = "inbound event was dropped because input dispatch is disabled";
566 break;
567 case DROP_REASON_APP_SWITCH:
568 ALOGI("Dropped event because of pending overdue app switch.");
569 reason = "inbound event was dropped because of pending overdue app switch";
570 break;
571 case DROP_REASON_BLOCKED:
572 ALOGI("Dropped event because the current application is not responding and the user "
573 "has started interacting with a different application.");
574 reason = "inbound event was dropped because the current application is not responding "
575 "and the user has started interacting with a different application";
576 break;
577 case DROP_REASON_STALE:
578 ALOGI("Dropped event because it is stale.");
579 reason = "inbound event was dropped because it is stale";
580 break;
581 default:
582 ALOG_ASSERT(false);
583 return;
584 }
585
586 switch (entry->type) {
587 case EventEntry::TYPE_KEY: {
588 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
589 synthesizeCancelationEventsForAllConnectionsLocked(options);
590 break;
591 }
592 case EventEntry::TYPE_MOTION: {
593 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
594 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
595 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
596 synthesizeCancelationEventsForAllConnectionsLocked(options);
597 } else {
598 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
599 synthesizeCancelationEventsForAllConnectionsLocked(options);
600 }
601 break;
602 }
603 }
604}
605
606bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
607 return keyCode == AKEYCODE_HOME
608 || keyCode == AKEYCODE_ENDCALL
609 || keyCode == AKEYCODE_APP_SWITCH;
610}
611
612bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
613 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
614 && isAppSwitchKeyCode(keyEntry->keyCode)
615 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
616 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
617}
618
619bool InputDispatcher::isAppSwitchPendingLocked() {
620 return mAppSwitchDueTime != LONG_LONG_MAX;
621}
622
623void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
624 mAppSwitchDueTime = LONG_LONG_MAX;
625
626#if DEBUG_APP_SWITCH
627 if (handled) {
628 ALOGD("App switch has arrived.");
629 } else {
630 ALOGD("App switch was abandoned.");
631 }
632#endif
633}
634
635bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
636 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
637}
638
639bool InputDispatcher::haveCommandsLocked() const {
640 return !mCommandQueue.isEmpty();
641}
642
643bool InputDispatcher::runCommandsLockedInterruptible() {
644 if (mCommandQueue.isEmpty()) {
645 return false;
646 }
647
648 do {
649 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
650
651 Command command = commandEntry->command;
652 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
653
654 commandEntry->connection.clear();
655 delete commandEntry;
656 } while (! mCommandQueue.isEmpty());
657 return true;
658}
659
660InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
661 CommandEntry* commandEntry = new CommandEntry(command);
662 mCommandQueue.enqueueAtTail(commandEntry);
663 return commandEntry;
664}
665
666void InputDispatcher::drainInboundQueueLocked() {
667 while (! mInboundQueue.isEmpty()) {
668 EventEntry* entry = mInboundQueue.dequeueAtHead();
669 releaseInboundEventLocked(entry);
670 }
671 traceInboundQueueLengthLocked();
672}
673
674void InputDispatcher::releasePendingEventLocked() {
675 if (mPendingEvent) {
676 resetANRTimeoutsLocked();
677 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700678 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679 }
680}
681
682void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
683 InjectionState* injectionState = entry->injectionState;
684 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
685#if DEBUG_DISPATCH_CYCLE
686 ALOGD("Injected inbound event was dropped.");
687#endif
688 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
689 }
690 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700691 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 }
693 addRecentEventLocked(entry);
694 entry->release();
695}
696
697void InputDispatcher::resetKeyRepeatLocked() {
698 if (mKeyRepeatState.lastKeyEntry) {
699 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700700 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800701 }
702}
703
704InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
705 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
706
707 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700708 uint32_t policyFlags = entry->policyFlags &
709 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800710 if (entry->refCount == 1) {
711 entry->recycle();
712 entry->eventTime = currentTime;
713 entry->policyFlags = policyFlags;
714 entry->repeatCount += 1;
715 } else {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800716 KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100717 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 entry->action, entry->flags, entry->keyCode, entry->scanCode,
719 entry->metaState, entry->repeatCount + 1, entry->downTime);
720
721 mKeyRepeatState.lastKeyEntry = newEntry;
722 entry->release();
723
724 entry = newEntry;
725 }
726 entry->syntheticRepeat = true;
727
728 // Increment reference count since we keep a reference to the event in
729 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
730 entry->refCount += 1;
731
732 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
733 return entry;
734}
735
736bool InputDispatcher::dispatchConfigurationChangedLocked(
737 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
738#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700739 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740#endif
741
742 // Reset key repeating in case a keyboard device was added or removed or something.
743 resetKeyRepeatLocked();
744
745 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
746 CommandEntry* commandEntry = postCommandLocked(
747 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
748 commandEntry->eventTime = entry->eventTime;
749 return true;
750}
751
752bool InputDispatcher::dispatchDeviceResetLocked(
753 nsecs_t currentTime, DeviceResetEntry* entry) {
754#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700755 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
756 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757#endif
758
759 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
760 "device was reset");
761 options.deviceId = entry->deviceId;
762 synthesizeCancelationEventsForAllConnectionsLocked(options);
763 return true;
764}
765
766bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
767 DropReason* dropReason, nsecs_t* nextWakeupTime) {
768 // Preprocessing.
769 if (! entry->dispatchInProgress) {
770 if (entry->repeatCount == 0
771 && entry->action == AKEY_EVENT_ACTION_DOWN
772 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
773 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
774 if (mKeyRepeatState.lastKeyEntry
775 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
776 // We have seen two identical key downs in a row which indicates that the device
777 // driver is automatically generating key repeats itself. We take note of the
778 // repeat here, but we disable our own next key repeat timer since it is clear that
779 // we will not need to synthesize key repeats ourselves.
780 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
781 resetKeyRepeatLocked();
782 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
783 } else {
784 // Not a repeat. Save key down state in case we do see a repeat later.
785 resetKeyRepeatLocked();
786 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
787 }
788 mKeyRepeatState.lastKeyEntry = entry;
789 entry->refCount += 1;
790 } else if (! entry->syntheticRepeat) {
791 resetKeyRepeatLocked();
792 }
793
794 if (entry->repeatCount == 1) {
795 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
796 } else {
797 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
798 }
799
800 entry->dispatchInProgress = true;
801
802 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
803 }
804
805 // Handle case where the policy asked us to try again later last time.
806 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
807 if (currentTime < entry->interceptKeyWakeupTime) {
808 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
809 *nextWakeupTime = entry->interceptKeyWakeupTime;
810 }
811 return false; // wait until next wakeup
812 }
813 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
814 entry->interceptKeyWakeupTime = 0;
815 }
816
817 // Give the policy a chance to intercept the key.
818 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
819 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
820 CommandEntry* commandEntry = postCommandLocked(
821 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800822 sp<InputWindowHandle> focusedWindowHandle =
823 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
824 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700825 commandEntry->inputChannel =
826 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 }
828 commandEntry->keyEntry = entry;
829 entry->refCount += 1;
830 return false; // wait for the command to run
831 } else {
832 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
833 }
834 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
835 if (*dropReason == DROP_REASON_NOT_DROPPED) {
836 *dropReason = DROP_REASON_POLICY;
837 }
838 }
839
840 // Clean up if dropping the event.
841 if (*dropReason != DROP_REASON_NOT_DROPPED) {
842 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
843 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
844 return true;
845 }
846
847 // Identify targets.
848 Vector<InputTarget> inputTargets;
849 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
850 entry, inputTargets, nextWakeupTime);
851 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
852 return false;
853 }
854
855 setInjectionResultLocked(entry, injectionResult);
856 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
857 return true;
858 }
859
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800860 // Add monitor channels from event's or focused display.
861 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862
863 // Dispatch the key.
864 dispatchEventLocked(currentTime, entry, inputTargets);
865 return true;
866}
867
868void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
869#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100870 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
871 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800872 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100874 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800876 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877#endif
878}
879
880bool InputDispatcher::dispatchMotionLocked(
881 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
882 // Preprocessing.
883 if (! entry->dispatchInProgress) {
884 entry->dispatchInProgress = true;
885
886 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
887 }
888
889 // Clean up if dropping the event.
890 if (*dropReason != DROP_REASON_NOT_DROPPED) {
891 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
892 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
893 return true;
894 }
895
896 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
897
898 // Identify targets.
899 Vector<InputTarget> inputTargets;
900
901 bool conflictingPointerActions = false;
902 int32_t injectionResult;
903 if (isPointerEvent) {
904 // Pointer event. (eg. touchscreen)
905 injectionResult = findTouchedWindowTargetsLocked(currentTime,
906 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
907 } else {
908 // Non touch event. (eg. trackball)
909 injectionResult = findFocusedWindowTargetsLocked(currentTime,
910 entry, inputTargets, nextWakeupTime);
911 }
912 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
913 return false;
914 }
915
916 setInjectionResultLocked(entry, injectionResult);
917 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100918 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
919 CancelationOptions::Mode mode(isPointerEvent ?
920 CancelationOptions::CANCEL_POINTER_EVENTS :
921 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
922 CancelationOptions options(mode, "input event injection failed");
923 synthesizeCancelationEventsForMonitorsLocked(options);
924 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 return true;
926 }
927
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800928 // Add monitor channels from event's or focused display.
929 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930
931 // Dispatch the motion.
932 if (conflictingPointerActions) {
933 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
934 "conflicting pointer actions");
935 synthesizeCancelationEventsForAllConnectionsLocked(options);
936 }
937 dispatchEventLocked(currentTime, entry, inputTargets);
938 return true;
939}
940
941
942void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
943#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800944 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
945 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100946 "action=0x%x, actionButton=0x%x, flags=0x%x, "
947 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800948 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800950 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100951 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952 entry->metaState, entry->buttonState,
953 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800954 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955
956 for (uint32_t i = 0; i < entry->pointerCount; i++) {
957 ALOGD(" Pointer %d: id=%d, toolType=%d, "
958 "x=%f, y=%f, pressure=%f, size=%f, "
959 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800960 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961 i, entry->pointerProperties[i].id,
962 entry->pointerProperties[i].toolType,
963 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
964 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
965 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
966 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
967 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
968 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
969 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
970 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800971 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 }
973#endif
974}
975
976void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
977 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
978#if DEBUG_DISPATCH_CYCLE
979 ALOGD("dispatchEventToCurrentInputTargets");
980#endif
981
982 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
983
984 pokeUserActivityLocked(eventEntry);
985
986 for (size_t i = 0; i < inputTargets.size(); i++) {
987 const InputTarget& inputTarget = inputTargets.itemAt(i);
988
989 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
990 if (connectionIndex >= 0) {
991 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
992 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
993 } else {
994#if DEBUG_FOCUS
995 ALOGD("Dropping event delivery to target with channel '%s' because it "
996 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800997 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800998#endif
999 }
1000 }
1001}
1002
1003int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1004 const EventEntry* entry,
1005 const sp<InputApplicationHandle>& applicationHandle,
1006 const sp<InputWindowHandle>& windowHandle,
1007 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001008 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1010#if DEBUG_FOCUS
1011 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1012#endif
1013 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1014 mInputTargetWaitStartTime = currentTime;
1015 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1016 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001017 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 }
1019 } else {
1020 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1021#if DEBUG_FOCUS
1022 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001023 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 reason);
1025#endif
1026 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001027 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001028 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001029 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 timeout = applicationHandle->getDispatchingTimeout(
1031 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1032 } else {
1033 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1034 }
1035
1036 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1037 mInputTargetWaitStartTime = currentTime;
1038 mInputTargetWaitTimeoutTime = currentTime + timeout;
1039 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001040 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041
Yi Kong9b14ac62018-07-17 13:48:38 -07001042 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001043 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 }
Robert Carr740167f2018-10-11 19:03:41 -07001045 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1046 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 }
1048 }
1049 }
1050
1051 if (mInputTargetWaitTimeoutExpired) {
1052 return INPUT_EVENT_INJECTION_TIMED_OUT;
1053 }
1054
1055 if (currentTime >= mInputTargetWaitTimeoutTime) {
1056 onANRLocked(currentTime, applicationHandle, windowHandle,
1057 entry->eventTime, mInputTargetWaitStartTime, reason);
1058
1059 // Force poll loop to wake up immediately on next iteration once we get the
1060 // ANR response back from the policy.
1061 *nextWakeupTime = LONG_LONG_MIN;
1062 return INPUT_EVENT_INJECTION_PENDING;
1063 } else {
1064 // Force poll loop to wake up when timeout is due.
1065 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1066 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1067 }
1068 return INPUT_EVENT_INJECTION_PENDING;
1069 }
1070}
1071
Robert Carr803535b2018-08-02 16:38:15 -07001072void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1073 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1074 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1075 state.removeWindowByToken(token);
1076 }
1077}
1078
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1080 const sp<InputChannel>& inputChannel) {
1081 if (newTimeout > 0) {
1082 // Extend the timeout.
1083 mInputTargetWaitTimeoutTime = now() + newTimeout;
1084 } else {
1085 // Give up.
1086 mInputTargetWaitTimeoutExpired = true;
1087
1088 // Input state will not be realistic. Mark it out of sync.
1089 if (inputChannel.get()) {
1090 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1091 if (connectionIndex >= 0) {
1092 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001093 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094
Robert Carr803535b2018-08-02 16:38:15 -07001095 if (token != nullptr) {
1096 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 }
1098
1099 if (connection->status == Connection::STATUS_NORMAL) {
1100 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1101 "application not responding");
1102 synthesizeCancelationEventsForConnectionLocked(connection, options);
1103 }
1104 }
1105 }
1106 }
1107}
1108
1109nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1110 nsecs_t currentTime) {
1111 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1112 return currentTime - mInputTargetWaitStartTime;
1113 }
1114 return 0;
1115}
1116
1117void InputDispatcher::resetANRTimeoutsLocked() {
1118#if DEBUG_FOCUS
1119 ALOGD("Resetting ANR timeouts.");
1120#endif
1121
1122 // Reset input target wait timeout.
1123 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001124 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125}
1126
Tiger Huang721e26f2018-07-24 22:26:19 +08001127/**
1128 * Get the display id that the given event should go to. If this event specifies a valid display id,
1129 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1130 * Focused display is the display that the user most recently interacted with.
1131 */
1132int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1133 int32_t displayId;
1134 switch (entry->type) {
1135 case EventEntry::TYPE_KEY: {
1136 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1137 displayId = typedEntry->displayId;
1138 break;
1139 }
1140 case EventEntry::TYPE_MOTION: {
1141 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1142 displayId = typedEntry->displayId;
1143 break;
1144 }
1145 default: {
1146 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1147 return ADISPLAY_ID_NONE;
1148 }
1149 }
1150 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1151}
1152
Michael Wrightd02c5b62014-02-10 15:10:22 -08001153int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1154 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1155 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001156 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001157
Tiger Huang721e26f2018-07-24 22:26:19 +08001158 int32_t displayId = getTargetDisplayId(entry);
1159 sp<InputWindowHandle> focusedWindowHandle =
1160 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1161 sp<InputApplicationHandle> focusedApplicationHandle =
1162 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1163
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 // If there is no currently focused window and no focused application
1165 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001166 if (focusedWindowHandle == nullptr) {
1167 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001169 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 "Waiting because no window has focus but there is a "
1171 "focused application that may eventually add a window "
1172 "when it finishes starting up.");
1173 goto Unresponsive;
1174 }
1175
Arthur Hung3b413f22018-10-26 18:05:34 +08001176 ALOGI("Dropping event because there is no focused window or focused application in display "
1177 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1179 goto Failed;
1180 }
1181
1182 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001183 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001184 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1185 goto Failed;
1186 }
1187
Jeff Brownffb49772014-10-10 19:01:34 -07001188 // Check whether the window is ready for more input.
1189 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001190 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001191 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001193 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 goto Unresponsive;
1195 }
1196
1197 // Success! Output targets.
1198 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001199 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1201 inputTargets);
1202
1203 // Done.
1204Failed:
1205Unresponsive:
1206 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1207 updateDispatchStatisticsLocked(currentTime, entry,
1208 injectionResult, timeSpentWaitingForApplication);
1209#if DEBUG_FOCUS
1210 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1211 "timeSpentWaitingForApplication=%0.1fms",
1212 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1213#endif
1214 return injectionResult;
1215}
1216
1217int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1218 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1219 bool* outConflictingPointerActions) {
1220 enum InjectionPermission {
1221 INJECTION_PERMISSION_UNKNOWN,
1222 INJECTION_PERMISSION_GRANTED,
1223 INJECTION_PERMISSION_DENIED
1224 };
1225
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 // For security reasons, we defer updating the touch state until we are sure that
1227 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 int32_t displayId = entry->displayId;
1229 int32_t action = entry->action;
1230 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1231
1232 // Update the touch state as needed based on the properties of the touch event.
1233 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1234 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1235 sp<InputWindowHandle> newHoverWindowHandle;
1236
Jeff Brownf086ddb2014-02-11 14:28:48 -08001237 // Copy current touch state into mTempTouchState.
1238 // This state is always reset at the end of this function, so if we don't find state
1239 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001240 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001241 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1242 if (oldStateIndex >= 0) {
1243 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1244 mTempTouchState.copyFrom(*oldState);
1245 }
1246
1247 bool isSplit = mTempTouchState.split;
1248 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1249 && (mTempTouchState.deviceId != entry->deviceId
1250 || mTempTouchState.source != entry->source
1251 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1253 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1254 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1255 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1256 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1257 || isHoverAction);
1258 bool wrongDevice = false;
1259 if (newGesture) {
1260 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001261 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001263 ALOGD("Dropping event because a pointer for a different device is already down "
1264 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001266 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1268 switchedDevice = false;
1269 wrongDevice = true;
1270 goto Failed;
1271 }
1272 mTempTouchState.reset();
1273 mTempTouchState.down = down;
1274 mTempTouchState.deviceId = entry->deviceId;
1275 mTempTouchState.source = entry->source;
1276 mTempTouchState.displayId = displayId;
1277 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001278 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1279#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001280 ALOGI("Dropping move event because a pointer for a different device is already active "
1281 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001282#endif
1283 // TODO: test multiple simultaneous input streams.
1284 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1285 switchedDevice = false;
1286 wrongDevice = true;
1287 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 }
1289
1290 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1291 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1292
1293 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1294 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1295 getAxisValue(AMOTION_EVENT_AXIS_X));
1296 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1297 getAxisValue(AMOTION_EVENT_AXIS_Y));
1298 sp<InputWindowHandle> newTouchedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 bool isTouchModal = false;
1300
1301 // Traverse windows from front to back to find touched window and outside targets.
Arthur Hungb92218b2018-08-14 12:00:21 +08001302 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1303 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001305 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1307 if (windowInfo->displayId != displayId) {
1308 continue; // wrong display
1309 }
1310
Michael Wrightd02c5b62014-02-10 15:10:22 -08001311 int32_t flags = windowInfo->layoutParamsFlags;
1312 if (windowInfo->visible) {
1313 if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
1314 isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
1315 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
1316 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Jeff Browndc5992e2014-04-11 01:27:26 -07001317 newTouchedWindowHandle = windowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001318 break; // found touched window, exit window loop
1319 }
1320 }
1321
1322 if (maskedAction == AMOTION_EVENT_ACTION_DOWN
1323 && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324 mTempTouchState.addOrUpdateWindow(
Michael Wright3b106102017-01-16 21:05:07 +00001325 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 }
1327 }
1328 }
1329
Michael Wrightd02c5b62014-02-10 15:10:22 -08001330 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001331 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001332 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1333 // New window supports splitting.
1334 isSplit = true;
1335 } else if (isSplit) {
1336 // New window does not support splitting but we have already split events.
1337 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001338 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 }
1340
1341 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001342 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001343 // Try to assign the pointer to the first foreground window we find, if there is one.
1344 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001345 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001346 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1347 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001348 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1349 goto Failed;
1350 }
1351 }
1352
1353 // Set target flags.
1354 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1355 if (isSplit) {
1356 targetFlags |= InputTarget::FLAG_SPLIT;
1357 }
1358 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1359 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001360 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1361 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362 }
1363
1364 // Update hover state.
1365 if (isHoverAction) {
1366 newHoverWindowHandle = newTouchedWindowHandle;
1367 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1368 newHoverWindowHandle = mLastHoverWindowHandle;
1369 }
1370
1371 // Update the temporary touch state.
1372 BitSet32 pointerIds;
1373 if (isSplit) {
1374 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1375 pointerIds.markBit(pointerId);
1376 }
1377 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1378 } else {
1379 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1380
1381 // If the pointer is not currently down, then ignore the event.
1382 if (! mTempTouchState.down) {
1383#if DEBUG_FOCUS
1384 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001385 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386#endif
1387 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1388 goto Failed;
1389 }
1390
1391 // Check whether touches should slip outside of the current foreground window.
1392 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1393 && entry->pointerCount == 1
1394 && mTempTouchState.isSlippery()) {
1395 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1396 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1397
1398 sp<InputWindowHandle> oldTouchedWindowHandle =
1399 mTempTouchState.getFirstForegroundWindowHandle();
1400 sp<InputWindowHandle> newTouchedWindowHandle =
1401 findTouchedWindowAtLocked(displayId, x, y);
1402 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001403 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001404#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001405 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001406 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001407 newTouchedWindowHandle->getName().c_str(),
1408 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001409#endif
1410 // Make a slippery exit from the old window.
1411 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1412 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1413
1414 // Make a slippery entrance into the new window.
1415 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1416 isSplit = true;
1417 }
1418
1419 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1420 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1421 if (isSplit) {
1422 targetFlags |= InputTarget::FLAG_SPLIT;
1423 }
1424 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1425 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1426 }
1427
1428 BitSet32 pointerIds;
1429 if (isSplit) {
1430 pointerIds.markBit(entry->pointerProperties[0].id);
1431 }
1432 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1433 }
1434 }
1435 }
1436
1437 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1438 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001439 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001440#if DEBUG_HOVER
1441 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001442 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001443#endif
1444 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1445 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1446 }
1447
1448 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001449 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450#if DEBUG_HOVER
1451 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001452 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453#endif
1454 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1455 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1456 }
1457 }
1458
1459 // Check permission to inject into all touched foreground windows and ensure there
1460 // is at least one touched foreground window.
1461 {
1462 bool haveForegroundWindow = false;
1463 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1464 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1465 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1466 haveForegroundWindow = true;
1467 if (! checkInjectionPermission(touchedWindow.windowHandle,
1468 entry->injectionState)) {
1469 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1470 injectionPermission = INJECTION_PERMISSION_DENIED;
1471 goto Failed;
1472 }
1473 }
1474 }
1475 if (! haveForegroundWindow) {
1476#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001477 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1478 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001479#endif
1480 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1481 goto Failed;
1482 }
1483
1484 // Permission granted to injection into all touched foreground windows.
1485 injectionPermission = INJECTION_PERMISSION_GRANTED;
1486 }
1487
1488 // Check whether windows listening for outside touches are owned by the same UID. If it is
1489 // set the policy flag that we will not reveal coordinate information to this window.
1490 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1491 sp<InputWindowHandle> foregroundWindowHandle =
1492 mTempTouchState.getFirstForegroundWindowHandle();
1493 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1494 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1495 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1496 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1497 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1498 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1499 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1500 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1501 }
1502 }
1503 }
1504 }
1505
1506 // Ensure all touched foreground windows are ready for new input.
1507 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1508 const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
1509 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001510 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001511 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001512 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001513 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001515 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 goto Unresponsive;
1517 }
1518 }
1519 }
1520
1521 // If this is the first pointer going down and the touched window has a wallpaper
1522 // then also add the touched wallpaper windows so they are locked in for the duration
1523 // of the touch gesture.
1524 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1525 // engine only supports touch events. We would need to add a mechanism similar
1526 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1527 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1528 sp<InputWindowHandle> foregroundWindowHandle =
1529 mTempTouchState.getFirstForegroundWindowHandle();
1530 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001531 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1532 size_t numWindows = windowHandles.size();
1533 for (size_t i = 0; i < numWindows; i++) {
1534 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001535 const InputWindowInfo* info = windowHandle->getInfo();
1536 if (info->displayId == displayId
1537 && windowHandle->getInfo()->layoutParamsType
1538 == InputWindowInfo::TYPE_WALLPAPER) {
1539 mTempTouchState.addOrUpdateWindow(windowHandle,
1540 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001541 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001542 | InputTarget::FLAG_DISPATCH_AS_IS,
1543 BitSet32(0));
1544 }
1545 }
1546 }
1547 }
1548
1549 // Success! Output targets.
1550 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1551
1552 for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
1553 const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
1554 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1555 touchedWindow.pointerIds, inputTargets);
1556 }
1557
1558 // Drop the outside or hover touch windows since we will not care about them
1559 // in the next iteration.
1560 mTempTouchState.filterNonAsIsTouchWindows();
1561
1562Failed:
1563 // Check injection permission once and for all.
1564 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001565 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566 injectionPermission = INJECTION_PERMISSION_GRANTED;
1567 } else {
1568 injectionPermission = INJECTION_PERMISSION_DENIED;
1569 }
1570 }
1571
1572 // Update final pieces of touch state if the injector had permission.
1573 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1574 if (!wrongDevice) {
1575 if (switchedDevice) {
1576#if DEBUG_FOCUS
1577 ALOGD("Conflicting pointer actions: Switched to a different device.");
1578#endif
1579 *outConflictingPointerActions = true;
1580 }
1581
1582 if (isHoverAction) {
1583 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001584 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585#if DEBUG_FOCUS
1586 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1587#endif
1588 *outConflictingPointerActions = true;
1589 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001590 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001591 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1592 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001593 mTempTouchState.deviceId = entry->deviceId;
1594 mTempTouchState.source = entry->source;
1595 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 }
1597 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1598 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1599 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001600 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001601 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1602 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001603 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001604#if DEBUG_FOCUS
1605 ALOGD("Conflicting pointer actions: Down received while already down.");
1606#endif
1607 *outConflictingPointerActions = true;
1608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001609 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1610 // One pointer went up.
1611 if (isSplit) {
1612 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1613 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1614
1615 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
1616 TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
1617 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1618 touchedWindow.pointerIds.clearBit(pointerId);
1619 if (touchedWindow.pointerIds.isEmpty()) {
1620 mTempTouchState.windows.removeAt(i);
1621 continue;
1622 }
1623 }
1624 i += 1;
1625 }
1626 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001627 }
1628
1629 // Save changes unless the action was scroll in which case the temporary touch
1630 // state was only valid for this one action.
1631 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1632 if (mTempTouchState.displayId >= 0) {
1633 if (oldStateIndex >= 0) {
1634 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1635 } else {
1636 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1637 }
1638 } else if (oldStateIndex >= 0) {
1639 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1640 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 }
1642
1643 // Update hover state.
1644 mLastHoverWindowHandle = newHoverWindowHandle;
1645 }
1646 } else {
1647#if DEBUG_FOCUS
1648 ALOGD("Not updating touch focus because injection was denied.");
1649#endif
1650 }
1651
1652Unresponsive:
1653 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1654 mTempTouchState.reset();
1655
1656 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1657 updateDispatchStatisticsLocked(currentTime, entry,
1658 injectionResult, timeSpentWaitingForApplication);
1659#if DEBUG_FOCUS
1660 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1661 "timeSpentWaitingForApplication=%0.1fms",
1662 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1663#endif
1664 return injectionResult;
1665}
1666
1667void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
1668 int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001669 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1670 if (inputChannel == nullptr) {
1671 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1672 return;
1673 }
1674
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 inputTargets.push();
1676
1677 const InputWindowInfo* windowInfo = windowHandle->getInfo();
1678 InputTarget& target = inputTargets.editTop();
Arthur Hungceeb5d72018-12-05 16:14:18 +08001679 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001680 target.flags = targetFlags;
1681 target.xOffset = - windowInfo->frameLeft;
1682 target.yOffset = - windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001683 target.globalScaleFactor = windowInfo->globalScaleFactor;
1684 target.windowXScale = windowInfo->windowXScale;
1685 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001686 target.pointerIds = pointerIds;
1687}
1688
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001689void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets,
1690 int32_t displayId) {
1691 std::unordered_map<int32_t, Vector<sp<InputChannel>>>::const_iterator it =
1692 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001694 if (it != mMonitoringChannelsByDisplay.end()) {
1695 const Vector<sp<InputChannel>>& monitoringChannels = it->second;
1696 const size_t numChannels = monitoringChannels.size();
1697 for (size_t i = 0; i < numChannels; i++) {
1698 inputTargets.push();
1699
1700 InputTarget& target = inputTargets.editTop();
1701 target.inputChannel = monitoringChannels[i];
1702 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1703 target.xOffset = 0;
1704 target.yOffset = 0;
1705 target.pointerIds.clear();
Robert Carre07e1032018-11-26 12:55:53 -08001706 target.globalScaleFactor = 1.0f;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001707 }
1708 } else {
1709 // If there is no monitor channel registered or all monitor channel unregistered,
1710 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001711 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001712 }
1713}
1714
1715bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1716 const InjectionState* injectionState) {
1717 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001718 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001719 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1720 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001721 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1723 "owned by uid %d",
1724 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001725 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 windowHandle->getInfo()->ownerUid);
1727 } else {
1728 ALOGW("Permission denied: injecting event from pid %d uid %d",
1729 injectionState->injectorPid, injectionState->injectorUid);
1730 }
1731 return false;
1732 }
1733 return true;
1734}
1735
1736bool InputDispatcher::isWindowObscuredAtPointLocked(
1737 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1738 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001739 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1740 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001742 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 if (otherHandle == windowHandle) {
1744 break;
1745 }
1746
1747 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1748 if (otherInfo->displayId == displayId
1749 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1750 && otherInfo->frameContainsPoint(x, y)) {
1751 return true;
1752 }
1753 }
1754 return false;
1755}
1756
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001757
1758bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1759 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hungb92218b2018-08-14 12:00:21 +08001760 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001761 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hungb92218b2018-08-14 12:00:21 +08001762 size_t numWindows = windowHandles.size();
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001763 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001764 sp<InputWindowHandle> otherHandle = windowHandles.itemAt(i);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001765 if (otherHandle == windowHandle) {
1766 break;
1767 }
1768
1769 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1770 if (otherInfo->displayId == displayId
1771 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1772 && otherInfo->overlaps(windowInfo)) {
1773 return true;
1774 }
1775 }
1776 return false;
1777}
1778
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001779std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001780 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1781 const char* targetType) {
1782 // If the window is paused then keep waiting.
1783 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001784 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001785 }
1786
1787 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001788 ssize_t connectionIndex = getConnectionIndexLocked(
1789 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001790 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001791 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001792 "registered with the input dispatcher. The window may be in the process "
1793 "of being removed.", targetType);
1794 }
1795
1796 // If the connection is dead then keep waiting.
1797 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1798 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001799 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001800 "The window may be in the process of being removed.", targetType,
1801 connection->getStatusLabel());
1802 }
1803
1804 // If the connection is backed up then keep waiting.
1805 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001806 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001807 "Outbound queue length: %d. Wait queue length: %d.",
1808 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1809 }
1810
1811 // Ensure that the dispatch queues aren't too far backed up for this event.
1812 if (eventEntry->type == EventEntry::TYPE_KEY) {
1813 // If the event is a key event, then we must wait for all previous events to
1814 // complete before delivering it because previous events may have the
1815 // side-effect of transferring focus to a different window and we want to
1816 // ensure that the following keys are sent to the new window.
1817 //
1818 // Suppose the user touches a button in a window then immediately presses "A".
1819 // If the button causes a pop-up window to appear then we want to ensure that
1820 // the "A" key is delivered to the new pop-up window. This is because users
1821 // often anticipate pending UI changes when typing on a keyboard.
1822 // To obtain this behavior, we must serialize key events with respect to all
1823 // prior input events.
1824 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001825 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001826 "finished processing all of the input events that were previously "
1827 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1828 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001829 }
Jeff Brownffb49772014-10-10 19:01:34 -07001830 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001831 // Touch events can always be sent to a window immediately because the user intended
1832 // to touch whatever was visible at the time. Even if focus changes or a new
1833 // window appears moments later, the touch event was meant to be delivered to
1834 // whatever window happened to be on screen at the time.
1835 //
1836 // Generic motion events, such as trackball or joystick events are a little trickier.
1837 // Like key events, generic motion events are delivered to the focused window.
1838 // Unlike key events, generic motion events don't tend to transfer focus to other
1839 // windows and it is not important for them to be serialized. So we prefer to deliver
1840 // generic motion events as soon as possible to improve efficiency and reduce lag
1841 // through batching.
1842 //
1843 // The one case where we pause input event delivery is when the wait queue is piling
1844 // up with lots of events because the application is not responding.
1845 // This condition ensures that ANRs are detected reliably.
1846 if (!connection->waitQueue.isEmpty()
1847 && currentTime >= connection->waitQueue.head->deliveryTime
1848 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001849 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001850 "finished processing certain input events that were delivered to it over "
1851 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1852 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1853 connection->waitQueue.count(),
1854 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 }
1856 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001857 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858}
1859
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001860std::string InputDispatcher::getApplicationWindowLabelLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 const sp<InputApplicationHandle>& applicationHandle,
1862 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001863 if (applicationHandle != nullptr) {
1864 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001865 std::string label(applicationHandle->getName());
1866 label += " - ";
1867 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001868 return label;
1869 } else {
1870 return applicationHandle->getName();
1871 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001872 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 return windowHandle->getName();
1874 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001875 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876 }
1877}
1878
1879void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001880 int32_t displayId = getTargetDisplayId(eventEntry);
1881 sp<InputWindowHandle> focusedWindowHandle =
1882 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1883 if (focusedWindowHandle != nullptr) {
1884 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1886#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001887 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888#endif
1889 return;
1890 }
1891 }
1892
1893 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1894 switch (eventEntry->type) {
1895 case EventEntry::TYPE_MOTION: {
1896 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1897 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1898 return;
1899 }
1900
1901 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1902 eventType = USER_ACTIVITY_EVENT_TOUCH;
1903 }
1904 break;
1905 }
1906 case EventEntry::TYPE_KEY: {
1907 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1908 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1909 return;
1910 }
1911 eventType = USER_ACTIVITY_EVENT_BUTTON;
1912 break;
1913 }
1914 }
1915
1916 CommandEntry* commandEntry = postCommandLocked(
1917 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1918 commandEntry->eventTime = eventEntry->eventTime;
1919 commandEntry->userActivityEventType = eventType;
1920}
1921
1922void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1923 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1924#if DEBUG_DISPATCH_CYCLE
1925 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Robert Carre07e1032018-11-26 12:55:53 -08001926 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1927 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001928 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929 inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001930 inputTarget->globalScaleFactor,
1931 inputTarget->windowXScale, inputTarget->windowYScale,
1932 inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001933#endif
1934
1935 // Skip this event if the connection status is not normal.
1936 // We don't want to enqueue additional outbound events if the connection is broken.
1937 if (connection->status != Connection::STATUS_NORMAL) {
1938#if DEBUG_DISPATCH_CYCLE
1939 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001940 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001941#endif
1942 return;
1943 }
1944
1945 // Split a motion event if needed.
1946 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1947 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1948
1949 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1950 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1951 MotionEntry* splitMotionEntry = splitMotionEvent(
1952 originalMotionEntry, inputTarget->pointerIds);
1953 if (!splitMotionEntry) {
1954 return; // split event was dropped
1955 }
1956#if DEBUG_FOCUS
1957 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001958 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959 logOutboundMotionDetailsLocked(" ", splitMotionEntry);
1960#endif
1961 enqueueDispatchEntriesLocked(currentTime, connection,
1962 splitMotionEntry, inputTarget);
1963 splitMotionEntry->release();
1964 return;
1965 }
1966 }
1967
1968 // Not splitting. Enqueue dispatch entries for the event as is.
1969 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1970}
1971
1972void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1973 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1974 bool wasEmpty = connection->outboundQueue.isEmpty();
1975
1976 // Enqueue dispatch entries for the requested modes.
1977 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1978 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
1979 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1980 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
1981 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1982 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
1983 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1984 InputTarget::FLAG_DISPATCH_AS_IS);
1985 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1986 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
1987 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
1988 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1989
1990 // If the outbound queue was previously empty, start the dispatch cycle going.
1991 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1992 startDispatchCycleLocked(currentTime, connection);
1993 }
1994}
1995
1996void InputDispatcher::enqueueDispatchEntryLocked(
1997 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1998 int32_t dispatchMode) {
1999 int32_t inputTargetFlags = inputTarget->flags;
2000 if (!(inputTargetFlags & dispatchMode)) {
2001 return;
2002 }
2003 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2004
2005 // This is a new event.
2006 // Enqueue a new dispatch entry onto the outbound queue for this connection.
2007 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
2008 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08002009 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2010 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011
2012 // Apply target flags and update the connection's input state.
2013 switch (eventEntry->type) {
2014 case EventEntry::TYPE_KEY: {
2015 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2016 dispatchEntry->resolvedAction = keyEntry->action;
2017 dispatchEntry->resolvedFlags = keyEntry->flags;
2018
2019 if (!connection->inputState.trackKey(keyEntry,
2020 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2021#if DEBUG_DISPATCH_CYCLE
2022 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002023 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024#endif
2025 delete dispatchEntry;
2026 return; // skip the inconsistent event
2027 }
2028 break;
2029 }
2030
2031 case EventEntry::TYPE_MOTION: {
2032 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2033 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2034 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2035 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2036 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2037 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2038 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2039 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2040 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2041 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2042 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2043 } else {
2044 dispatchEntry->resolvedAction = motionEntry->action;
2045 }
2046 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2047 && !connection->inputState.isHovering(
2048 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2049#if DEBUG_DISPATCH_CYCLE
2050 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002051 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052#endif
2053 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2054 }
2055
2056 dispatchEntry->resolvedFlags = motionEntry->flags;
2057 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2058 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2059 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002060 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2061 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063
2064 if (!connection->inputState.trackMotion(motionEntry,
2065 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2066#if DEBUG_DISPATCH_CYCLE
2067 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002068 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069#endif
2070 delete dispatchEntry;
2071 return; // skip the inconsistent event
2072 }
2073 break;
2074 }
2075 }
2076
2077 // Remember that we are waiting for this dispatch to complete.
2078 if (dispatchEntry->hasForegroundTarget()) {
2079 incrementPendingForegroundDispatchesLocked(eventEntry);
2080 }
2081
2082 // Enqueue the dispatch entry.
2083 connection->outboundQueue.enqueueAtTail(dispatchEntry);
2084 traceOutboundQueueLengthLocked(connection);
2085}
2086
2087void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2088 const sp<Connection>& connection) {
2089#if DEBUG_DISPATCH_CYCLE
2090 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002091 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092#endif
2093
2094 while (connection->status == Connection::STATUS_NORMAL
2095 && !connection->outboundQueue.isEmpty()) {
2096 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2097 dispatchEntry->deliveryTime = currentTime;
2098
2099 // Publish the event.
2100 status_t status;
2101 EventEntry* eventEntry = dispatchEntry->eventEntry;
2102 switch (eventEntry->type) {
2103 case EventEntry::TYPE_KEY: {
2104 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2105
2106 // Publish the key event.
2107 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002108 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2110 keyEntry->keyCode, keyEntry->scanCode,
2111 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2112 keyEntry->eventTime);
2113 break;
2114 }
2115
2116 case EventEntry::TYPE_MOTION: {
2117 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2118
2119 PointerCoords scaledCoords[MAX_POINTERS];
2120 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2121
2122 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002123 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2125 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002126 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2127 float wxs = dispatchEntry->windowXScale;
2128 float wys = dispatchEntry->windowYScale;
2129 xOffset = dispatchEntry->xOffset * wxs;
2130 yOffset = dispatchEntry->yOffset * wys;
2131 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002132 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002134 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 }
2136 usingCoords = scaledCoords;
2137 }
2138 } else {
2139 xOffset = 0.0f;
2140 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141
2142 // We don't want the dispatch target to know.
2143 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002144 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145 scaledCoords[i].clear();
2146 }
2147 usingCoords = scaledCoords;
2148 }
2149 }
2150
2151 // Publish the motion event.
2152 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002153 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002154 dispatchEntry->resolvedAction, motionEntry->actionButton,
2155 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
2156 motionEntry->metaState, motionEntry->buttonState,
2157 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 motionEntry->downTime, motionEntry->eventTime,
2159 motionEntry->pointerCount, motionEntry->pointerProperties,
2160 usingCoords);
2161 break;
2162 }
2163
2164 default:
2165 ALOG_ASSERT(false);
2166 return;
2167 }
2168
2169 // Check the result.
2170 if (status) {
2171 if (status == WOULD_BLOCK) {
2172 if (connection->waitQueue.isEmpty()) {
2173 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2174 "This is unexpected because the wait queue is empty, so the pipe "
2175 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002176 "event to it, status=%d", connection->getInputChannelName().c_str(),
2177 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2179 } else {
2180 // Pipe is full and we are waiting for the app to finish process some events
2181 // before sending more events to it.
2182#if DEBUG_DISPATCH_CYCLE
2183 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2184 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002185 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186#endif
2187 connection->inputPublisherBlocked = true;
2188 }
2189 } else {
2190 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002191 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2193 }
2194 return;
2195 }
2196
2197 // Re-enqueue the event on the wait queue.
2198 connection->outboundQueue.dequeue(dispatchEntry);
2199 traceOutboundQueueLengthLocked(connection);
2200 connection->waitQueue.enqueueAtTail(dispatchEntry);
2201 traceWaitQueueLengthLocked(connection);
2202 }
2203}
2204
2205void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2206 const sp<Connection>& connection, uint32_t seq, bool handled) {
2207#if DEBUG_DISPATCH_CYCLE
2208 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002209 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210#endif
2211
2212 connection->inputPublisherBlocked = false;
2213
2214 if (connection->status == Connection::STATUS_BROKEN
2215 || connection->status == Connection::STATUS_ZOMBIE) {
2216 return;
2217 }
2218
2219 // Notify other system components and prepare to start the next dispatch cycle.
2220 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2221}
2222
2223void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2224 const sp<Connection>& connection, bool notify) {
2225#if DEBUG_DISPATCH_CYCLE
2226 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002227 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228#endif
2229
2230 // Clear the dispatch queues.
2231 drainDispatchQueueLocked(&connection->outboundQueue);
2232 traceOutboundQueueLengthLocked(connection);
2233 drainDispatchQueueLocked(&connection->waitQueue);
2234 traceWaitQueueLengthLocked(connection);
2235
2236 // The connection appears to be unrecoverably broken.
2237 // Ignore already broken or zombie connections.
2238 if (connection->status == Connection::STATUS_NORMAL) {
2239 connection->status = Connection::STATUS_BROKEN;
2240
2241 if (notify) {
2242 // Notify other system components.
2243 onDispatchCycleBrokenLocked(currentTime, connection);
2244 }
2245 }
2246}
2247
2248void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
2249 while (!queue->isEmpty()) {
2250 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
2251 releaseDispatchEntryLocked(dispatchEntry);
2252 }
2253}
2254
2255void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
2256 if (dispatchEntry->hasForegroundTarget()) {
2257 decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
2258 }
2259 delete dispatchEntry;
2260}
2261
2262int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2263 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2264
2265 { // acquire lock
2266 AutoMutex _l(d->mLock);
2267
2268 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2269 if (connectionIndex < 0) {
2270 ALOGE("Received spurious receive callback for unknown input channel. "
2271 "fd=%d, events=0x%x", fd, events);
2272 return 0; // remove the callback
2273 }
2274
2275 bool notify;
2276 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2277 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2278 if (!(events & ALOOPER_EVENT_INPUT)) {
2279 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002280 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 return 1;
2282 }
2283
2284 nsecs_t currentTime = now();
2285 bool gotOne = false;
2286 status_t status;
2287 for (;;) {
2288 uint32_t seq;
2289 bool handled;
2290 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2291 if (status) {
2292 break;
2293 }
2294 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2295 gotOne = true;
2296 }
2297 if (gotOne) {
2298 d->runCommandsLockedInterruptible();
2299 if (status == WOULD_BLOCK) {
2300 return 1;
2301 }
2302 }
2303
2304 notify = status != DEAD_OBJECT || !connection->monitor;
2305 if (notify) {
2306 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002307 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 }
2309 } else {
2310 // Monitor channels are never explicitly unregistered.
2311 // We do it automatically when the remote endpoint is closed so don't warn
2312 // about them.
2313 notify = !connection->monitor;
2314 if (notify) {
2315 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002316 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 }
2318 }
2319
2320 // Unregister the channel.
2321 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2322 return 0; // remove the callback
2323 } // release lock
2324}
2325
2326void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
2327 const CancelationOptions& options) {
2328 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2329 synthesizeCancelationEventsForConnectionLocked(
2330 mConnectionsByFd.valueAt(i), options);
2331 }
2332}
2333
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002334void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2335 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002336 for (auto& it : mMonitoringChannelsByDisplay) {
2337 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
2338 const size_t numChannels = monitoringChannels.size();
2339 for (size_t i = 0; i < numChannels; i++) {
2340 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2341 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002342 }
2343}
2344
Michael Wrightd02c5b62014-02-10 15:10:22 -08002345void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2346 const sp<InputChannel>& channel, const CancelationOptions& options) {
2347 ssize_t index = getConnectionIndexLocked(channel);
2348 if (index >= 0) {
2349 synthesizeCancelationEventsForConnectionLocked(
2350 mConnectionsByFd.valueAt(index), options);
2351 }
2352}
2353
2354void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2355 const sp<Connection>& connection, const CancelationOptions& options) {
2356 if (connection->status == Connection::STATUS_BROKEN) {
2357 return;
2358 }
2359
2360 nsecs_t currentTime = now();
2361
2362 Vector<EventEntry*> cancelationEvents;
2363 connection->inputState.synthesizeCancelationEvents(currentTime,
2364 cancelationEvents, options);
2365
2366 if (!cancelationEvents.isEmpty()) {
2367#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002368 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002370 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371 options.reason, options.mode);
2372#endif
2373 for (size_t i = 0; i < cancelationEvents.size(); i++) {
2374 EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
2375 switch (cancelationEventEntry->type) {
2376 case EventEntry::TYPE_KEY:
2377 logOutboundKeyDetailsLocked("cancel - ",
2378 static_cast<KeyEntry*>(cancelationEventEntry));
2379 break;
2380 case EventEntry::TYPE_MOTION:
2381 logOutboundMotionDetailsLocked("cancel - ",
2382 static_cast<MotionEntry*>(cancelationEventEntry));
2383 break;
2384 }
2385
2386 InputTarget target;
2387 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07002388 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2390 target.xOffset = -windowInfo->frameLeft;
2391 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002392 target.globalScaleFactor = windowInfo->globalScaleFactor;
2393 target.windowXScale = windowInfo->windowXScale;
2394 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 } else {
2396 target.xOffset = 0;
2397 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002398 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 }
2400 target.inputChannel = connection->inputChannel;
2401 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2402
2403 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2404 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2405
2406 cancelationEventEntry->release();
2407 }
2408
2409 startDispatchCycleLocked(currentTime, connection);
2410 }
2411}
2412
2413InputDispatcher::MotionEntry*
2414InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2415 ALOG_ASSERT(pointerIds.value != 0);
2416
2417 uint32_t splitPointerIndexMap[MAX_POINTERS];
2418 PointerProperties splitPointerProperties[MAX_POINTERS];
2419 PointerCoords splitPointerCoords[MAX_POINTERS];
2420
2421 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2422 uint32_t splitPointerCount = 0;
2423
2424 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2425 originalPointerIndex++) {
2426 const PointerProperties& pointerProperties =
2427 originalMotionEntry->pointerProperties[originalPointerIndex];
2428 uint32_t pointerId = uint32_t(pointerProperties.id);
2429 if (pointerIds.hasBit(pointerId)) {
2430 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2431 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2432 splitPointerCoords[splitPointerCount].copyFrom(
2433 originalMotionEntry->pointerCoords[originalPointerIndex]);
2434 splitPointerCount += 1;
2435 }
2436 }
2437
2438 if (splitPointerCount != pointerIds.count()) {
2439 // This is bad. We are missing some of the pointers that we expected to deliver.
2440 // Most likely this indicates that we received an ACTION_MOVE events that has
2441 // different pointer ids than we expected based on the previous ACTION_DOWN
2442 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2443 // in this way.
2444 ALOGW("Dropping split motion event because the pointer count is %d but "
2445 "we expected there to be %d pointers. This probably means we received "
2446 "a broken sequence of pointer ids from the input device.",
2447 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002448 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 }
2450
2451 int32_t action = originalMotionEntry->action;
2452 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2453 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2454 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2455 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2456 const PointerProperties& pointerProperties =
2457 originalMotionEntry->pointerProperties[originalPointerIndex];
2458 uint32_t pointerId = uint32_t(pointerProperties.id);
2459 if (pointerIds.hasBit(pointerId)) {
2460 if (pointerIds.count() == 1) {
2461 // The first/last pointer went down/up.
2462 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2463 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2464 } else {
2465 // A secondary pointer went down/up.
2466 uint32_t splitPointerIndex = 0;
2467 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2468 splitPointerIndex += 1;
2469 }
2470 action = maskedAction | (splitPointerIndex
2471 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2472 }
2473 } else {
2474 // An unrelated pointer changed.
2475 action = AMOTION_EVENT_ACTION_MOVE;
2476 }
2477 }
2478
2479 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002480 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481 originalMotionEntry->eventTime,
2482 originalMotionEntry->deviceId,
2483 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002484 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002485 originalMotionEntry->policyFlags,
2486 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002487 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 originalMotionEntry->flags,
2489 originalMotionEntry->metaState,
2490 originalMotionEntry->buttonState,
2491 originalMotionEntry->edgeFlags,
2492 originalMotionEntry->xPrecision,
2493 originalMotionEntry->yPrecision,
2494 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002495 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496
2497 if (originalMotionEntry->injectionState) {
2498 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2499 splitMotionEntry->injectionState->refCount += 1;
2500 }
2501
2502 return splitMotionEntry;
2503}
2504
2505void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2506#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002507 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508#endif
2509
2510 bool needWake;
2511 { // acquire lock
2512 AutoMutex _l(mLock);
2513
Prabir Pradhan42611e02018-11-27 14:04:02 -08002514 ConfigurationChangedEntry* newEntry =
2515 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 needWake = enqueueInboundEventLocked(newEntry);
2517 } // release lock
2518
2519 if (needWake) {
2520 mLooper->wake();
2521 }
2522}
2523
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002524/**
2525 * If one of the meta shortcuts is detected, process them here:
2526 * Meta + Backspace -> generate BACK
2527 * Meta + Enter -> generate HOME
2528 * This will potentially overwrite keyCode and metaState.
2529 */
2530void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2531 int32_t& keyCode, int32_t& metaState) {
2532 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2533 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2534 if (keyCode == AKEYCODE_DEL) {
2535 newKeyCode = AKEYCODE_BACK;
2536 } else if (keyCode == AKEYCODE_ENTER) {
2537 newKeyCode = AKEYCODE_HOME;
2538 }
2539 if (newKeyCode != AKEYCODE_UNKNOWN) {
2540 AutoMutex _l(mLock);
2541 struct KeyReplacement replacement = {keyCode, deviceId};
2542 mReplacedKeys.add(replacement, newKeyCode);
2543 keyCode = newKeyCode;
2544 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2545 }
2546 } else if (action == AKEY_EVENT_ACTION_UP) {
2547 // In order to maintain a consistent stream of up and down events, check to see if the key
2548 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2549 // even if the modifier was released between the down and the up events.
2550 AutoMutex _l(mLock);
2551 struct KeyReplacement replacement = {keyCode, deviceId};
2552 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2553 if (index >= 0) {
2554 keyCode = mReplacedKeys.valueAt(index);
2555 mReplacedKeys.removeItemsAt(index);
2556 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2557 }
2558 }
2559}
2560
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2562#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002563 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002564 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002565 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002566 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002568 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569#endif
2570 if (!validateKeyEvent(args->action)) {
2571 return;
2572 }
2573
2574 uint32_t policyFlags = args->policyFlags;
2575 int32_t flags = args->flags;
2576 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002577 // InputDispatcher tracks and generates key repeats on behalf of
2578 // whatever notifies it, so repeatCount should always be set to 0
2579 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2581 policyFlags |= POLICY_FLAG_VIRTUAL;
2582 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2583 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 if (policyFlags & POLICY_FLAG_FUNCTION) {
2585 metaState |= AMETA_FUNCTION_ON;
2586 }
2587
2588 policyFlags |= POLICY_FLAG_TRUSTED;
2589
Michael Wright78f24442014-08-06 15:55:28 -07002590 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002591 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002592
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002594 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002595 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 args->downTime, args->eventTime);
2597
Michael Wright2b3c3302018-03-02 17:19:13 +00002598 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002600 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2601 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2602 std::to_string(t.duration().count()).c_str());
2603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604
Michael Wrightd02c5b62014-02-10 15:10:22 -08002605 bool needWake;
2606 { // acquire lock
2607 mLock.lock();
2608
2609 if (shouldSendKeyToInputFilterLocked(args)) {
2610 mLock.unlock();
2611
2612 policyFlags |= POLICY_FLAG_FILTERED;
2613 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2614 return; // event was consumed by the filter
2615 }
2616
2617 mLock.lock();
2618 }
2619
Prabir Pradhan42611e02018-11-27 14:04:02 -08002620 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002621 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002622 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 metaState, repeatCount, args->downTime);
2624
2625 needWake = enqueueInboundEventLocked(newEntry);
2626 mLock.unlock();
2627 } // release lock
2628
2629 if (needWake) {
2630 mLooper->wake();
2631 }
2632}
2633
2634bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2635 return mInputFilterEnabled;
2636}
2637
2638void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2639#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002640 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2641 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002642 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002643 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2644 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002645 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002646 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 for (uint32_t i = 0; i < args->pointerCount; i++) {
2648 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2649 "x=%f, y=%f, pressure=%f, size=%f, "
2650 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2651 "orientation=%f",
2652 i, args->pointerProperties[i].id,
2653 args->pointerProperties[i].toolType,
2654 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2655 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2656 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2657 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2658 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2659 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2660 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2661 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2662 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2663 }
2664#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002665 if (!validateMotionEvent(args->action, args->actionButton,
2666 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667 return;
2668 }
2669
2670 uint32_t policyFlags = args->policyFlags;
2671 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002672
2673 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674 mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002675 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2676 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2677 std::to_string(t.duration().count()).c_str());
2678 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679
2680 bool needWake;
2681 { // acquire lock
2682 mLock.lock();
2683
2684 if (shouldSendMotionToInputFilterLocked(args)) {
2685 mLock.unlock();
2686
2687 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002688 event.initialize(args->deviceId, args->source, args->displayId,
2689 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002690 args->flags, args->edgeFlags, args->metaState, args->buttonState,
2691 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 args->downTime, args->eventTime,
2693 args->pointerCount, args->pointerProperties, args->pointerCoords);
2694
2695 policyFlags |= POLICY_FLAG_FILTERED;
2696 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2697 return; // event was consumed by the filter
2698 }
2699
2700 mLock.lock();
2701 }
2702
2703 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002704 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002705 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002706 args->action, args->actionButton, args->flags,
2707 args->metaState, args->buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002709 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710
2711 needWake = enqueueInboundEventLocked(newEntry);
2712 mLock.unlock();
2713 } // release lock
2714
2715 if (needWake) {
2716 mLooper->wake();
2717 }
2718}
2719
2720bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
2721 // TODO: support sending secondary display events to input filter
2722 return mInputFilterEnabled && isMainDisplay(args->displayId);
2723}
2724
2725void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2726#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002727 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2728 "switchMask=0x%08x",
2729 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730#endif
2731
2732 uint32_t policyFlags = args->policyFlags;
2733 policyFlags |= POLICY_FLAG_TRUSTED;
2734 mPolicy->notifySwitch(args->eventTime,
2735 args->switchValues, args->switchMask, policyFlags);
2736}
2737
2738void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2739#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002740 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741 args->eventTime, args->deviceId);
2742#endif
2743
2744 bool needWake;
2745 { // acquire lock
2746 AutoMutex _l(mLock);
2747
Prabir Pradhan42611e02018-11-27 14:04:02 -08002748 DeviceResetEntry* newEntry =
2749 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002750 needWake = enqueueInboundEventLocked(newEntry);
2751 } // release lock
2752
2753 if (needWake) {
2754 mLooper->wake();
2755 }
2756}
2757
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002758int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2760 uint32_t policyFlags) {
2761#if DEBUG_INBOUND_EVENT_DETAILS
2762 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002763 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2764 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765#endif
2766
2767 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2768
2769 policyFlags |= POLICY_FLAG_INJECTED;
2770 if (hasInjectionPermission(injectorPid, injectorUid)) {
2771 policyFlags |= POLICY_FLAG_TRUSTED;
2772 }
2773
2774 EventEntry* firstInjectedEntry;
2775 EventEntry* lastInjectedEntry;
2776 switch (event->getType()) {
2777 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002778 KeyEvent keyEvent;
2779 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2780 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781 if (! validateKeyEvent(action)) {
2782 return INPUT_EVENT_INJECTION_FAILED;
2783 }
2784
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002785 int32_t flags = keyEvent.getFlags();
2786 int32_t keyCode = keyEvent.getKeyCode();
2787 int32_t metaState = keyEvent.getMetaState();
2788 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2789 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002790 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002791 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002792 keyEvent.getDownTime(), keyEvent.getEventTime());
2793
Michael Wrightd02c5b62014-02-10 15:10:22 -08002794 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2795 policyFlags |= POLICY_FLAG_VIRTUAL;
2796 }
2797
2798 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002799 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002800 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002801 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2802 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2803 std::to_string(t.duration().count()).c_str());
2804 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 }
2806
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002808 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002809 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002811 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2812 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 lastInjectedEntry = firstInjectedEntry;
2814 break;
2815 }
2816
2817 case AINPUT_EVENT_TYPE_MOTION: {
2818 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 int32_t action = motionEvent->getAction();
2820 size_t pointerCount = motionEvent->getPointerCount();
2821 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002822 int32_t actionButton = motionEvent->getActionButton();
2823 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 return INPUT_EVENT_INJECTION_FAILED;
2825 }
2826
2827 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2828 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002829 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002831 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2832 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2833 std::to_string(t.duration().count()).c_str());
2834 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835 }
2836
2837 mLock.lock();
2838 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2839 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002840 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002841 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2842 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002843 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844 motionEvent->getMetaState(), motionEvent->getButtonState(),
2845 motionEvent->getEdgeFlags(),
2846 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002847 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002848 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2849 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 lastInjectedEntry = firstInjectedEntry;
2851 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2852 sampleEventTimes += 1;
2853 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002854 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2855 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002856 motionEvent->getDeviceId(), motionEvent->getSource(),
2857 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002858 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859 motionEvent->getMetaState(), motionEvent->getButtonState(),
2860 motionEvent->getEdgeFlags(),
2861 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002862 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002863 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2864 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865 lastInjectedEntry->next = nextInjectedEntry;
2866 lastInjectedEntry = nextInjectedEntry;
2867 }
2868 break;
2869 }
2870
2871 default:
2872 ALOGW("Cannot inject event of type %d", event->getType());
2873 return INPUT_EVENT_INJECTION_FAILED;
2874 }
2875
2876 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2877 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2878 injectionState->injectionIsAsync = true;
2879 }
2880
2881 injectionState->refCount += 1;
2882 lastInjectedEntry->injectionState = injectionState;
2883
2884 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002885 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886 EventEntry* nextEntry = entry->next;
2887 needWake |= enqueueInboundEventLocked(entry);
2888 entry = nextEntry;
2889 }
2890
2891 mLock.unlock();
2892
2893 if (needWake) {
2894 mLooper->wake();
2895 }
2896
2897 int32_t injectionResult;
2898 { // acquire lock
2899 AutoMutex _l(mLock);
2900
2901 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2902 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2903 } else {
2904 for (;;) {
2905 injectionResult = injectionState->injectionResult;
2906 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2907 break;
2908 }
2909
2910 nsecs_t remainingTimeout = endTime - now();
2911 if (remainingTimeout <= 0) {
2912#if DEBUG_INJECTION
2913 ALOGD("injectInputEvent - Timed out waiting for injection result "
2914 "to become available.");
2915#endif
2916 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2917 break;
2918 }
2919
2920 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2921 }
2922
2923 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2924 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2925 while (injectionState->pendingForegroundDispatches != 0) {
2926#if DEBUG_INJECTION
2927 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2928 injectionState->pendingForegroundDispatches);
2929#endif
2930 nsecs_t remainingTimeout = endTime - now();
2931 if (remainingTimeout <= 0) {
2932#if DEBUG_INJECTION
2933 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2934 "dispatches to finish.");
2935#endif
2936 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2937 break;
2938 }
2939
2940 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2941 }
2942 }
2943 }
2944
2945 injectionState->release();
2946 } // release lock
2947
2948#if DEBUG_INJECTION
2949 ALOGD("injectInputEvent - Finished with result %d. "
2950 "injectorPid=%d, injectorUid=%d",
2951 injectionResult, injectorPid, injectorUid);
2952#endif
2953
2954 return injectionResult;
2955}
2956
2957bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2958 return injectorUid == 0
2959 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2960}
2961
2962void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2963 InjectionState* injectionState = entry->injectionState;
2964 if (injectionState) {
2965#if DEBUG_INJECTION
2966 ALOGD("Setting input event injection result to %d. "
2967 "injectorPid=%d, injectorUid=%d",
2968 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2969#endif
2970
2971 if (injectionState->injectionIsAsync
2972 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2973 // Log the outcome since the injector did not wait for the injection result.
2974 switch (injectionResult) {
2975 case INPUT_EVENT_INJECTION_SUCCEEDED:
2976 ALOGV("Asynchronous input event injection succeeded.");
2977 break;
2978 case INPUT_EVENT_INJECTION_FAILED:
2979 ALOGW("Asynchronous input event injection failed.");
2980 break;
2981 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2982 ALOGW("Asynchronous input event injection permission denied.");
2983 break;
2984 case INPUT_EVENT_INJECTION_TIMED_OUT:
2985 ALOGW("Asynchronous input event injection timed out.");
2986 break;
2987 }
2988 }
2989
2990 injectionState->injectionResult = injectionResult;
2991 mInjectionResultAvailableCondition.broadcast();
2992 }
2993}
2994
2995void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2996 InjectionState* injectionState = entry->injectionState;
2997 if (injectionState) {
2998 injectionState->pendingForegroundDispatches += 1;
2999 }
3000}
3001
3002void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3003 InjectionState* injectionState = entry->injectionState;
3004 if (injectionState) {
3005 injectionState->pendingForegroundDispatches -= 1;
3006
3007 if (injectionState->pendingForegroundDispatches == 0) {
3008 mInjectionSyncFinishedCondition.broadcast();
3009 }
3010 }
3011}
3012
Arthur Hungb92218b2018-08-14 12:00:21 +08003013Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
3014 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
3015 mWindowHandlesByDisplay.find(displayId);
3016 if(it != mWindowHandlesByDisplay.end()) {
3017 return it->second;
3018 }
3019
3020 // Return an empty one if nothing found.
3021 return Vector<sp<InputWindowHandle>>();
3022}
3023
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
3025 const sp<InputChannel>& inputChannel) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003026 for (auto& it : mWindowHandlesByDisplay) {
3027 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3028 size_t numWindows = windowHandles.size();
3029 for (size_t i = 0; i < numWindows; i++) {
3030 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
Robert Carr5c8a0262018-10-03 16:30:44 -07003031 if (windowHandle->getToken() == inputChannel->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003032 return windowHandle;
3033 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034 }
3035 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003036 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037}
3038
3039bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003040 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003041 for (auto& it : mWindowHandlesByDisplay) {
3042 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3043 size_t numWindows = windowHandles.size();
3044 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003045 if (windowHandles.itemAt(i)->getToken()
3046 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003047 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003048 ALOGE("Found window %s in display %" PRId32
3049 ", but it should belong to display %" PRId32,
3050 windowHandle->getName().c_str(), it.first,
3051 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003052 }
3053 return true;
3054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055 }
3056 }
3057 return false;
3058}
3059
Robert Carr5c8a0262018-10-03 16:30:44 -07003060sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3061 size_t count = mInputChannelsByToken.count(token);
3062 if (count == 0) {
3063 return nullptr;
3064 }
3065 return mInputChannelsByToken.at(token);
3066}
3067
Arthur Hungb92218b2018-08-14 12:00:21 +08003068/**
3069 * Called from InputManagerService, update window handle list by displayId that can receive input.
3070 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3071 * If set an empty list, remove all handles from the specific display.
3072 * For focused handle, check if need to change and send a cancel event to previous one.
3073 * For removed handle, check if need to send a cancel event if already in touch.
3074 */
3075void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3076 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003078 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079#endif
3080 { // acquire lock
3081 AutoMutex _l(mLock);
3082
Arthur Hungb92218b2018-08-14 12:00:21 +08003083 // Copy old handles for release if they are no longer present.
3084 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085
Tiger Huang721e26f2018-07-24 22:26:19 +08003086 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003088
3089 if (inputWindowHandles.isEmpty()) {
3090 // Remove all handles on a display if there are no windows left.
3091 mWindowHandlesByDisplay.erase(displayId);
3092 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003093 // Since we compare the pointer of input window handles across window updates, we need
3094 // to make sure the handle object for the same window stays unchanged across updates.
3095 const Vector<sp<InputWindowHandle>>& oldHandles = mWindowHandlesByDisplay[displayId];
3096 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3097 for (size_t i = 0; i < oldHandles.size(); i++) {
3098 const sp<InputWindowHandle>& handle = oldHandles.itemAt(i);
3099 oldHandlesByTokens[handle->getToken()] = handle;
3100 }
3101
3102 const size_t numWindows = inputWindowHandles.size();
3103 Vector<sp<InputWindowHandle>> newHandles;
Arthur Hungb92218b2018-08-14 12:00:21 +08003104 for (size_t i = 0; i < numWindows; i++) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003105 const sp<InputWindowHandle>& handle = inputWindowHandles.itemAt(i);
3106 if (!handle->updateInfo() || getInputChannelLocked(handle->getToken()) == nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003107 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003108 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003109 continue;
3110 }
3111
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003112 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003113 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003114 handle->getName().c_str(), displayId,
3115 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003116 continue;
3117 }
3118
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003119 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3120 const sp<InputWindowHandle> oldHandle =
3121 oldHandlesByTokens.at(handle->getToken());
3122 oldHandle->updateFrom(handle);
3123 newHandles.push_back(oldHandle);
3124 } else {
3125 newHandles.push_back(handle);
3126 }
3127 }
3128
3129 for (size_t i = 0; i < newHandles.size(); i++) {
3130 const sp<InputWindowHandle>& windowHandle = newHandles.itemAt(i);
Siarhei Vishniakou49ee3232018-12-03 15:10:36 -06003131 if (windowHandle->getInfo()->hasFocus && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003132 newFocusedWindowHandle = windowHandle;
3133 }
3134 if (windowHandle == mLastHoverWindowHandle) {
3135 foundHoveredWindow = true;
3136 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003137 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003138
3139 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003140 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141 }
3142
3143 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003144 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145 }
3146
Tiger Huang721e26f2018-07-24 22:26:19 +08003147 sp<InputWindowHandle> oldFocusedWindowHandle =
3148 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3149
3150 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3151 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003153 ALOGD("Focus left window: %s in display %" PRId32,
3154 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003156 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3157 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003158 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3160 "focus left window");
3161 synthesizeCancelationEventsForInputChannelLocked(
3162 focusedInputChannel, options);
3163 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003164 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003166 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003168 ALOGD("Focus entered window: %s in display %" PRId32,
3169 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003171 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 }
Robert Carrf759f162018-11-13 12:57:11 -08003173
3174 if (mFocusedDisplayId == displayId) {
3175 onFocusChangedLocked(newFocusedWindowHandle);
3176 }
3177
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 }
3179
Arthur Hungb92218b2018-08-14 12:00:21 +08003180 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3181 if (stateIndex >= 0) {
3182 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003183 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003184 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003185 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003187 ALOGD("Touched window was removed: %s in display %" PRId32,
3188 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003190 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003191 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003192 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003193 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3194 "touched window was removed");
3195 synthesizeCancelationEventsForInputChannelLocked(
3196 touchedInputChannel, options);
3197 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003198 state.windows.removeAt(i);
3199 } else {
3200 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202 }
3203 }
3204
3205 // Release information for windows that are no longer present.
3206 // This ensures that unused input channels are released promptly.
3207 // Otherwise, they might stick around until the window handle is destroyed
3208 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003209 size_t numWindows = oldWindowHandles.size();
3210 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003212 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003213#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003214 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003216 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 }
3218 }
3219 } // release lock
3220
3221 // Wake up poll loop since it may need to make new input dispatching choices.
3222 mLooper->wake();
3223}
3224
3225void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003226 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003228 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229#endif
3230 { // acquire lock
3231 AutoMutex _l(mLock);
3232
Tiger Huang721e26f2018-07-24 22:26:19 +08003233 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3234 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003235 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003236 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3237 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003239 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003241 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003243 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003245 oldFocusedApplicationHandle->releaseInfo();
3246 oldFocusedApplicationHandle.clear();
3247 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 }
3249
3250#if DEBUG_FOCUS
3251 //logDispatchStateLocked();
3252#endif
3253 } // release lock
3254
3255 // Wake up poll loop since it may need to make new input dispatching choices.
3256 mLooper->wake();
3257}
3258
Tiger Huang721e26f2018-07-24 22:26:19 +08003259/**
3260 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3261 * the display not specified.
3262 *
3263 * We track any unreleased events for each window. If a window loses the ability to receive the
3264 * released event, we will send a cancel event to it. So when the focused display is changed, we
3265 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3266 * display. The display-specified events won't be affected.
3267 */
3268void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3269#if DEBUG_FOCUS
3270 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3271#endif
3272 { // acquire lock
3273 AutoMutex _l(mLock);
3274
3275 if (mFocusedDisplayId != displayId) {
3276 sp<InputWindowHandle> oldFocusedWindowHandle =
3277 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3278 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003279 sp<InputChannel> inputChannel =
3280 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003281 if (inputChannel != nullptr) {
3282 CancelationOptions options(
3283 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3284 "The display which contains this window no longer has focus.");
3285 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3286 }
3287 }
3288 mFocusedDisplayId = displayId;
3289
3290 // Sanity check
3291 sp<InputWindowHandle> newFocusedWindowHandle =
3292 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
Robert Carrf759f162018-11-13 12:57:11 -08003293 onFocusChangedLocked(newFocusedWindowHandle);
3294
Tiger Huang721e26f2018-07-24 22:26:19 +08003295 if (newFocusedWindowHandle == nullptr) {
3296 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3297 if (!mFocusedWindowHandlesByDisplay.empty()) {
3298 ALOGE("But another display has a focused window:");
3299 for (auto& it : mFocusedWindowHandlesByDisplay) {
3300 const int32_t displayId = it.first;
3301 const sp<InputWindowHandle>& windowHandle = it.second;
3302 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3303 displayId, windowHandle->getName().c_str());
3304 }
3305 }
3306 }
3307 }
3308
3309#if DEBUG_FOCUS
3310 logDispatchStateLocked();
3311#endif
3312 } // release lock
3313
3314 // Wake up poll loop since it may need to make new input dispatching choices.
3315 mLooper->wake();
3316}
3317
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3319#if DEBUG_FOCUS
3320 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3321#endif
3322
3323 bool changed;
3324 { // acquire lock
3325 AutoMutex _l(mLock);
3326
3327 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3328 if (mDispatchFrozen && !frozen) {
3329 resetANRTimeoutsLocked();
3330 }
3331
3332 if (mDispatchEnabled && !enabled) {
3333 resetAndDropEverythingLocked("dispatcher is being disabled");
3334 }
3335
3336 mDispatchEnabled = enabled;
3337 mDispatchFrozen = frozen;
3338 changed = true;
3339 } else {
3340 changed = false;
3341 }
3342
3343#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003344 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345#endif
3346 } // release lock
3347
3348 if (changed) {
3349 // Wake up poll loop since it may need to make new input dispatching choices.
3350 mLooper->wake();
3351 }
3352}
3353
3354void InputDispatcher::setInputFilterEnabled(bool enabled) {
3355#if DEBUG_FOCUS
3356 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3357#endif
3358
3359 { // acquire lock
3360 AutoMutex _l(mLock);
3361
3362 if (mInputFilterEnabled == enabled) {
3363 return;
3364 }
3365
3366 mInputFilterEnabled = enabled;
3367 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3368 } // release lock
3369
3370 // Wake up poll loop since there might be work to do to drop everything.
3371 mLooper->wake();
3372}
3373
3374bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
3375 const sp<InputChannel>& toChannel) {
3376#if DEBUG_FOCUS
3377 ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003378 fromChannel->getName().c_str(), toChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379#endif
3380 { // acquire lock
3381 AutoMutex _l(mLock);
3382
3383 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
3384 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
Yi Kong9b14ac62018-07-17 13:48:38 -07003385 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386#if DEBUG_FOCUS
3387 ALOGD("Cannot transfer focus because from or to window not found.");
3388#endif
3389 return false;
3390 }
3391 if (fromWindowHandle == toWindowHandle) {
3392#if DEBUG_FOCUS
3393 ALOGD("Trivial transfer to same window.");
3394#endif
3395 return true;
3396 }
3397 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3398#if DEBUG_FOCUS
3399 ALOGD("Cannot transfer focus because windows are on different displays.");
3400#endif
3401 return false;
3402 }
3403
3404 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003405 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3406 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3407 for (size_t i = 0; i < state.windows.size(); i++) {
3408 const TouchedWindow& touchedWindow = state.windows[i];
3409 if (touchedWindow.windowHandle == fromWindowHandle) {
3410 int32_t oldTargetFlags = touchedWindow.targetFlags;
3411 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412
Jeff Brownf086ddb2014-02-11 14:28:48 -08003413 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414
Jeff Brownf086ddb2014-02-11 14:28:48 -08003415 int32_t newTargetFlags = oldTargetFlags
3416 & (InputTarget::FLAG_FOREGROUND
3417 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3418 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419
Jeff Brownf086ddb2014-02-11 14:28:48 -08003420 found = true;
3421 goto Found;
3422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 }
3424 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003425Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426
3427 if (! found) {
3428#if DEBUG_FOCUS
3429 ALOGD("Focus transfer failed because from window did not have focus.");
3430#endif
3431 return false;
3432 }
3433
3434 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3435 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3436 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3437 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3438 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3439
3440 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3441 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3442 "transferring touch focus from this window to another window");
3443 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3444 }
3445
3446#if DEBUG_FOCUS
3447 logDispatchStateLocked();
3448#endif
3449 } // release lock
3450
3451 // Wake up poll loop since it may need to make new input dispatching choices.
3452 mLooper->wake();
3453 return true;
3454}
3455
3456void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3457#if DEBUG_FOCUS
3458 ALOGD("Resetting and dropping all events (%s).", reason);
3459#endif
3460
3461 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3462 synthesizeCancelationEventsForAllConnectionsLocked(options);
3463
3464 resetKeyRepeatLocked();
3465 releasePendingEventLocked();
3466 drainInboundQueueLocked();
3467 resetANRTimeoutsLocked();
3468
Jeff Brownf086ddb2014-02-11 14:28:48 -08003469 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003471 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472}
3473
3474void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003475 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476 dumpDispatchStateLocked(dump);
3477
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003478 std::istringstream stream(dump);
3479 std::string line;
3480
3481 while (std::getline(stream, line, '\n')) {
3482 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003483 }
3484}
3485
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003486void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3487 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3488 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003489 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490
Tiger Huang721e26f2018-07-24 22:26:19 +08003491 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3492 dump += StringPrintf(INDENT "FocusedApplications:\n");
3493 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3494 const int32_t displayId = it.first;
3495 const sp<InputApplicationHandle>& applicationHandle = it.second;
3496 dump += StringPrintf(
3497 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3498 displayId,
3499 applicationHandle->getName().c_str(),
3500 applicationHandle->getDispatchingTimeout(
3501 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3502 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003504 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003506
3507 if (!mFocusedWindowHandlesByDisplay.empty()) {
3508 dump += StringPrintf(INDENT "FocusedWindows:\n");
3509 for (auto& it : mFocusedWindowHandlesByDisplay) {
3510 const int32_t displayId = it.first;
3511 const sp<InputWindowHandle>& windowHandle = it.second;
3512 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3513 displayId, windowHandle->getName().c_str());
3514 }
3515 } else {
3516 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3517 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518
Jeff Brownf086ddb2014-02-11 14:28:48 -08003519 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003520 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003521 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3522 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003523 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003524 state.displayId, toString(state.down), toString(state.split),
3525 state.deviceId, state.source);
3526 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003527 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003528 for (size_t i = 0; i < state.windows.size(); i++) {
3529 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003530 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3531 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003532 touchedWindow.pointerIds.value,
3533 touchedWindow.targetFlags);
3534 }
3535 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003536 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003537 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 }
3539 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003540 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003541 }
3542
Arthur Hungb92218b2018-08-14 12:00:21 +08003543 if (!mWindowHandlesByDisplay.empty()) {
3544 for (auto& it : mWindowHandlesByDisplay) {
3545 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003546 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003547 if (!windowHandles.isEmpty()) {
3548 dump += INDENT2 "Windows:\n";
3549 for (size_t i = 0; i < windowHandles.size(); i++) {
3550 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3551 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552
Arthur Hungb92218b2018-08-14 12:00:21 +08003553 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
3554 "paused=%s, hasFocus=%s, hasWallpaper=%s, "
3555 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003556 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003557 "touchableRegion=",
3558 i, windowInfo->name.c_str(), windowInfo->displayId,
3559 toString(windowInfo->paused),
3560 toString(windowInfo->hasFocus),
3561 toString(windowInfo->hasWallpaper),
3562 toString(windowInfo->visible),
3563 toString(windowInfo->canReceiveKeys),
3564 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3565 windowInfo->layer,
3566 windowInfo->frameLeft, windowInfo->frameTop,
3567 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003568 windowInfo->globalScaleFactor,
3569 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003570 dumpRegion(dump, windowInfo->touchableRegion);
3571 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3572 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3573 windowInfo->ownerPid, windowInfo->ownerUid,
3574 windowInfo->dispatchingTimeout / 1000000.0);
3575 }
3576 } else {
3577 dump += INDENT2 "Windows: <none>\n";
3578 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579 }
3580 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003581 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 }
3583
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003584 if (!mMonitoringChannelsByDisplay.empty()) {
3585 for (auto& it : mMonitoringChannelsByDisplay) {
3586 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003587 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003588 const size_t numChannels = monitoringChannels.size();
3589 for (size_t i = 0; i < numChannels; i++) {
3590 const sp<InputChannel>& channel = monitoringChannels[i];
3591 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3592 }
3593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003595 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 }
3597
3598 nsecs_t currentTime = now();
3599
3600 // Dump recently dispatched or dropped events from oldest to newest.
3601 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003602 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003604 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003606 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 (currentTime - entry->eventTime) * 0.000001f);
3608 }
3609 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003610 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 }
3612
3613 // Dump event currently being dispatched.
3614 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003615 dump += INDENT "PendingEvent:\n";
3616 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003618 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3620 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003621 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 }
3623
3624 // Dump inbound events from oldest to newest.
3625 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003626 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003628 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003630 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 (currentTime - entry->eventTime) * 0.000001f);
3632 }
3633 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003634 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 }
3636
Michael Wright78f24442014-08-06 15:55:28 -07003637 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003638 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003639 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3640 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3641 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003642 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003643 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3644 }
3645 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003646 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003647 }
3648
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003650 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003651 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3652 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003653 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003655 i, connection->getInputChannelName().c_str(),
3656 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 connection->getStatusLabel(), toString(connection->monitor),
3658 toString(connection->inputPublisherBlocked));
3659
3660 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003661 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 connection->outboundQueue.count());
3663 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3664 entry = entry->next) {
3665 dump.append(INDENT4);
3666 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003667 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 entry->targetFlags, entry->resolvedAction,
3669 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3670 }
3671 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003672 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673 }
3674
3675 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003676 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 connection->waitQueue.count());
3678 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3679 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003680 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003682 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 "age=%0.1fms, wait=%0.1fms\n",
3684 entry->targetFlags, entry->resolvedAction,
3685 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3686 (currentTime - entry->deliveryTime) * 0.000001f);
3687 }
3688 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003689 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 }
3691 }
3692 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003693 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 }
3695
3696 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003697 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 (mAppSwitchDueTime - now()) / 1000000.0);
3699 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003700 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 }
3702
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003703 dump += INDENT "Configuration:\n";
3704 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003706 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 mConfig.keyRepeatTimeout * 0.000001f);
3708}
3709
Robert Carr803535b2018-08-02 16:38:15 -07003710status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003711#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003712 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3713 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714#endif
3715
3716 { // acquire lock
3717 AutoMutex _l(mLock);
3718
Robert Carr4e670e52018-08-15 13:26:12 -07003719 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3720 // treat inputChannel as monitor channel for displayId.
3721 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3722 if (monitor) {
3723 inputChannel->setToken(new BBinder());
3724 }
3725
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 if (getConnectionIndexLocked(inputChannel) >= 0) {
3727 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003728 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 return BAD_VALUE;
3730 }
3731
Robert Carr803535b2018-08-02 16:38:15 -07003732 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733
3734 int fd = inputChannel->getFd();
3735 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003736 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003738 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003740 Vector<sp<InputChannel>>& monitoringChannels =
3741 mMonitoringChannelsByDisplay[displayId];
3742 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 }
3744
3745 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3746 } // release lock
3747
3748 // Wake the looper because some connections have changed.
3749 mLooper->wake();
3750 return OK;
3751}
3752
3753status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3754#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003755 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756#endif
3757
3758 { // acquire lock
3759 AutoMutex _l(mLock);
3760
3761 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3762 if (status) {
3763 return status;
3764 }
3765 } // release lock
3766
3767 // Wake the poll loop because removing the connection may have changed the current
3768 // synchronization state.
3769 mLooper->wake();
3770 return OK;
3771}
3772
3773status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3774 bool notify) {
3775 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3776 if (connectionIndex < 0) {
3777 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003778 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779 return BAD_VALUE;
3780 }
3781
3782 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3783 mConnectionsByFd.removeItemsAt(connectionIndex);
3784
Robert Carr5c8a0262018-10-03 16:30:44 -07003785 mInputChannelsByToken.erase(inputChannel->getToken());
3786
Michael Wrightd02c5b62014-02-10 15:10:22 -08003787 if (connection->monitor) {
3788 removeMonitorChannelLocked(inputChannel);
3789 }
3790
3791 mLooper->removeFd(inputChannel->getFd());
3792
3793 nsecs_t currentTime = now();
3794 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3795
3796 connection->status = Connection::STATUS_ZOMBIE;
3797 return OK;
3798}
3799
3800void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003801 for (auto it = mMonitoringChannelsByDisplay.begin();
3802 it != mMonitoringChannelsByDisplay.end(); ) {
3803 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3804 const size_t numChannels = monitoringChannels.size();
3805 for (size_t i = 0; i < numChannels; i++) {
3806 if (monitoringChannels[i] == inputChannel) {
3807 monitoringChannels.removeAt(i);
3808 break;
3809 }
3810 }
3811 if (monitoringChannels.empty()) {
3812 it = mMonitoringChannelsByDisplay.erase(it);
3813 } else {
3814 ++it;
3815 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816 }
3817}
3818
3819ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003820 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003821 return -1;
3822 }
3823
Robert Carr4e670e52018-08-15 13:26:12 -07003824 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3825 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3826 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3827 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003828 }
3829 }
Robert Carr4e670e52018-08-15 13:26:12 -07003830
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 return -1;
3832}
3833
3834void InputDispatcher::onDispatchCycleFinishedLocked(
3835 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3836 CommandEntry* commandEntry = postCommandLocked(
3837 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3838 commandEntry->connection = connection;
3839 commandEntry->eventTime = currentTime;
3840 commandEntry->seq = seq;
3841 commandEntry->handled = handled;
3842}
3843
3844void InputDispatcher::onDispatchCycleBrokenLocked(
3845 nsecs_t currentTime, const sp<Connection>& connection) {
3846 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003847 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848
3849 CommandEntry* commandEntry = postCommandLocked(
3850 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3851 commandEntry->connection = connection;
3852}
3853
Robert Carrf759f162018-11-13 12:57:11 -08003854void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& newFocus) {
3855 sp<IBinder> token = newFocus != nullptr ? newFocus->getToken() : nullptr;
3856 CommandEntry* commandEntry = postCommandLocked(
3857 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
3858 commandEntry->token = token;
3859}
3860
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861void InputDispatcher::onANRLocked(
3862 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3863 const sp<InputWindowHandle>& windowHandle,
3864 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3865 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3866 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3867 ALOGI("Application is not responding: %s. "
3868 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003869 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870 dispatchLatency, waitDuration, reason);
3871
3872 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003873 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874 struct tm tm;
3875 localtime_r(&t, &tm);
3876 char timestr[64];
3877 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3878 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003879 mLastANRState += INDENT "ANR:\n";
3880 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3881 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3882 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3883 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3884 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3885 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003886 dumpDispatchStateLocked(mLastANRState);
3887
3888 CommandEntry* commandEntry = postCommandLocked(
3889 & InputDispatcher::doNotifyANRLockedInterruptible);
3890 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003891 commandEntry->inputChannel = windowHandle != nullptr ?
3892 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003893 commandEntry->reason = reason;
3894}
3895
3896void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3897 CommandEntry* commandEntry) {
3898 mLock.unlock();
3899
3900 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3901
3902 mLock.lock();
3903}
3904
3905void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3906 CommandEntry* commandEntry) {
3907 sp<Connection> connection = commandEntry->connection;
3908
3909 if (connection->status != Connection::STATUS_ZOMBIE) {
3910 mLock.unlock();
3911
Robert Carr803535b2018-08-02 16:38:15 -07003912 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913
3914 mLock.lock();
3915 }
3916}
3917
Robert Carrf759f162018-11-13 12:57:11 -08003918void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3919 CommandEntry* commandEntry) {
3920 sp<IBinder> token = commandEntry->token;
3921 mLock.unlock();
3922 mPolicy->notifyFocusChanged(token);
3923 mLock.lock();
3924}
3925
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926void InputDispatcher::doNotifyANRLockedInterruptible(
3927 CommandEntry* commandEntry) {
3928 mLock.unlock();
3929
3930 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003931 commandEntry->inputApplicationHandle,
3932 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933 commandEntry->reason);
3934
3935 mLock.lock();
3936
3937 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003938 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003939}
3940
3941void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3942 CommandEntry* commandEntry) {
3943 KeyEntry* entry = commandEntry->keyEntry;
3944
3945 KeyEvent event;
3946 initializeKeyEvent(&event, entry);
3947
3948 mLock.unlock();
3949
Michael Wright2b3c3302018-03-02 17:19:13 +00003950 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003951 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3952 commandEntry->inputChannel->getToken() : nullptr;
3953 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003955 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3956 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3957 std::to_string(t.duration().count()).c_str());
3958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959
3960 mLock.lock();
3961
3962 if (delay < 0) {
3963 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3964 } else if (!delay) {
3965 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3966 } else {
3967 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3968 entry->interceptKeyWakeupTime = now() + delay;
3969 }
3970 entry->release();
3971}
3972
3973void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3974 CommandEntry* commandEntry) {
3975 sp<Connection> connection = commandEntry->connection;
3976 nsecs_t finishTime = commandEntry->eventTime;
3977 uint32_t seq = commandEntry->seq;
3978 bool handled = commandEntry->handled;
3979
3980 // Handle post-event policy actions.
3981 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
3982 if (dispatchEntry) {
3983 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
3984 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003985 std::string msg =
3986 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003987 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003989 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 }
3991
3992 bool restartEvent;
3993 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
3994 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
3995 restartEvent = afterKeyEventLockedInterruptible(connection,
3996 dispatchEntry, keyEntry, handled);
3997 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
3998 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
3999 restartEvent = afterMotionEventLockedInterruptible(connection,
4000 dispatchEntry, motionEntry, handled);
4001 } else {
4002 restartEvent = false;
4003 }
4004
4005 // Dequeue the event and start the next cycle.
4006 // Note that because the lock might have been released, it is possible that the
4007 // contents of the wait queue to have been drained, so we need to double-check
4008 // a few things.
4009 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4010 connection->waitQueue.dequeue(dispatchEntry);
4011 traceWaitQueueLengthLocked(connection);
4012 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4013 connection->outboundQueue.enqueueAtHead(dispatchEntry);
4014 traceOutboundQueueLengthLocked(connection);
4015 } else {
4016 releaseDispatchEntryLocked(dispatchEntry);
4017 }
4018 }
4019
4020 // Start the next dispatch cycle for this connection.
4021 startDispatchCycleLocked(now(), connection);
4022 }
4023}
4024
4025bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4026 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004027 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4028 return false;
4029 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004031 // Get the fallback key state.
4032 // Clear it out after dispatching the UP.
4033 int32_t originalKeyCode = keyEntry->keyCode;
4034 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4035 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4036 connection->inputState.removeFallbackKey(originalKeyCode);
4037 }
4038
4039 if (handled || !dispatchEntry->hasForegroundTarget()) {
4040 // If the application handles the original key for which we previously
4041 // generated a fallback or if the window is not a foreground window,
4042 // then cancel the associated fallback key, if any.
4043 if (fallbackKeyCode != -1) {
4044 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004045#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004046 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004047 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4048 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4049 keyEntry->policyFlags);
4050#endif
4051 KeyEvent event;
4052 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004053 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054
4055 mLock.unlock();
4056
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004057 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4058 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004059
4060 mLock.lock();
4061
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004062 // Cancel the fallback key.
4063 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004065 "application handled the original non-fallback key "
4066 "or is no longer a foreground target, "
4067 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068 options.keyCode = fallbackKeyCode;
4069 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004071 connection->inputState.removeFallbackKey(originalKeyCode);
4072 }
4073 } else {
4074 // If the application did not handle a non-fallback key, first check
4075 // that we are in a good state to perform unhandled key event processing
4076 // Then ask the policy what to do with it.
4077 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4078 && keyEntry->repeatCount == 0;
4079 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004081 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4082 "since this is not an initial down. "
4083 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4084 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4085 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004087 return false;
4088 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004089
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004090 // Dispatch the unhandled key to the policy.
4091#if DEBUG_OUTBOUND_EVENT_DETAILS
4092 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4093 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4094 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4095 keyEntry->policyFlags);
4096#endif
4097 KeyEvent event;
4098 initializeKeyEvent(&event, keyEntry);
4099
4100 mLock.unlock();
4101
4102 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4103 &event, keyEntry->policyFlags, &event);
4104
4105 mLock.lock();
4106
4107 if (connection->status != Connection::STATUS_NORMAL) {
4108 connection->inputState.removeFallbackKey(originalKeyCode);
4109 return false;
4110 }
4111
4112 // Latch the fallback keycode for this key on an initial down.
4113 // The fallback keycode cannot change at any other point in the lifecycle.
4114 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004116 fallbackKeyCode = event.getKeyCode();
4117 } else {
4118 fallbackKeyCode = AKEYCODE_UNKNOWN;
4119 }
4120 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4121 }
4122
4123 ALOG_ASSERT(fallbackKeyCode != -1);
4124
4125 // Cancel the fallback key if the policy decides not to send it anymore.
4126 // We will continue to dispatch the key to the policy but we will no
4127 // longer dispatch a fallback key to the application.
4128 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4129 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4130#if DEBUG_OUTBOUND_EVENT_DETAILS
4131 if (fallback) {
4132 ALOGD("Unhandled key event: Policy requested to send key %d"
4133 "as a fallback for %d, but on the DOWN it had requested "
4134 "to send %d instead. Fallback canceled.",
4135 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4136 } else {
4137 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4138 "but on the DOWN it had requested to send %d. "
4139 "Fallback canceled.",
4140 originalKeyCode, fallbackKeyCode);
4141 }
4142#endif
4143
4144 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4145 "canceling fallback, policy no longer desires it");
4146 options.keyCode = fallbackKeyCode;
4147 synthesizeCancelationEventsForConnectionLocked(connection, options);
4148
4149 fallback = false;
4150 fallbackKeyCode = AKEYCODE_UNKNOWN;
4151 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4152 connection->inputState.setFallbackKey(originalKeyCode,
4153 fallbackKeyCode);
4154 }
4155 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156
4157#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004158 {
4159 std::string msg;
4160 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4161 connection->inputState.getFallbackKeys();
4162 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4163 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4164 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004166 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4167 fallbackKeys.size(), msg.c_str());
4168 }
4169#endif
4170
4171 if (fallback) {
4172 // Restart the dispatch cycle using the fallback key.
4173 keyEntry->eventTime = event.getEventTime();
4174 keyEntry->deviceId = event.getDeviceId();
4175 keyEntry->source = event.getSource();
4176 keyEntry->displayId = event.getDisplayId();
4177 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4178 keyEntry->keyCode = fallbackKeyCode;
4179 keyEntry->scanCode = event.getScanCode();
4180 keyEntry->metaState = event.getMetaState();
4181 keyEntry->repeatCount = event.getRepeatCount();
4182 keyEntry->downTime = event.getDownTime();
4183 keyEntry->syntheticRepeat = false;
4184
4185#if DEBUG_OUTBOUND_EVENT_DETAILS
4186 ALOGD("Unhandled key event: Dispatching fallback key. "
4187 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4188 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4189#endif
4190 return true; // restart the event
4191 } else {
4192#if DEBUG_OUTBOUND_EVENT_DETAILS
4193 ALOGD("Unhandled key event: No fallback key.");
4194#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 }
4196 }
4197 return false;
4198}
4199
4200bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4201 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4202 return false;
4203}
4204
4205void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4206 mLock.unlock();
4207
4208 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4209
4210 mLock.lock();
4211}
4212
4213void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004214 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4216 entry->downTime, entry->eventTime);
4217}
4218
4219void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4220 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4221 // TODO Write some statistics about how long we spend waiting.
4222}
4223
4224void InputDispatcher::traceInboundQueueLengthLocked() {
4225 if (ATRACE_ENABLED()) {
4226 ATRACE_INT("iq", mInboundQueue.count());
4227 }
4228}
4229
4230void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4231 if (ATRACE_ENABLED()) {
4232 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004233 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 ATRACE_INT(counterName, connection->outboundQueue.count());
4235 }
4236}
4237
4238void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4239 if (ATRACE_ENABLED()) {
4240 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004241 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 ATRACE_INT(counterName, connection->waitQueue.count());
4243 }
4244}
4245
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004246void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 AutoMutex _l(mLock);
4248
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004249 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 dumpDispatchStateLocked(dump);
4251
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004252 if (!mLastANRState.empty()) {
4253 dump += "\nInput Dispatcher State at time of last ANR:\n";
4254 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 }
4256}
4257
4258void InputDispatcher::monitor() {
4259 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4260 mLock.lock();
4261 mLooper->wake();
4262 mDispatcherIsAliveCondition.wait(mLock);
4263 mLock.unlock();
4264}
4265
4266
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267// --- InputDispatcher::InjectionState ---
4268
4269InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4270 refCount(1),
4271 injectorPid(injectorPid), injectorUid(injectorUid),
4272 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4273 pendingForegroundDispatches(0) {
4274}
4275
4276InputDispatcher::InjectionState::~InjectionState() {
4277}
4278
4279void InputDispatcher::InjectionState::release() {
4280 refCount -= 1;
4281 if (refCount == 0) {
4282 delete this;
4283 } else {
4284 ALOG_ASSERT(refCount > 0);
4285 }
4286}
4287
4288
4289// --- InputDispatcher::EventEntry ---
4290
Prabir Pradhan42611e02018-11-27 14:04:02 -08004291InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4292 nsecs_t eventTime, uint32_t policyFlags) :
4293 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4294 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295}
4296
4297InputDispatcher::EventEntry::~EventEntry() {
4298 releaseInjectionState();
4299}
4300
4301void InputDispatcher::EventEntry::release() {
4302 refCount -= 1;
4303 if (refCount == 0) {
4304 delete this;
4305 } else {
4306 ALOG_ASSERT(refCount > 0);
4307 }
4308}
4309
4310void InputDispatcher::EventEntry::releaseInjectionState() {
4311 if (injectionState) {
4312 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004313 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 }
4315}
4316
4317
4318// --- InputDispatcher::ConfigurationChangedEntry ---
4319
Prabir Pradhan42611e02018-11-27 14:04:02 -08004320InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4321 uint32_t sequenceNum, nsecs_t eventTime) :
4322 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323}
4324
4325InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4326}
4327
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004328void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4329 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330}
4331
4332
4333// --- InputDispatcher::DeviceResetEntry ---
4334
Prabir Pradhan42611e02018-11-27 14:04:02 -08004335InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4336 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4337 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 deviceId(deviceId) {
4339}
4340
4341InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4342}
4343
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004344void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4345 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346 deviceId, policyFlags);
4347}
4348
4349
4350// --- InputDispatcher::KeyEntry ---
4351
Prabir Pradhan42611e02018-11-27 14:04:02 -08004352InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004353 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4355 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004356 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004357 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4359 repeatCount(repeatCount), downTime(downTime),
4360 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4361 interceptKeyWakeupTime(0) {
4362}
4363
4364InputDispatcher::KeyEntry::~KeyEntry() {
4365}
4366
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004367void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004368 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4370 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004371 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004372 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373}
4374
4375void InputDispatcher::KeyEntry::recycle() {
4376 releaseInjectionState();
4377
4378 dispatchInProgress = false;
4379 syntheticRepeat = false;
4380 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4381 interceptKeyWakeupTime = 0;
4382}
4383
4384
4385// --- InputDispatcher::MotionEntry ---
4386
Prabir Pradhan42611e02018-11-27 14:04:02 -08004387InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004388 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4389 int32_t actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01004390 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4391 float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004392 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004393 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4394 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004395 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004397 deviceId(deviceId), source(source), displayId(displayId), action(action),
4398 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Michael Wright7b159c92015-05-14 14:48:03 +01004399 edgeFlags(edgeFlags), xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004400 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004401 for (uint32_t i = 0; i < pointerCount; i++) {
4402 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4403 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004404 if (xOffset || yOffset) {
4405 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004407 }
4408}
4409
4410InputDispatcher::MotionEntry::~MotionEntry() {
4411}
4412
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004413void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004414 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004415 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004416 "edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004417 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
4418 metaState, buttonState, edgeFlags, xPrecision, yPrecision);
4419
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420 for (uint32_t i = 0; i < pointerCount; i++) {
4421 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004422 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004423 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004424 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004425 pointerCoords[i].getX(), pointerCoords[i].getY());
4426 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004427 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428}
4429
4430
4431// --- InputDispatcher::DispatchEntry ---
4432
4433volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4434
4435InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004436 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4437 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438 seq(nextSeq()),
4439 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004440 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4441 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004442 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4443 eventEntry->refCount += 1;
4444}
4445
4446InputDispatcher::DispatchEntry::~DispatchEntry() {
4447 eventEntry->release();
4448}
4449
4450uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4451 // Sequence number 0 is reserved and will never be returned.
4452 uint32_t seq;
4453 do {
4454 seq = android_atomic_inc(&sNextSeqAtomic);
4455 } while (!seq);
4456 return seq;
4457}
4458
4459
4460// --- InputDispatcher::InputState ---
4461
4462InputDispatcher::InputState::InputState() {
4463}
4464
4465InputDispatcher::InputState::~InputState() {
4466}
4467
4468bool InputDispatcher::InputState::isNeutral() const {
4469 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4470}
4471
4472bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4473 int32_t displayId) const {
4474 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4475 const MotionMemento& memento = mMotionMementos.itemAt(i);
4476 if (memento.deviceId == deviceId
4477 && memento.source == source
4478 && memento.displayId == displayId
4479 && memento.hovering) {
4480 return true;
4481 }
4482 }
4483 return false;
4484}
4485
4486bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4487 int32_t action, int32_t flags) {
4488 switch (action) {
4489 case AKEY_EVENT_ACTION_UP: {
4490 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4491 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4492 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4493 mFallbackKeys.removeItemsAt(i);
4494 } else {
4495 i += 1;
4496 }
4497 }
4498 }
4499 ssize_t index = findKeyMemento(entry);
4500 if (index >= 0) {
4501 mKeyMementos.removeAt(index);
4502 return true;
4503 }
4504 /* FIXME: We can't just drop the key up event because that prevents creating
4505 * popup windows that are automatically shown when a key is held and then
4506 * dismissed when the key is released. The problem is that the popup will
4507 * not have received the original key down, so the key up will be considered
4508 * to be inconsistent with its observed state. We could perhaps handle this
4509 * by synthesizing a key down but that will cause other problems.
4510 *
4511 * So for now, allow inconsistent key up events to be dispatched.
4512 *
4513#if DEBUG_OUTBOUND_EVENT_DETAILS
4514 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4515 "keyCode=%d, scanCode=%d",
4516 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4517#endif
4518 return false;
4519 */
4520 return true;
4521 }
4522
4523 case AKEY_EVENT_ACTION_DOWN: {
4524 ssize_t index = findKeyMemento(entry);
4525 if (index >= 0) {
4526 mKeyMementos.removeAt(index);
4527 }
4528 addKeyMemento(entry, flags);
4529 return true;
4530 }
4531
4532 default:
4533 return true;
4534 }
4535}
4536
4537bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4538 int32_t action, int32_t flags) {
4539 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4540 switch (actionMasked) {
4541 case AMOTION_EVENT_ACTION_UP:
4542 case AMOTION_EVENT_ACTION_CANCEL: {
4543 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4544 if (index >= 0) {
4545 mMotionMementos.removeAt(index);
4546 return true;
4547 }
4548#if DEBUG_OUTBOUND_EVENT_DETAILS
4549 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004550 "displayId=%" PRId32 ", actionMasked=%d",
4551 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004552#endif
4553 return false;
4554 }
4555
4556 case AMOTION_EVENT_ACTION_DOWN: {
4557 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4558 if (index >= 0) {
4559 mMotionMementos.removeAt(index);
4560 }
4561 addMotionMemento(entry, flags, false /*hovering*/);
4562 return true;
4563 }
4564
4565 case AMOTION_EVENT_ACTION_POINTER_UP:
4566 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4567 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004568 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4569 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4570 // generate cancellation events for these since they're based in relative rather than
4571 // absolute units.
4572 return true;
4573 }
4574
Michael Wrightd02c5b62014-02-10 15:10:22 -08004575 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004576
4577 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4578 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4579 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4580 // other value and we need to track the motion so we can send cancellation events for
4581 // anything generating fallback events (e.g. DPad keys for joystick movements).
4582 if (index >= 0) {
4583 if (entry->pointerCoords[0].isEmpty()) {
4584 mMotionMementos.removeAt(index);
4585 } else {
4586 MotionMemento& memento = mMotionMementos.editItemAt(index);
4587 memento.setPointers(entry);
4588 }
4589 } else if (!entry->pointerCoords[0].isEmpty()) {
4590 addMotionMemento(entry, flags, false /*hovering*/);
4591 }
4592
4593 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4594 return true;
4595 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 if (index >= 0) {
4597 MotionMemento& memento = mMotionMementos.editItemAt(index);
4598 memento.setPointers(entry);
4599 return true;
4600 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601#if DEBUG_OUTBOUND_EVENT_DETAILS
4602 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004603 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4604 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605#endif
4606 return false;
4607 }
4608
4609 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4610 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4611 if (index >= 0) {
4612 mMotionMementos.removeAt(index);
4613 return true;
4614 }
4615#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004616 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4617 "displayId=%" PRId32,
4618 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004619#endif
4620 return false;
4621 }
4622
4623 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4624 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4625 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4626 if (index >= 0) {
4627 mMotionMementos.removeAt(index);
4628 }
4629 addMotionMemento(entry, flags, true /*hovering*/);
4630 return true;
4631 }
4632
4633 default:
4634 return true;
4635 }
4636}
4637
4638ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4639 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4640 const KeyMemento& memento = mKeyMementos.itemAt(i);
4641 if (memento.deviceId == entry->deviceId
4642 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004643 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644 && memento.keyCode == entry->keyCode
4645 && memento.scanCode == entry->scanCode) {
4646 return i;
4647 }
4648 }
4649 return -1;
4650}
4651
4652ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4653 bool hovering) const {
4654 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4655 const MotionMemento& memento = mMotionMementos.itemAt(i);
4656 if (memento.deviceId == entry->deviceId
4657 && memento.source == entry->source
4658 && memento.displayId == entry->displayId
4659 && memento.hovering == hovering) {
4660 return i;
4661 }
4662 }
4663 return -1;
4664}
4665
4666void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4667 mKeyMementos.push();
4668 KeyMemento& memento = mKeyMementos.editTop();
4669 memento.deviceId = entry->deviceId;
4670 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004671 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004672 memento.keyCode = entry->keyCode;
4673 memento.scanCode = entry->scanCode;
4674 memento.metaState = entry->metaState;
4675 memento.flags = flags;
4676 memento.downTime = entry->downTime;
4677 memento.policyFlags = entry->policyFlags;
4678}
4679
4680void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4681 int32_t flags, bool hovering) {
4682 mMotionMementos.push();
4683 MotionMemento& memento = mMotionMementos.editTop();
4684 memento.deviceId = entry->deviceId;
4685 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004686 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687 memento.flags = flags;
4688 memento.xPrecision = entry->xPrecision;
4689 memento.yPrecision = entry->yPrecision;
4690 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691 memento.setPointers(entry);
4692 memento.hovering = hovering;
4693 memento.policyFlags = entry->policyFlags;
4694}
4695
4696void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4697 pointerCount = entry->pointerCount;
4698 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4699 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4700 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4701 }
4702}
4703
4704void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4705 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4706 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4707 const KeyMemento& memento = mKeyMementos.itemAt(i);
4708 if (shouldCancelKey(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004709 outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004710 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4712 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4713 }
4714 }
4715
4716 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4717 const MotionMemento& memento = mMotionMementos.itemAt(i);
4718 if (shouldCancelMotion(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004719 outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004720 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721 memento.hovering
4722 ? AMOTION_EVENT_ACTION_HOVER_EXIT
4723 : AMOTION_EVENT_ACTION_CANCEL,
Michael Wright7b159c92015-05-14 14:48:03 +01004724 memento.flags, 0, 0, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004726 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
4727 0, 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728 }
4729 }
4730}
4731
4732void InputDispatcher::InputState::clear() {
4733 mKeyMementos.clear();
4734 mMotionMementos.clear();
4735 mFallbackKeys.clear();
4736}
4737
4738void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4739 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4740 const MotionMemento& memento = mMotionMementos.itemAt(i);
4741 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4742 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4743 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4744 if (memento.deviceId == otherMemento.deviceId
4745 && memento.source == otherMemento.source
4746 && memento.displayId == otherMemento.displayId) {
4747 other.mMotionMementos.removeAt(j);
4748 } else {
4749 j += 1;
4750 }
4751 }
4752 other.mMotionMementos.push(memento);
4753 }
4754 }
4755}
4756
4757int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4758 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4759 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4760}
4761
4762void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4763 int32_t fallbackKeyCode) {
4764 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4765 if (index >= 0) {
4766 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4767 } else {
4768 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4769 }
4770}
4771
4772void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4773 mFallbackKeys.removeItem(originalKeyCode);
4774}
4775
4776bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4777 const CancelationOptions& options) {
4778 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4779 return false;
4780 }
4781
4782 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4783 return false;
4784 }
4785
4786 switch (options.mode) {
4787 case CancelationOptions::CANCEL_ALL_EVENTS:
4788 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4789 return true;
4790 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4791 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004792 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4793 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 default:
4795 return false;
4796 }
4797}
4798
4799bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4800 const CancelationOptions& options) {
4801 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4802 return false;
4803 }
4804
4805 switch (options.mode) {
4806 case CancelationOptions::CANCEL_ALL_EVENTS:
4807 return true;
4808 case CancelationOptions::CANCEL_POINTER_EVENTS:
4809 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4810 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4811 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004812 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4813 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 default:
4815 return false;
4816 }
4817}
4818
4819
4820// --- InputDispatcher::Connection ---
4821
Robert Carr803535b2018-08-02 16:38:15 -07004822InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4823 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 monitor(monitor),
4825 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4826}
4827
4828InputDispatcher::Connection::~Connection() {
4829}
4830
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004831const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004832 if (inputChannel != nullptr) {
4833 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 }
4835 if (monitor) {
4836 return "monitor";
4837 }
4838 return "?";
4839}
4840
4841const char* InputDispatcher::Connection::getStatusLabel() const {
4842 switch (status) {
4843 case STATUS_NORMAL:
4844 return "NORMAL";
4845
4846 case STATUS_BROKEN:
4847 return "BROKEN";
4848
4849 case STATUS_ZOMBIE:
4850 return "ZOMBIE";
4851
4852 default:
4853 return "UNKNOWN";
4854 }
4855}
4856
4857InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004858 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 if (entry->seq == seq) {
4860 return entry;
4861 }
4862 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004863 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864}
4865
4866
4867// --- InputDispatcher::CommandEntry ---
4868
4869InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004870 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 seq(0), handled(false) {
4872}
4873
4874InputDispatcher::CommandEntry::~CommandEntry() {
4875}
4876
4877
4878// --- InputDispatcher::TouchState ---
4879
4880InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004881 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882}
4883
4884InputDispatcher::TouchState::~TouchState() {
4885}
4886
4887void InputDispatcher::TouchState::reset() {
4888 down = false;
4889 split = false;
4890 deviceId = -1;
4891 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004892 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893 windows.clear();
4894}
4895
4896void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4897 down = other.down;
4898 split = other.split;
4899 deviceId = other.deviceId;
4900 source = other.source;
4901 displayId = other.displayId;
4902 windows = other.windows;
4903}
4904
4905void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4906 int32_t targetFlags, BitSet32 pointerIds) {
4907 if (targetFlags & InputTarget::FLAG_SPLIT) {
4908 split = true;
4909 }
4910
4911 for (size_t i = 0; i < windows.size(); i++) {
4912 TouchedWindow& touchedWindow = windows.editItemAt(i);
4913 if (touchedWindow.windowHandle == windowHandle) {
4914 touchedWindow.targetFlags |= targetFlags;
4915 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4916 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4917 }
4918 touchedWindow.pointerIds.value |= pointerIds.value;
4919 return;
4920 }
4921 }
4922
4923 windows.push();
4924
4925 TouchedWindow& touchedWindow = windows.editTop();
4926 touchedWindow.windowHandle = windowHandle;
4927 touchedWindow.targetFlags = targetFlags;
4928 touchedWindow.pointerIds = pointerIds;
4929}
4930
4931void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4932 for (size_t i = 0; i < windows.size(); i++) {
4933 if (windows.itemAt(i).windowHandle == windowHandle) {
4934 windows.removeAt(i);
4935 return;
4936 }
4937 }
4938}
4939
Robert Carr803535b2018-08-02 16:38:15 -07004940void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4941 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004942 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004943 windows.removeAt(i);
4944 return;
4945 }
4946 }
4947}
4948
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4950 for (size_t i = 0 ; i < windows.size(); ) {
4951 TouchedWindow& window = windows.editItemAt(i);
4952 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4953 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4954 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4955 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4956 i += 1;
4957 } else {
4958 windows.removeAt(i);
4959 }
4960 }
4961}
4962
4963sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
4964 for (size_t i = 0; i < windows.size(); i++) {
4965 const TouchedWindow& window = windows.itemAt(i);
4966 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4967 return window.windowHandle;
4968 }
4969 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004970 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971}
4972
4973bool InputDispatcher::TouchState::isSlippery() const {
4974 // Must have exactly one foreground window.
4975 bool haveSlipperyForegroundWindow = false;
4976 for (size_t i = 0; i < windows.size(); i++) {
4977 const TouchedWindow& window = windows.itemAt(i);
4978 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
4979 if (haveSlipperyForegroundWindow
4980 || !(window.windowHandle->getInfo()->layoutParamsFlags
4981 & InputWindowInfo::FLAG_SLIPPERY)) {
4982 return false;
4983 }
4984 haveSlipperyForegroundWindow = true;
4985 }
4986 }
4987 return haveSlipperyForegroundWindow;
4988}
4989
4990
4991// --- InputDispatcherThread ---
4992
4993InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
4994 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
4995}
4996
4997InputDispatcherThread::~InputDispatcherThread() {
4998}
4999
5000bool InputDispatcherThread::threadLoop() {
5001 mDispatcher->dispatchOnce();
5002 return true;
5003}
5004
5005} // namespace android