blob: 7ff8b20a7e283fcfa46b4ac02dcafaca846cb465 [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
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800218static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800219 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800220 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800221 return;
222 }
223
224 bool first = true;
225 Region::const_iterator cur = region.begin();
226 Region::const_iterator const tail = region.end();
227 while (cur != tail) {
228 if (first) {
229 first = false;
230 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800231 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800233 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 cur++;
235 }
236}
237
Tiger Huang721e26f2018-07-24 22:26:19 +0800238template<typename T, typename U>
239static T getValueByKey(std::unordered_map<U, T>& map, U key) {
240 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
241 return it != map.end() ? it->second : T{};
242}
243
Michael Wrightd02c5b62014-02-10 15:10:22 -0800244
245// --- InputDispatcher ---
246
247InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
248 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700249 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100250 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700251 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800253 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
255 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800256 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257
Yi Kong9b14ac62018-07-17 13:48:38 -0700258 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259
260 policy->getDispatcherConfiguration(&mConfig);
261}
262
263InputDispatcher::~InputDispatcher() {
264 { // acquire lock
265 AutoMutex _l(mLock);
266
267 resetKeyRepeatLocked();
268 releasePendingEventLocked();
269 drainInboundQueueLocked();
270 }
271
272 while (mConnectionsByFd.size() != 0) {
273 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
274 }
275}
276
277void InputDispatcher::dispatchOnce() {
278 nsecs_t nextWakeupTime = LONG_LONG_MAX;
279 { // acquire lock
280 AutoMutex _l(mLock);
281 mDispatcherIsAliveCondition.broadcast();
282
283 // Run a dispatch loop if there are no pending commands.
284 // The dispatch loop might enqueue commands to run afterwards.
285 if (!haveCommandsLocked()) {
286 dispatchOnceInnerLocked(&nextWakeupTime);
287 }
288
289 // Run all pending commands if there are any.
290 // If any commands were run then force the next poll to wake up immediately.
291 if (runCommandsLockedInterruptible()) {
292 nextWakeupTime = LONG_LONG_MIN;
293 }
294 } // release lock
295
296 // Wait for callback or timeout or wake. (make sure we round up, not down)
297 nsecs_t currentTime = now();
298 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
299 mLooper->pollOnce(timeoutMillis);
300}
301
302void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
303 nsecs_t currentTime = now();
304
Jeff Browndc5992e2014-04-11 01:27:26 -0700305 // Reset the key repeat timer whenever normal dispatch is suspended while the
306 // device is in a non-interactive state. This is to ensure that we abort a key
307 // repeat if the device is just coming out of sleep.
308 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800309 resetKeyRepeatLocked();
310 }
311
312 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
313 if (mDispatchFrozen) {
314#if DEBUG_FOCUS
315 ALOGD("Dispatch frozen. Waiting some more.");
316#endif
317 return;
318 }
319
320 // Optimize latency of app switches.
321 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
322 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
323 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
324 if (mAppSwitchDueTime < *nextWakeupTime) {
325 *nextWakeupTime = mAppSwitchDueTime;
326 }
327
328 // Ready to start a new event.
329 // If we don't already have a pending event, go grab one.
330 if (! mPendingEvent) {
331 if (mInboundQueue.isEmpty()) {
332 if (isAppSwitchDue) {
333 // The inbound queue is empty so the app switch key we were waiting
334 // for will never arrive. Stop waiting for it.
335 resetPendingAppSwitchLocked(false);
336 isAppSwitchDue = false;
337 }
338
339 // Synthesize a key repeat if appropriate.
340 if (mKeyRepeatState.lastKeyEntry) {
341 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
342 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
343 } else {
344 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
345 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
346 }
347 }
348 }
349
350 // Nothing to do if there is no pending event.
351 if (!mPendingEvent) {
352 return;
353 }
354 } else {
355 // Inbound queue has at least one entry.
356 mPendingEvent = mInboundQueue.dequeueAtHead();
357 traceInboundQueueLengthLocked();
358 }
359
360 // Poke user activity for this event.
361 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
362 pokeUserActivityLocked(mPendingEvent);
363 }
364
365 // Get ready to dispatch the event.
366 resetANRTimeoutsLocked();
367 }
368
369 // Now we have an event to dispatch.
370 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700371 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372 bool done = false;
373 DropReason dropReason = DROP_REASON_NOT_DROPPED;
374 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
375 dropReason = DROP_REASON_POLICY;
376 } else if (!mDispatchEnabled) {
377 dropReason = DROP_REASON_DISABLED;
378 }
379
380 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700381 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800382 }
383
384 switch (mPendingEvent->type) {
385 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
386 ConfigurationChangedEntry* typedEntry =
387 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
388 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
389 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
390 break;
391 }
392
393 case EventEntry::TYPE_DEVICE_RESET: {
394 DeviceResetEntry* typedEntry =
395 static_cast<DeviceResetEntry*>(mPendingEvent);
396 done = dispatchDeviceResetLocked(currentTime, typedEntry);
397 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
398 break;
399 }
400
401 case EventEntry::TYPE_KEY: {
402 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
403 if (isAppSwitchDue) {
404 if (isAppSwitchKeyEventLocked(typedEntry)) {
405 resetPendingAppSwitchLocked(true);
406 isAppSwitchDue = false;
407 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
408 dropReason = DROP_REASON_APP_SWITCH;
409 }
410 }
411 if (dropReason == DROP_REASON_NOT_DROPPED
412 && isStaleEventLocked(currentTime, typedEntry)) {
413 dropReason = DROP_REASON_STALE;
414 }
415 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
416 dropReason = DROP_REASON_BLOCKED;
417 }
418 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
419 break;
420 }
421
422 case EventEntry::TYPE_MOTION: {
423 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
424 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
425 dropReason = DROP_REASON_APP_SWITCH;
426 }
427 if (dropReason == DROP_REASON_NOT_DROPPED
428 && isStaleEventLocked(currentTime, typedEntry)) {
429 dropReason = DROP_REASON_STALE;
430 }
431 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
432 dropReason = DROP_REASON_BLOCKED;
433 }
434 done = dispatchMotionLocked(currentTime, typedEntry,
435 &dropReason, nextWakeupTime);
436 break;
437 }
438
439 default:
440 ALOG_ASSERT(false);
441 break;
442 }
443
444 if (done) {
445 if (dropReason != DROP_REASON_NOT_DROPPED) {
446 dropInboundEventLocked(mPendingEvent, dropReason);
447 }
Michael Wright3a981722015-06-10 15:26:13 +0100448 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449
450 releasePendingEventLocked();
451 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
452 }
453}
454
455bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
456 bool needWake = mInboundQueue.isEmpty();
457 mInboundQueue.enqueueAtTail(entry);
458 traceInboundQueueLengthLocked();
459
460 switch (entry->type) {
461 case EventEntry::TYPE_KEY: {
462 // Optimize app switch latency.
463 // If the application takes too long to catch up then we drop all events preceding
464 // the app switch key.
465 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
466 if (isAppSwitchKeyEventLocked(keyEntry)) {
467 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
468 mAppSwitchSawKeyDown = true;
469 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
470 if (mAppSwitchSawKeyDown) {
471#if DEBUG_APP_SWITCH
472 ALOGD("App switch is pending!");
473#endif
474 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
475 mAppSwitchSawKeyDown = false;
476 needWake = true;
477 }
478 }
479 }
480 break;
481 }
482
483 case EventEntry::TYPE_MOTION: {
484 // Optimize case where the current application is unresponsive and the user
485 // decides to touch a window in a different application.
486 // If the application takes too long to catch up then we drop all events preceding
487 // the touch into the other window.
488 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
489 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
490 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
491 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Robert Carr740167f2018-10-11 19:03:41 -0700492 && mInputTargetWaitApplicationToken != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 int32_t displayId = motionEntry->displayId;
494 int32_t x = int32_t(motionEntry->pointerCoords[0].
495 getAxisValue(AMOTION_EVENT_AXIS_X));
496 int32_t y = int32_t(motionEntry->pointerCoords[0].
497 getAxisValue(AMOTION_EVENT_AXIS_Y));
498 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700499 if (touchedWindowHandle != nullptr
Robert Carr740167f2018-10-11 19:03:41 -0700500 && touchedWindowHandle->getApplicationToken()
501 != mInputTargetWaitApplicationToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 // User touched a different application than the one we are waiting on.
503 // Flag the event, and start pruning the input queue.
504 mNextUnblockedEvent = motionEntry;
505 needWake = true;
506 }
507 }
508 break;
509 }
510 }
511
512 return needWake;
513}
514
515void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
516 entry->refCount += 1;
517 mRecentQueue.enqueueAtTail(entry);
518 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
519 mRecentQueue.dequeueAtHead()->release();
520 }
521}
522
523sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800524 int32_t x, int32_t y, bool addOutsideTargets, bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525 // Traverse windows from front to back to find touched window.
Arthur Hungb92218b2018-08-14 12:00:21 +0800526 const Vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
527 size_t numWindows = windowHandles.size();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 for (size_t i = 0; i < numWindows; i++) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800529 sp<InputWindowHandle> windowHandle = windowHandles.itemAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 const InputWindowInfo* windowInfo = windowHandle->getInfo();
531 if (windowInfo->displayId == displayId) {
532 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533
534 if (windowInfo->visible) {
535 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
536 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
537 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
538 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800539 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
540 if (portalToDisplayId != ADISPLAY_ID_NONE
541 && portalToDisplayId != displayId) {
542 if (addPortalWindows) {
543 // For the monitoring channels of the display.
544 mTempTouchState.addPortalWindow(windowHandle);
545 }
546 return findTouchedWindowAtLocked(
547 portalToDisplayId, x, y, addOutsideTargets, addPortalWindows);
548 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549 // Found window.
550 return windowHandle;
551 }
552 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800553
554 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
555 mTempTouchState.addOrUpdateWindow(
556 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 }
560 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700561 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562}
563
564void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
565 const char* reason;
566 switch (dropReason) {
567 case DROP_REASON_POLICY:
568#if DEBUG_INBOUND_EVENT_DETAILS
569 ALOGD("Dropped event because policy consumed it.");
570#endif
571 reason = "inbound event was dropped because the policy consumed it";
572 break;
573 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100574 if (mLastDropReason != DROP_REASON_DISABLED) {
575 ALOGI("Dropped event because input dispatch is disabled.");
576 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577 reason = "inbound event was dropped because input dispatch is disabled";
578 break;
579 case DROP_REASON_APP_SWITCH:
580 ALOGI("Dropped event because of pending overdue app switch.");
581 reason = "inbound event was dropped because of pending overdue app switch";
582 break;
583 case DROP_REASON_BLOCKED:
584 ALOGI("Dropped event because the current application is not responding and the user "
585 "has started interacting with a different application.");
586 reason = "inbound event was dropped because the current application is not responding "
587 "and the user has started interacting with a different application";
588 break;
589 case DROP_REASON_STALE:
590 ALOGI("Dropped event because it is stale.");
591 reason = "inbound event was dropped because it is stale";
592 break;
593 default:
594 ALOG_ASSERT(false);
595 return;
596 }
597
598 switch (entry->type) {
599 case EventEntry::TYPE_KEY: {
600 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
601 synthesizeCancelationEventsForAllConnectionsLocked(options);
602 break;
603 }
604 case EventEntry::TYPE_MOTION: {
605 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
606 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
607 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
608 synthesizeCancelationEventsForAllConnectionsLocked(options);
609 } else {
610 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
611 synthesizeCancelationEventsForAllConnectionsLocked(options);
612 }
613 break;
614 }
615 }
616}
617
618bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
619 return keyCode == AKEYCODE_HOME
620 || keyCode == AKEYCODE_ENDCALL
621 || keyCode == AKEYCODE_APP_SWITCH;
622}
623
624bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
625 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
626 && isAppSwitchKeyCode(keyEntry->keyCode)
627 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
628 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
629}
630
631bool InputDispatcher::isAppSwitchPendingLocked() {
632 return mAppSwitchDueTime != LONG_LONG_MAX;
633}
634
635void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
636 mAppSwitchDueTime = LONG_LONG_MAX;
637
638#if DEBUG_APP_SWITCH
639 if (handled) {
640 ALOGD("App switch has arrived.");
641 } else {
642 ALOGD("App switch was abandoned.");
643 }
644#endif
645}
646
647bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
648 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
649}
650
651bool InputDispatcher::haveCommandsLocked() const {
652 return !mCommandQueue.isEmpty();
653}
654
655bool InputDispatcher::runCommandsLockedInterruptible() {
656 if (mCommandQueue.isEmpty()) {
657 return false;
658 }
659
660 do {
661 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
662
663 Command command = commandEntry->command;
664 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
665
666 commandEntry->connection.clear();
667 delete commandEntry;
668 } while (! mCommandQueue.isEmpty());
669 return true;
670}
671
672InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
673 CommandEntry* commandEntry = new CommandEntry(command);
674 mCommandQueue.enqueueAtTail(commandEntry);
675 return commandEntry;
676}
677
678void InputDispatcher::drainInboundQueueLocked() {
679 while (! mInboundQueue.isEmpty()) {
680 EventEntry* entry = mInboundQueue.dequeueAtHead();
681 releaseInboundEventLocked(entry);
682 }
683 traceInboundQueueLengthLocked();
684}
685
686void InputDispatcher::releasePendingEventLocked() {
687 if (mPendingEvent) {
688 resetANRTimeoutsLocked();
689 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700690 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800691 }
692}
693
694void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
695 InjectionState* injectionState = entry->injectionState;
696 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
697#if DEBUG_DISPATCH_CYCLE
698 ALOGD("Injected inbound event was dropped.");
699#endif
700 setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
701 }
702 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700703 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 }
705 addRecentEventLocked(entry);
706 entry->release();
707}
708
709void InputDispatcher::resetKeyRepeatLocked() {
710 if (mKeyRepeatState.lastKeyEntry) {
711 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700712 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 }
714}
715
716InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
717 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
718
719 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700720 uint32_t policyFlags = entry->policyFlags &
721 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800722 if (entry->refCount == 1) {
723 entry->recycle();
724 entry->eventTime = currentTime;
725 entry->policyFlags = policyFlags;
726 entry->repeatCount += 1;
727 } else {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800728 KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100729 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 entry->action, entry->flags, entry->keyCode, entry->scanCode,
731 entry->metaState, entry->repeatCount + 1, entry->downTime);
732
733 mKeyRepeatState.lastKeyEntry = newEntry;
734 entry->release();
735
736 entry = newEntry;
737 }
738 entry->syntheticRepeat = true;
739
740 // Increment reference count since we keep a reference to the event in
741 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
742 entry->refCount += 1;
743
744 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
745 return entry;
746}
747
748bool InputDispatcher::dispatchConfigurationChangedLocked(
749 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
750#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700751 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800752#endif
753
754 // Reset key repeating in case a keyboard device was added or removed or something.
755 resetKeyRepeatLocked();
756
757 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
758 CommandEntry* commandEntry = postCommandLocked(
759 & InputDispatcher::doNotifyConfigurationChangedInterruptible);
760 commandEntry->eventTime = entry->eventTime;
761 return true;
762}
763
764bool InputDispatcher::dispatchDeviceResetLocked(
765 nsecs_t currentTime, DeviceResetEntry* entry) {
766#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700767 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
768 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800769#endif
770
771 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
772 "device was reset");
773 options.deviceId = entry->deviceId;
774 synthesizeCancelationEventsForAllConnectionsLocked(options);
775 return true;
776}
777
778bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
779 DropReason* dropReason, nsecs_t* nextWakeupTime) {
780 // Preprocessing.
781 if (! entry->dispatchInProgress) {
782 if (entry->repeatCount == 0
783 && entry->action == AKEY_EVENT_ACTION_DOWN
784 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
785 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
786 if (mKeyRepeatState.lastKeyEntry
787 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
788 // We have seen two identical key downs in a row which indicates that the device
789 // driver is automatically generating key repeats itself. We take note of the
790 // repeat here, but we disable our own next key repeat timer since it is clear that
791 // we will not need to synthesize key repeats ourselves.
792 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
793 resetKeyRepeatLocked();
794 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
795 } else {
796 // Not a repeat. Save key down state in case we do see a repeat later.
797 resetKeyRepeatLocked();
798 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
799 }
800 mKeyRepeatState.lastKeyEntry = entry;
801 entry->refCount += 1;
802 } else if (! entry->syntheticRepeat) {
803 resetKeyRepeatLocked();
804 }
805
806 if (entry->repeatCount == 1) {
807 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
808 } else {
809 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
810 }
811
812 entry->dispatchInProgress = true;
813
814 logOutboundKeyDetailsLocked("dispatchKey - ", entry);
815 }
816
817 // Handle case where the policy asked us to try again later last time.
818 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
819 if (currentTime < entry->interceptKeyWakeupTime) {
820 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
821 *nextWakeupTime = entry->interceptKeyWakeupTime;
822 }
823 return false; // wait until next wakeup
824 }
825 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
826 entry->interceptKeyWakeupTime = 0;
827 }
828
829 // Give the policy a chance to intercept the key.
830 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
831 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
832 CommandEntry* commandEntry = postCommandLocked(
833 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800834 sp<InputWindowHandle> focusedWindowHandle =
835 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
836 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700837 commandEntry->inputChannel =
838 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 }
840 commandEntry->keyEntry = entry;
841 entry->refCount += 1;
842 return false; // wait for the command to run
843 } else {
844 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
845 }
846 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
847 if (*dropReason == DROP_REASON_NOT_DROPPED) {
848 *dropReason = DROP_REASON_POLICY;
849 }
850 }
851
852 // Clean up if dropping the event.
853 if (*dropReason != DROP_REASON_NOT_DROPPED) {
854 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
855 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800856 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 return true;
858 }
859
860 // Identify targets.
861 Vector<InputTarget> inputTargets;
862 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
863 entry, inputTargets, nextWakeupTime);
864 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
865 return false;
866 }
867
868 setInjectionResultLocked(entry, injectionResult);
869 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
870 return true;
871 }
872
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800873 // Add monitor channels from event's or focused display.
874 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875
876 // Dispatch the key.
877 dispatchEventLocked(currentTime, entry, inputTargets);
878 return true;
879}
880
881void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
882#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100883 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
884 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800885 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100887 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800889 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890#endif
891}
892
893bool InputDispatcher::dispatchMotionLocked(
894 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
895 // Preprocessing.
896 if (! entry->dispatchInProgress) {
897 entry->dispatchInProgress = true;
898
899 logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
900 }
901
902 // Clean up if dropping the event.
903 if (*dropReason != DROP_REASON_NOT_DROPPED) {
904 setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
905 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
906 return true;
907 }
908
909 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
910
911 // Identify targets.
912 Vector<InputTarget> inputTargets;
913
914 bool conflictingPointerActions = false;
915 int32_t injectionResult;
916 if (isPointerEvent) {
917 // Pointer event. (eg. touchscreen)
918 injectionResult = findTouchedWindowTargetsLocked(currentTime,
919 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
920 } else {
921 // Non touch event. (eg. trackball)
922 injectionResult = findFocusedWindowTargetsLocked(currentTime,
923 entry, inputTargets, nextWakeupTime);
924 }
925 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
926 return false;
927 }
928
929 setInjectionResultLocked(entry, injectionResult);
930 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100931 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
932 CancelationOptions::Mode mode(isPointerEvent ?
933 CancelationOptions::CANCEL_POINTER_EVENTS :
934 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
935 CancelationOptions options(mode, "input event injection failed");
936 synthesizeCancelationEventsForMonitorsLocked(options);
937 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 return true;
939 }
940
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800941 // Add monitor channels from event's or focused display.
942 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800944 if (isPointerEvent) {
945 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
946 if (stateIndex >= 0) {
947 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
948 if (!state.portalWindows.isEmpty()) {
949 // The event has gone through these portal windows, so we add monitoring targets of
950 // the corresponding displays as well.
951 for (size_t i = 0; i < state.portalWindows.size(); i++) {
952 const InputWindowInfo* windowInfo = state.portalWindows.itemAt(i)->getInfo();
953 addMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
954 -windowInfo->frameLeft, -windowInfo->frameTop);
955 }
956 }
957 }
958 }
959
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 // Dispatch the motion.
961 if (conflictingPointerActions) {
962 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
963 "conflicting pointer actions");
964 synthesizeCancelationEventsForAllConnectionsLocked(options);
965 }
966 dispatchEventLocked(currentTime, entry, inputTargets);
967 return true;
968}
969
970
971void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
972#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800973 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
974 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100975 "action=0x%x, actionButton=0x%x, flags=0x%x, "
976 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800977 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800979 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100980 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 entry->metaState, entry->buttonState,
982 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800983 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800984
985 for (uint32_t i = 0; i < entry->pointerCount; i++) {
986 ALOGD(" Pointer %d: id=%d, toolType=%d, "
987 "x=%f, y=%f, pressure=%f, size=%f, "
988 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800989 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 i, entry->pointerProperties[i].id,
991 entry->pointerProperties[i].toolType,
992 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
993 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
994 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
995 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
996 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
997 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
998 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
999 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08001000 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 }
1002#endif
1003}
1004
1005void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
1006 EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
1007#if DEBUG_DISPATCH_CYCLE
1008 ALOGD("dispatchEventToCurrentInputTargets");
1009#endif
1010
1011 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1012
1013 pokeUserActivityLocked(eventEntry);
1014
1015 for (size_t i = 0; i < inputTargets.size(); i++) {
1016 const InputTarget& inputTarget = inputTargets.itemAt(i);
1017
1018 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
1019 if (connectionIndex >= 0) {
1020 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1021 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1022 } else {
1023#if DEBUG_FOCUS
1024 ALOGD("Dropping event delivery to target with channel '%s' because it "
1025 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001026 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027#endif
1028 }
1029 }
1030}
1031
1032int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1033 const EventEntry* entry,
1034 const sp<InputApplicationHandle>& applicationHandle,
1035 const sp<InputWindowHandle>& windowHandle,
1036 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001037 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001038 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1039#if DEBUG_FOCUS
1040 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1041#endif
1042 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1043 mInputTargetWaitStartTime = currentTime;
1044 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1045 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001046 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 }
1048 } else {
1049 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1050#if DEBUG_FOCUS
1051 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001052 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 reason);
1054#endif
1055 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001056 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001057 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001058 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 timeout = applicationHandle->getDispatchingTimeout(
1060 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1061 } else {
1062 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1063 }
1064
1065 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1066 mInputTargetWaitStartTime = currentTime;
1067 mInputTargetWaitTimeoutTime = currentTime + timeout;
1068 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001069 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070
Yi Kong9b14ac62018-07-17 13:48:38 -07001071 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001072 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
Robert Carr740167f2018-10-11 19:03:41 -07001074 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1075 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 }
1077 }
1078 }
1079
1080 if (mInputTargetWaitTimeoutExpired) {
1081 return INPUT_EVENT_INJECTION_TIMED_OUT;
1082 }
1083
1084 if (currentTime >= mInputTargetWaitTimeoutTime) {
1085 onANRLocked(currentTime, applicationHandle, windowHandle,
1086 entry->eventTime, mInputTargetWaitStartTime, reason);
1087
1088 // Force poll loop to wake up immediately on next iteration once we get the
1089 // ANR response back from the policy.
1090 *nextWakeupTime = LONG_LONG_MIN;
1091 return INPUT_EVENT_INJECTION_PENDING;
1092 } else {
1093 // Force poll loop to wake up when timeout is due.
1094 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1095 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1096 }
1097 return INPUT_EVENT_INJECTION_PENDING;
1098 }
1099}
1100
Robert Carr803535b2018-08-02 16:38:15 -07001101void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1102 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1103 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1104 state.removeWindowByToken(token);
1105 }
1106}
1107
Michael Wrightd02c5b62014-02-10 15:10:22 -08001108void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1109 const sp<InputChannel>& inputChannel) {
1110 if (newTimeout > 0) {
1111 // Extend the timeout.
1112 mInputTargetWaitTimeoutTime = now() + newTimeout;
1113 } else {
1114 // Give up.
1115 mInputTargetWaitTimeoutExpired = true;
1116
1117 // Input state will not be realistic. Mark it out of sync.
1118 if (inputChannel.get()) {
1119 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1120 if (connectionIndex >= 0) {
1121 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001122 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123
Robert Carr803535b2018-08-02 16:38:15 -07001124 if (token != nullptr) {
1125 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 }
1127
1128 if (connection->status == Connection::STATUS_NORMAL) {
1129 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1130 "application not responding");
1131 synthesizeCancelationEventsForConnectionLocked(connection, options);
1132 }
1133 }
1134 }
1135 }
1136}
1137
1138nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1139 nsecs_t currentTime) {
1140 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1141 return currentTime - mInputTargetWaitStartTime;
1142 }
1143 return 0;
1144}
1145
1146void InputDispatcher::resetANRTimeoutsLocked() {
1147#if DEBUG_FOCUS
1148 ALOGD("Resetting ANR timeouts.");
1149#endif
1150
1151 // Reset input target wait timeout.
1152 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001153 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001154}
1155
Tiger Huang721e26f2018-07-24 22:26:19 +08001156/**
1157 * Get the display id that the given event should go to. If this event specifies a valid display id,
1158 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1159 * Focused display is the display that the user most recently interacted with.
1160 */
1161int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1162 int32_t displayId;
1163 switch (entry->type) {
1164 case EventEntry::TYPE_KEY: {
1165 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1166 displayId = typedEntry->displayId;
1167 break;
1168 }
1169 case EventEntry::TYPE_MOTION: {
1170 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1171 displayId = typedEntry->displayId;
1172 break;
1173 }
1174 default: {
1175 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1176 return ADISPLAY_ID_NONE;
1177 }
1178 }
1179 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1180}
1181
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
1183 const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
1184 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001185 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186
Tiger Huang721e26f2018-07-24 22:26:19 +08001187 int32_t displayId = getTargetDisplayId(entry);
1188 sp<InputWindowHandle> focusedWindowHandle =
1189 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1190 sp<InputApplicationHandle> focusedApplicationHandle =
1191 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1192
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193 // If there is no currently focused window and no focused application
1194 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001195 if (focusedWindowHandle == nullptr) {
1196 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001198 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 "Waiting because no window has focus but there is a "
1200 "focused application that may eventually add a window "
1201 "when it finishes starting up.");
1202 goto Unresponsive;
1203 }
1204
Arthur Hung3b413f22018-10-26 18:05:34 +08001205 ALOGI("Dropping event because there is no focused window or focused application in display "
1206 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001207 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1208 goto Failed;
1209 }
1210
1211 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001212 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1214 goto Failed;
1215 }
1216
Jeff Brownffb49772014-10-10 19:01:34 -07001217 // Check whether the window is ready for more input.
1218 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001219 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001220 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001222 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 goto Unresponsive;
1224 }
1225
1226 // Success! Output targets.
1227 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001228 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1230 inputTargets);
1231
1232 // Done.
1233Failed:
1234Unresponsive:
1235 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
1236 updateDispatchStatisticsLocked(currentTime, entry,
1237 injectionResult, timeSpentWaitingForApplication);
1238#if DEBUG_FOCUS
1239 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1240 "timeSpentWaitingForApplication=%0.1fms",
1241 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1242#endif
1243 return injectionResult;
1244}
1245
1246int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
1247 const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
1248 bool* outConflictingPointerActions) {
1249 enum InjectionPermission {
1250 INJECTION_PERMISSION_UNKNOWN,
1251 INJECTION_PERMISSION_GRANTED,
1252 INJECTION_PERMISSION_DENIED
1253 };
1254
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 // For security reasons, we defer updating the touch state until we are sure that
1256 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 int32_t displayId = entry->displayId;
1258 int32_t action = entry->action;
1259 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1260
1261 // Update the touch state as needed based on the properties of the touch event.
1262 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1263 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1264 sp<InputWindowHandle> newHoverWindowHandle;
1265
Jeff Brownf086ddb2014-02-11 14:28:48 -08001266 // Copy current touch state into mTempTouchState.
1267 // This state is always reset at the end of this function, so if we don't find state
1268 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001269 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001270 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1271 if (oldStateIndex >= 0) {
1272 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1273 mTempTouchState.copyFrom(*oldState);
1274 }
1275
1276 bool isSplit = mTempTouchState.split;
1277 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1278 && (mTempTouchState.deviceId != entry->deviceId
1279 || mTempTouchState.source != entry->source
1280 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001281 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1282 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1283 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1284 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1285 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1286 || isHoverAction);
1287 bool wrongDevice = false;
1288 if (newGesture) {
1289 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001290 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001292 ALOGD("Dropping event because a pointer for a different device is already down "
1293 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001295 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1297 switchedDevice = false;
1298 wrongDevice = true;
1299 goto Failed;
1300 }
1301 mTempTouchState.reset();
1302 mTempTouchState.down = down;
1303 mTempTouchState.deviceId = entry->deviceId;
1304 mTempTouchState.source = entry->source;
1305 mTempTouchState.displayId = displayId;
1306 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001307 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1308#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001309 ALOGI("Dropping move event because a pointer for a different device is already active "
1310 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001311#endif
1312 // TODO: test multiple simultaneous input streams.
1313 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1314 switchedDevice = false;
1315 wrongDevice = true;
1316 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001317 }
1318
1319 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1320 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1321
1322 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1323 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1324 getAxisValue(AMOTION_EVENT_AXIS_X));
1325 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1326 getAxisValue(AMOTION_EVENT_AXIS_Y));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001327 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(
1328 displayId, x, y, maskedAction == AMOTION_EVENT_ACTION_DOWN, true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329
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,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001690 int32_t displayId, float xOffset, float yOffset) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001691 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;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001703 target.xOffset = xOffset;
1704 target.yOffset = yOffset;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001705 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,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002156 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification,
Michael Wright7b159c92015-05-14 14:48:03 +01002157 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;
chaviwfbe5d9c2018-12-26 12:23:37 -08002387 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(
2388 connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002389 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2391 target.xOffset = -windowInfo->frameLeft;
2392 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002393 target.globalScaleFactor = windowInfo->globalScaleFactor;
2394 target.windowXScale = windowInfo->windowXScale;
2395 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 } else {
2397 target.xOffset = 0;
2398 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002399 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400 }
2401 target.inputChannel = connection->inputChannel;
2402 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2403
2404 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
2405 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2406
2407 cancelationEventEntry->release();
2408 }
2409
2410 startDispatchCycleLocked(currentTime, connection);
2411 }
2412}
2413
2414InputDispatcher::MotionEntry*
2415InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2416 ALOG_ASSERT(pointerIds.value != 0);
2417
2418 uint32_t splitPointerIndexMap[MAX_POINTERS];
2419 PointerProperties splitPointerProperties[MAX_POINTERS];
2420 PointerCoords splitPointerCoords[MAX_POINTERS];
2421
2422 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2423 uint32_t splitPointerCount = 0;
2424
2425 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2426 originalPointerIndex++) {
2427 const PointerProperties& pointerProperties =
2428 originalMotionEntry->pointerProperties[originalPointerIndex];
2429 uint32_t pointerId = uint32_t(pointerProperties.id);
2430 if (pointerIds.hasBit(pointerId)) {
2431 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2432 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2433 splitPointerCoords[splitPointerCount].copyFrom(
2434 originalMotionEntry->pointerCoords[originalPointerIndex]);
2435 splitPointerCount += 1;
2436 }
2437 }
2438
2439 if (splitPointerCount != pointerIds.count()) {
2440 // This is bad. We are missing some of the pointers that we expected to deliver.
2441 // Most likely this indicates that we received an ACTION_MOVE events that has
2442 // different pointer ids than we expected based on the previous ACTION_DOWN
2443 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2444 // in this way.
2445 ALOGW("Dropping split motion event because the pointer count is %d but "
2446 "we expected there to be %d pointers. This probably means we received "
2447 "a broken sequence of pointer ids from the input device.",
2448 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002449 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450 }
2451
2452 int32_t action = originalMotionEntry->action;
2453 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2454 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2455 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2456 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2457 const PointerProperties& pointerProperties =
2458 originalMotionEntry->pointerProperties[originalPointerIndex];
2459 uint32_t pointerId = uint32_t(pointerProperties.id);
2460 if (pointerIds.hasBit(pointerId)) {
2461 if (pointerIds.count() == 1) {
2462 // The first/last pointer went down/up.
2463 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2464 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2465 } else {
2466 // A secondary pointer went down/up.
2467 uint32_t splitPointerIndex = 0;
2468 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2469 splitPointerIndex += 1;
2470 }
2471 action = maskedAction | (splitPointerIndex
2472 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2473 }
2474 } else {
2475 // An unrelated pointer changed.
2476 action = AMOTION_EVENT_ACTION_MOVE;
2477 }
2478 }
2479
2480 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002481 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 originalMotionEntry->eventTime,
2483 originalMotionEntry->deviceId,
2484 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002485 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 originalMotionEntry->policyFlags,
2487 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002488 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 originalMotionEntry->flags,
2490 originalMotionEntry->metaState,
2491 originalMotionEntry->buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002492 originalMotionEntry->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 originalMotionEntry->edgeFlags,
2494 originalMotionEntry->xPrecision,
2495 originalMotionEntry->yPrecision,
2496 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002497 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498
2499 if (originalMotionEntry->injectionState) {
2500 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2501 splitMotionEntry->injectionState->refCount += 1;
2502 }
2503
2504 return splitMotionEntry;
2505}
2506
2507void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2508#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002509 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510#endif
2511
2512 bool needWake;
2513 { // acquire lock
2514 AutoMutex _l(mLock);
2515
Prabir Pradhan42611e02018-11-27 14:04:02 -08002516 ConfigurationChangedEntry* newEntry =
2517 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518 needWake = enqueueInboundEventLocked(newEntry);
2519 } // release lock
2520
2521 if (needWake) {
2522 mLooper->wake();
2523 }
2524}
2525
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002526/**
2527 * If one of the meta shortcuts is detected, process them here:
2528 * Meta + Backspace -> generate BACK
2529 * Meta + Enter -> generate HOME
2530 * This will potentially overwrite keyCode and metaState.
2531 */
2532void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2533 int32_t& keyCode, int32_t& metaState) {
2534 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2535 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2536 if (keyCode == AKEYCODE_DEL) {
2537 newKeyCode = AKEYCODE_BACK;
2538 } else if (keyCode == AKEYCODE_ENTER) {
2539 newKeyCode = AKEYCODE_HOME;
2540 }
2541 if (newKeyCode != AKEYCODE_UNKNOWN) {
2542 AutoMutex _l(mLock);
2543 struct KeyReplacement replacement = {keyCode, deviceId};
2544 mReplacedKeys.add(replacement, newKeyCode);
2545 keyCode = newKeyCode;
2546 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2547 }
2548 } else if (action == AKEY_EVENT_ACTION_UP) {
2549 // In order to maintain a consistent stream of up and down events, check to see if the key
2550 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2551 // even if the modifier was released between the down and the up events.
2552 AutoMutex _l(mLock);
2553 struct KeyReplacement replacement = {keyCode, deviceId};
2554 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2555 if (index >= 0) {
2556 keyCode = mReplacedKeys.valueAt(index);
2557 mReplacedKeys.removeItemsAt(index);
2558 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2559 }
2560 }
2561}
2562
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2564#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002565 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002566 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002567 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002568 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002570 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571#endif
2572 if (!validateKeyEvent(args->action)) {
2573 return;
2574 }
2575
2576 uint32_t policyFlags = args->policyFlags;
2577 int32_t flags = args->flags;
2578 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002579 // InputDispatcher tracks and generates key repeats on behalf of
2580 // whatever notifies it, so repeatCount should always be set to 0
2581 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2583 policyFlags |= POLICY_FLAG_VIRTUAL;
2584 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2585 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 if (policyFlags & POLICY_FLAG_FUNCTION) {
2587 metaState |= AMETA_FUNCTION_ON;
2588 }
2589
2590 policyFlags |= POLICY_FLAG_TRUSTED;
2591
Michael Wright78f24442014-08-06 15:55:28 -07002592 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002593 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002594
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002596 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002597 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 args->downTime, args->eventTime);
2599
Michael Wright2b3c3302018-03-02 17:19:13 +00002600 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002602 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2603 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2604 std::to_string(t.duration().count()).c_str());
2605 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 bool needWake;
2608 { // acquire lock
2609 mLock.lock();
2610
2611 if (shouldSendKeyToInputFilterLocked(args)) {
2612 mLock.unlock();
2613
2614 policyFlags |= POLICY_FLAG_FILTERED;
2615 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2616 return; // event was consumed by the filter
2617 }
2618
2619 mLock.lock();
2620 }
2621
Prabir Pradhan42611e02018-11-27 14:04:02 -08002622 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002623 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002624 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 metaState, repeatCount, args->downTime);
2626
2627 needWake = enqueueInboundEventLocked(newEntry);
2628 mLock.unlock();
2629 } // release lock
2630
2631 if (needWake) {
2632 mLooper->wake();
2633 }
2634}
2635
2636bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2637 return mInputFilterEnabled;
2638}
2639
2640void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2641#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002642 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2643 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002644 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002645 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2646 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002647 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002648 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 for (uint32_t i = 0; i < args->pointerCount; i++) {
2650 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2651 "x=%f, y=%f, pressure=%f, size=%f, "
2652 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2653 "orientation=%f",
2654 i, args->pointerProperties[i].id,
2655 args->pointerProperties[i].toolType,
2656 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2657 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2658 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2659 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2660 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2661 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2662 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2663 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2664 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2665 }
2666#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002667 if (!validateMotionEvent(args->action, args->actionButton,
2668 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 return;
2670 }
2671
2672 uint32_t policyFlags = args->policyFlags;
2673 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002674
2675 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002676 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002677 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2678 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2679 std::to_string(t.duration().count()).c_str());
2680 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681
2682 bool needWake;
2683 { // acquire lock
2684 mLock.lock();
2685
2686 if (shouldSendMotionToInputFilterLocked(args)) {
2687 mLock.unlock();
2688
2689 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002690 event.initialize(args->deviceId, args->source, args->displayId,
2691 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002692 args->flags, args->edgeFlags, args->metaState, args->buttonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002693 args->classification, 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 args->downTime, args->eventTime,
2695 args->pointerCount, args->pointerProperties, args->pointerCoords);
2696
2697 policyFlags |= POLICY_FLAG_FILTERED;
2698 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2699 return; // event was consumed by the filter
2700 }
2701
2702 mLock.lock();
2703 }
2704
2705 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002706 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002707 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002708 args->action, args->actionButton, args->flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002709 args->metaState, args->buttonState, args->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002711 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712
2713 needWake = enqueueInboundEventLocked(newEntry);
2714 mLock.unlock();
2715 } // release lock
2716
2717 if (needWake) {
2718 mLooper->wake();
2719 }
2720}
2721
2722bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002723 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724}
2725
2726void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2727#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002728 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2729 "switchMask=0x%08x",
2730 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002731#endif
2732
2733 uint32_t policyFlags = args->policyFlags;
2734 policyFlags |= POLICY_FLAG_TRUSTED;
2735 mPolicy->notifySwitch(args->eventTime,
2736 args->switchValues, args->switchMask, policyFlags);
2737}
2738
2739void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2740#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002741 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 args->eventTime, args->deviceId);
2743#endif
2744
2745 bool needWake;
2746 { // acquire lock
2747 AutoMutex _l(mLock);
2748
Prabir Pradhan42611e02018-11-27 14:04:02 -08002749 DeviceResetEntry* newEntry =
2750 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002751 needWake = enqueueInboundEventLocked(newEntry);
2752 } // release lock
2753
2754 if (needWake) {
2755 mLooper->wake();
2756 }
2757}
2758
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002759int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2761 uint32_t policyFlags) {
2762#if DEBUG_INBOUND_EVENT_DETAILS
2763 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002764 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2765 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766#endif
2767
2768 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2769
2770 policyFlags |= POLICY_FLAG_INJECTED;
2771 if (hasInjectionPermission(injectorPid, injectorUid)) {
2772 policyFlags |= POLICY_FLAG_TRUSTED;
2773 }
2774
2775 EventEntry* firstInjectedEntry;
2776 EventEntry* lastInjectedEntry;
2777 switch (event->getType()) {
2778 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002779 KeyEvent keyEvent;
2780 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2781 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 if (! validateKeyEvent(action)) {
2783 return INPUT_EVENT_INJECTION_FAILED;
2784 }
2785
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002786 int32_t flags = keyEvent.getFlags();
2787 int32_t keyCode = keyEvent.getKeyCode();
2788 int32_t metaState = keyEvent.getMetaState();
2789 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2790 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002791 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002792 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002793 keyEvent.getDownTime(), keyEvent.getEventTime());
2794
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2796 policyFlags |= POLICY_FLAG_VIRTUAL;
2797 }
2798
2799 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002800 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002801 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002802 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2803 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2804 std::to_string(t.duration().count()).c_str());
2805 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002806 }
2807
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002809 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002810 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002812 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2813 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814 lastInjectedEntry = firstInjectedEntry;
2815 break;
2816 }
2817
2818 case AINPUT_EVENT_TYPE_MOTION: {
2819 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 int32_t action = motionEvent->getAction();
2821 size_t pointerCount = motionEvent->getPointerCount();
2822 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002823 int32_t actionButton = motionEvent->getActionButton();
Charles Chen3611f1f2019-01-29 17:26:18 +08002824 int32_t displayId = motionEvent->getDisplayId();
Michael Wright7b159c92015-05-14 14:48:03 +01002825 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002826 return INPUT_EVENT_INJECTION_FAILED;
2827 }
2828
2829 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2830 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002831 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002832 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002833 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2834 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2835 std::to_string(t.duration().count()).c_str());
2836 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 }
2838
2839 mLock.lock();
2840 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2841 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002842 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002843 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2844 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002845 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002846 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002847 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002849 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002850 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2851 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 lastInjectedEntry = firstInjectedEntry;
2853 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2854 sampleEventTimes += 1;
2855 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002856 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2857 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002858 motionEvent->getDeviceId(), motionEvent->getSource(),
2859 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002860 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002862 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002864 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002865 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2866 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 lastInjectedEntry->next = nextInjectedEntry;
2868 lastInjectedEntry = nextInjectedEntry;
2869 }
2870 break;
2871 }
2872
2873 default:
2874 ALOGW("Cannot inject event of type %d", event->getType());
2875 return INPUT_EVENT_INJECTION_FAILED;
2876 }
2877
2878 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2879 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2880 injectionState->injectionIsAsync = true;
2881 }
2882
2883 injectionState->refCount += 1;
2884 lastInjectedEntry->injectionState = injectionState;
2885
2886 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002887 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888 EventEntry* nextEntry = entry->next;
2889 needWake |= enqueueInboundEventLocked(entry);
2890 entry = nextEntry;
2891 }
2892
2893 mLock.unlock();
2894
2895 if (needWake) {
2896 mLooper->wake();
2897 }
2898
2899 int32_t injectionResult;
2900 { // acquire lock
2901 AutoMutex _l(mLock);
2902
2903 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2904 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2905 } else {
2906 for (;;) {
2907 injectionResult = injectionState->injectionResult;
2908 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2909 break;
2910 }
2911
2912 nsecs_t remainingTimeout = endTime - now();
2913 if (remainingTimeout <= 0) {
2914#if DEBUG_INJECTION
2915 ALOGD("injectInputEvent - Timed out waiting for injection result "
2916 "to become available.");
2917#endif
2918 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2919 break;
2920 }
2921
2922 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2923 }
2924
2925 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2926 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2927 while (injectionState->pendingForegroundDispatches != 0) {
2928#if DEBUG_INJECTION
2929 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2930 injectionState->pendingForegroundDispatches);
2931#endif
2932 nsecs_t remainingTimeout = endTime - now();
2933 if (remainingTimeout <= 0) {
2934#if DEBUG_INJECTION
2935 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2936 "dispatches to finish.");
2937#endif
2938 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2939 break;
2940 }
2941
2942 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2943 }
2944 }
2945 }
2946
2947 injectionState->release();
2948 } // release lock
2949
2950#if DEBUG_INJECTION
2951 ALOGD("injectInputEvent - Finished with result %d. "
2952 "injectorPid=%d, injectorUid=%d",
2953 injectionResult, injectorPid, injectorUid);
2954#endif
2955
2956 return injectionResult;
2957}
2958
2959bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2960 return injectorUid == 0
2961 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2962}
2963
2964void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2965 InjectionState* injectionState = entry->injectionState;
2966 if (injectionState) {
2967#if DEBUG_INJECTION
2968 ALOGD("Setting input event injection result to %d. "
2969 "injectorPid=%d, injectorUid=%d",
2970 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2971#endif
2972
2973 if (injectionState->injectionIsAsync
2974 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2975 // Log the outcome since the injector did not wait for the injection result.
2976 switch (injectionResult) {
2977 case INPUT_EVENT_INJECTION_SUCCEEDED:
2978 ALOGV("Asynchronous input event injection succeeded.");
2979 break;
2980 case INPUT_EVENT_INJECTION_FAILED:
2981 ALOGW("Asynchronous input event injection failed.");
2982 break;
2983 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2984 ALOGW("Asynchronous input event injection permission denied.");
2985 break;
2986 case INPUT_EVENT_INJECTION_TIMED_OUT:
2987 ALOGW("Asynchronous input event injection timed out.");
2988 break;
2989 }
2990 }
2991
2992 injectionState->injectionResult = injectionResult;
2993 mInjectionResultAvailableCondition.broadcast();
2994 }
2995}
2996
2997void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2998 InjectionState* injectionState = entry->injectionState;
2999 if (injectionState) {
3000 injectionState->pendingForegroundDispatches += 1;
3001 }
3002}
3003
3004void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3005 InjectionState* injectionState = entry->injectionState;
3006 if (injectionState) {
3007 injectionState->pendingForegroundDispatches -= 1;
3008
3009 if (injectionState->pendingForegroundDispatches == 0) {
3010 mInjectionSyncFinishedCondition.broadcast();
3011 }
3012 }
3013}
3014
Arthur Hungb92218b2018-08-14 12:00:21 +08003015Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
3016 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
3017 mWindowHandlesByDisplay.find(displayId);
3018 if(it != mWindowHandlesByDisplay.end()) {
3019 return it->second;
3020 }
3021
3022 // Return an empty one if nothing found.
3023 return Vector<sp<InputWindowHandle>>();
3024}
3025
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003027 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003028 for (auto& it : mWindowHandlesByDisplay) {
3029 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3030 size_t numWindows = windowHandles.size();
3031 for (size_t i = 0; i < numWindows; i++) {
3032 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
chaviwfbe5d9c2018-12-26 12:23:37 -08003033 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003034 return windowHandle;
3035 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036 }
3037 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003038 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003039}
3040
3041bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003042 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003043 for (auto& it : mWindowHandlesByDisplay) {
3044 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3045 size_t numWindows = windowHandles.size();
3046 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003047 if (windowHandles.itemAt(i)->getToken()
3048 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003049 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003050 ALOGE("Found window %s in display %" PRId32
3051 ", but it should belong to display %" PRId32,
3052 windowHandle->getName().c_str(), it.first,
3053 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003054 }
3055 return true;
3056 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003057 }
3058 }
3059 return false;
3060}
3061
Robert Carr5c8a0262018-10-03 16:30:44 -07003062sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3063 size_t count = mInputChannelsByToken.count(token);
3064 if (count == 0) {
3065 return nullptr;
3066 }
3067 return mInputChannelsByToken.at(token);
3068}
3069
Arthur Hungb92218b2018-08-14 12:00:21 +08003070/**
3071 * Called from InputManagerService, update window handle list by displayId that can receive input.
3072 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3073 * If set an empty list, remove all handles from the specific display.
3074 * For focused handle, check if need to change and send a cancel event to previous one.
3075 * For removed handle, check if need to send a cancel event if already in touch.
3076 */
3077void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3078 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003080 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081#endif
3082 { // acquire lock
3083 AutoMutex _l(mLock);
3084
Arthur Hungb92218b2018-08-14 12:00:21 +08003085 // Copy old handles for release if they are no longer present.
3086 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003087
Tiger Huang721e26f2018-07-24 22:26:19 +08003088 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003090
3091 if (inputWindowHandles.isEmpty()) {
3092 // Remove all handles on a display if there are no windows left.
3093 mWindowHandlesByDisplay.erase(displayId);
3094 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003095 // Since we compare the pointer of input window handles across window updates, we need
3096 // to make sure the handle object for the same window stays unchanged across updates.
3097 const Vector<sp<InputWindowHandle>>& oldHandles = mWindowHandlesByDisplay[displayId];
3098 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3099 for (size_t i = 0; i < oldHandles.size(); i++) {
3100 const sp<InputWindowHandle>& handle = oldHandles.itemAt(i);
3101 oldHandlesByTokens[handle->getToken()] = handle;
3102 }
3103
3104 const size_t numWindows = inputWindowHandles.size();
3105 Vector<sp<InputWindowHandle>> newHandles;
Arthur Hungb92218b2018-08-14 12:00:21 +08003106 for (size_t i = 0; i < numWindows; i++) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003107 const sp<InputWindowHandle>& handle = inputWindowHandles.itemAt(i);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003108 if (!handle->updateInfo() || (getInputChannelLocked(handle->getToken()) == nullptr
3109 && handle->getInfo()->portalToDisplayId == ADISPLAY_ID_NONE)) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003110 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003111 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003112 continue;
3113 }
3114
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003115 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003116 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003117 handle->getName().c_str(), displayId,
3118 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003119 continue;
3120 }
3121
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003122 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3123 const sp<InputWindowHandle> oldHandle =
3124 oldHandlesByTokens.at(handle->getToken());
3125 oldHandle->updateFrom(handle);
3126 newHandles.push_back(oldHandle);
3127 } else {
3128 newHandles.push_back(handle);
3129 }
3130 }
3131
3132 for (size_t i = 0; i < newHandles.size(); i++) {
3133 const sp<InputWindowHandle>& windowHandle = newHandles.itemAt(i);
Arthur Hung7ab76b12019-01-09 19:17:20 +08003134 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3135 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3136 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003137 newFocusedWindowHandle = windowHandle;
3138 }
3139 if (windowHandle == mLastHoverWindowHandle) {
3140 foundHoveredWindow = true;
3141 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003142 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003143
3144 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003145 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 }
3147
3148 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003149 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 }
3151
Tiger Huang721e26f2018-07-24 22:26:19 +08003152 sp<InputWindowHandle> oldFocusedWindowHandle =
3153 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3154
3155 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3156 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003158 ALOGD("Focus left window: %s in display %" PRId32,
3159 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003161 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3162 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003163 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3165 "focus left window");
3166 synthesizeCancelationEventsForInputChannelLocked(
3167 focusedInputChannel, options);
3168 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003169 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003171 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003173 ALOGD("Focus entered window: %s in display %" PRId32,
3174 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003176 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 }
Robert Carrf759f162018-11-13 12:57:11 -08003178
3179 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003180 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003181 }
3182
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 }
3184
Arthur Hungb92218b2018-08-14 12:00:21 +08003185 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3186 if (stateIndex >= 0) {
3187 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003188 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003189 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003190 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003192 ALOGD("Touched window was removed: %s in display %" PRId32,
3193 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003195 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003196 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003197 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003198 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3199 "touched window was removed");
3200 synthesizeCancelationEventsForInputChannelLocked(
3201 touchedInputChannel, options);
3202 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003203 state.windows.removeAt(i);
3204 } else {
3205 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 }
3208 }
3209
3210 // Release information for windows that are no longer present.
3211 // This ensures that unused input channels are released promptly.
3212 // Otherwise, they might stick around until the window handle is destroyed
3213 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003214 size_t numWindows = oldWindowHandles.size();
3215 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003217 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003219 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003221 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 }
3223 }
3224 } // release lock
3225
3226 // Wake up poll loop since it may need to make new input dispatching choices.
3227 mLooper->wake();
3228}
3229
3230void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003231 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003233 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234#endif
3235 { // acquire lock
3236 AutoMutex _l(mLock);
3237
Tiger Huang721e26f2018-07-24 22:26:19 +08003238 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3239 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003240 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003241 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3242 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003244 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003246 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003248 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003250 oldFocusedApplicationHandle->releaseInfo();
3251 oldFocusedApplicationHandle.clear();
3252 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 }
3254
3255#if DEBUG_FOCUS
3256 //logDispatchStateLocked();
3257#endif
3258 } // release lock
3259
3260 // Wake up poll loop since it may need to make new input dispatching choices.
3261 mLooper->wake();
3262}
3263
Tiger Huang721e26f2018-07-24 22:26:19 +08003264/**
3265 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3266 * the display not specified.
3267 *
3268 * We track any unreleased events for each window. If a window loses the ability to receive the
3269 * released event, we will send a cancel event to it. So when the focused display is changed, we
3270 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3271 * display. The display-specified events won't be affected.
3272 */
3273void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3274#if DEBUG_FOCUS
3275 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3276#endif
3277 { // acquire lock
3278 AutoMutex _l(mLock);
3279
3280 if (mFocusedDisplayId != displayId) {
3281 sp<InputWindowHandle> oldFocusedWindowHandle =
3282 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3283 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003284 sp<InputChannel> inputChannel =
3285 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003286 if (inputChannel != nullptr) {
3287 CancelationOptions options(
3288 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3289 "The display which contains this window no longer has focus.");
3290 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3291 }
3292 }
3293 mFocusedDisplayId = displayId;
3294
3295 // Sanity check
3296 sp<InputWindowHandle> newFocusedWindowHandle =
3297 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003298 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003299
Tiger Huang721e26f2018-07-24 22:26:19 +08003300 if (newFocusedWindowHandle == nullptr) {
3301 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3302 if (!mFocusedWindowHandlesByDisplay.empty()) {
3303 ALOGE("But another display has a focused window:");
3304 for (auto& it : mFocusedWindowHandlesByDisplay) {
3305 const int32_t displayId = it.first;
3306 const sp<InputWindowHandle>& windowHandle = it.second;
3307 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3308 displayId, windowHandle->getName().c_str());
3309 }
3310 }
3311 }
3312 }
3313
3314#if DEBUG_FOCUS
3315 logDispatchStateLocked();
3316#endif
3317 } // release lock
3318
3319 // Wake up poll loop since it may need to make new input dispatching choices.
3320 mLooper->wake();
3321}
3322
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3324#if DEBUG_FOCUS
3325 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3326#endif
3327
3328 bool changed;
3329 { // acquire lock
3330 AutoMutex _l(mLock);
3331
3332 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3333 if (mDispatchFrozen && !frozen) {
3334 resetANRTimeoutsLocked();
3335 }
3336
3337 if (mDispatchEnabled && !enabled) {
3338 resetAndDropEverythingLocked("dispatcher is being disabled");
3339 }
3340
3341 mDispatchEnabled = enabled;
3342 mDispatchFrozen = frozen;
3343 changed = true;
3344 } else {
3345 changed = false;
3346 }
3347
3348#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003349 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350#endif
3351 } // release lock
3352
3353 if (changed) {
3354 // Wake up poll loop since it may need to make new input dispatching choices.
3355 mLooper->wake();
3356 }
3357}
3358
3359void InputDispatcher::setInputFilterEnabled(bool enabled) {
3360#if DEBUG_FOCUS
3361 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3362#endif
3363
3364 { // acquire lock
3365 AutoMutex _l(mLock);
3366
3367 if (mInputFilterEnabled == enabled) {
3368 return;
3369 }
3370
3371 mInputFilterEnabled = enabled;
3372 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3373 } // release lock
3374
3375 // Wake up poll loop since there might be work to do to drop everything.
3376 mLooper->wake();
3377}
3378
chaviwfbe5d9c2018-12-26 12:23:37 -08003379bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3380 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003381#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003382 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003384 return true;
3385 }
3386
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387 { // acquire lock
3388 AutoMutex _l(mLock);
3389
chaviwfbe5d9c2018-12-26 12:23:37 -08003390 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3391 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003392 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003393 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 return false;
3395 }
chaviw4f2dd402018-12-26 15:30:27 -08003396#if DEBUG_FOCUS
3397 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3398 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3399#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3401#if DEBUG_FOCUS
3402 ALOGD("Cannot transfer focus because windows are on different displays.");
3403#endif
3404 return false;
3405 }
3406
3407 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003408 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3409 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3410 for (size_t i = 0; i < state.windows.size(); i++) {
3411 const TouchedWindow& touchedWindow = state.windows[i];
3412 if (touchedWindow.windowHandle == fromWindowHandle) {
3413 int32_t oldTargetFlags = touchedWindow.targetFlags;
3414 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415
Jeff Brownf086ddb2014-02-11 14:28:48 -08003416 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417
Jeff Brownf086ddb2014-02-11 14:28:48 -08003418 int32_t newTargetFlags = oldTargetFlags
3419 & (InputTarget::FLAG_FOREGROUND
3420 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3421 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422
Jeff Brownf086ddb2014-02-11 14:28:48 -08003423 found = true;
3424 goto Found;
3425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 }
3427 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003428Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429
3430 if (! found) {
3431#if DEBUG_FOCUS
3432 ALOGD("Focus transfer failed because from window did not have focus.");
3433#endif
3434 return false;
3435 }
3436
chaviwfbe5d9c2018-12-26 12:23:37 -08003437
3438 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3439 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3441 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3442 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3443 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3444 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3445
3446 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3447 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3448 "transferring touch focus from this window to another window");
3449 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3450 }
3451
3452#if DEBUG_FOCUS
3453 logDispatchStateLocked();
3454#endif
3455 } // release lock
3456
3457 // Wake up poll loop since it may need to make new input dispatching choices.
3458 mLooper->wake();
3459 return true;
3460}
3461
3462void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3463#if DEBUG_FOCUS
3464 ALOGD("Resetting and dropping all events (%s).", reason);
3465#endif
3466
3467 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3468 synthesizeCancelationEventsForAllConnectionsLocked(options);
3469
3470 resetKeyRepeatLocked();
3471 releasePendingEventLocked();
3472 drainInboundQueueLocked();
3473 resetANRTimeoutsLocked();
3474
Jeff Brownf086ddb2014-02-11 14:28:48 -08003475 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003477 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003478}
3479
3480void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003481 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482 dumpDispatchStateLocked(dump);
3483
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003484 std::istringstream stream(dump);
3485 std::string line;
3486
3487 while (std::getline(stream, line, '\n')) {
3488 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489 }
3490}
3491
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003492void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3493 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3494 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003495 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496
Tiger Huang721e26f2018-07-24 22:26:19 +08003497 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3498 dump += StringPrintf(INDENT "FocusedApplications:\n");
3499 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3500 const int32_t displayId = it.first;
3501 const sp<InputApplicationHandle>& applicationHandle = it.second;
3502 dump += StringPrintf(
3503 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3504 displayId,
3505 applicationHandle->getName().c_str(),
3506 applicationHandle->getDispatchingTimeout(
3507 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3508 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003510 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003512
3513 if (!mFocusedWindowHandlesByDisplay.empty()) {
3514 dump += StringPrintf(INDENT "FocusedWindows:\n");
3515 for (auto& it : mFocusedWindowHandlesByDisplay) {
3516 const int32_t displayId = it.first;
3517 const sp<InputWindowHandle>& windowHandle = it.second;
3518 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3519 displayId, windowHandle->getName().c_str());
3520 }
3521 } else {
3522 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3523 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524
Jeff Brownf086ddb2014-02-11 14:28:48 -08003525 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003526 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003527 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3528 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003529 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003530 state.displayId, toString(state.down), toString(state.split),
3531 state.deviceId, state.source);
3532 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003533 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003534 for (size_t i = 0; i < state.windows.size(); i++) {
3535 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003536 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3537 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003538 touchedWindow.pointerIds.value,
3539 touchedWindow.targetFlags);
3540 }
3541 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003542 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003543 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003544 if (!state.portalWindows.isEmpty()) {
3545 dump += INDENT3 "Portal windows:\n";
3546 for (size_t i = 0; i < state.portalWindows.size(); i++) {
3547 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows.itemAt(i);
3548 dump += StringPrintf(INDENT4 "%zu: name='%s'\n",
3549 i, portalWindowHandle->getName().c_str());
3550 }
3551 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 }
3553 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003554 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003555 }
3556
Arthur Hungb92218b2018-08-14 12:00:21 +08003557 if (!mWindowHandlesByDisplay.empty()) {
3558 for (auto& it : mWindowHandlesByDisplay) {
3559 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003560 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003561 if (!windowHandles.isEmpty()) {
3562 dump += INDENT2 "Windows:\n";
3563 for (size_t i = 0; i < windowHandles.size(); i++) {
3564 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3565 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566
Arthur Hungb92218b2018-08-14 12:00:21 +08003567 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003568 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, "
Arthur Hungb92218b2018-08-14 12:00:21 +08003569 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003570 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003571 "touchableRegion=",
3572 i, windowInfo->name.c_str(), windowInfo->displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003573 windowInfo->portalToDisplayId,
Arthur Hungb92218b2018-08-14 12:00:21 +08003574 toString(windowInfo->paused),
3575 toString(windowInfo->hasFocus),
3576 toString(windowInfo->hasWallpaper),
3577 toString(windowInfo->visible),
3578 toString(windowInfo->canReceiveKeys),
3579 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3580 windowInfo->layer,
3581 windowInfo->frameLeft, windowInfo->frameTop,
3582 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003583 windowInfo->globalScaleFactor,
3584 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003585 dumpRegion(dump, windowInfo->touchableRegion);
3586 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3587 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3588 windowInfo->ownerPid, windowInfo->ownerUid,
3589 windowInfo->dispatchingTimeout / 1000000.0);
3590 }
3591 } else {
3592 dump += INDENT2 "Windows: <none>\n";
3593 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003594 }
3595 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003596 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 }
3598
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003599 if (!mMonitoringChannelsByDisplay.empty()) {
3600 for (auto& it : mMonitoringChannelsByDisplay) {
3601 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003602 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003603 const size_t numChannels = monitoringChannels.size();
3604 for (size_t i = 0; i < numChannels; i++) {
3605 const sp<InputChannel>& channel = monitoringChannels[i];
3606 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3607 }
3608 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003610 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 }
3612
3613 nsecs_t currentTime = now();
3614
3615 // Dump recently dispatched or dropped events from oldest to newest.
3616 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003617 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003619 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003621 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 (currentTime - entry->eventTime) * 0.000001f);
3623 }
3624 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003625 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003626 }
3627
3628 // Dump event currently being dispatched.
3629 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003630 dump += INDENT "PendingEvent:\n";
3631 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003633 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003634 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3635 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003636 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 }
3638
3639 // Dump inbound events from oldest to newest.
3640 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003641 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003643 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003645 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 (currentTime - entry->eventTime) * 0.000001f);
3647 }
3648 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003649 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650 }
3651
Michael Wright78f24442014-08-06 15:55:28 -07003652 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003653 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003654 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3655 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3656 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003657 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003658 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3659 }
3660 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003661 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003662 }
3663
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003665 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3667 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003668 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003670 i, connection->getInputChannelName().c_str(),
3671 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672 connection->getStatusLabel(), toString(connection->monitor),
3673 toString(connection->inputPublisherBlocked));
3674
3675 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003676 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 connection->outboundQueue.count());
3678 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3679 entry = entry->next) {
3680 dump.append(INDENT4);
3681 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003682 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 entry->targetFlags, entry->resolvedAction,
3684 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3685 }
3686 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003687 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 }
3689
3690 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003691 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692 connection->waitQueue.count());
3693 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3694 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003695 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003697 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 "age=%0.1fms, wait=%0.1fms\n",
3699 entry->targetFlags, entry->resolvedAction,
3700 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3701 (currentTime - entry->deliveryTime) * 0.000001f);
3702 }
3703 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003704 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 }
3706 }
3707 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003708 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 }
3710
3711 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003712 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003713 (mAppSwitchDueTime - now()) / 1000000.0);
3714 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003715 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 }
3717
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003718 dump += INDENT "Configuration:\n";
3719 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003721 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722 mConfig.keyRepeatTimeout * 0.000001f);
3723}
3724
Robert Carr803535b2018-08-02 16:38:15 -07003725status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003727 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3728 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729#endif
3730
3731 { // acquire lock
3732 AutoMutex _l(mLock);
3733
Robert Carr4e670e52018-08-15 13:26:12 -07003734 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3735 // treat inputChannel as monitor channel for displayId.
3736 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3737 if (monitor) {
3738 inputChannel->setToken(new BBinder());
3739 }
3740
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741 if (getConnectionIndexLocked(inputChannel) >= 0) {
3742 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003743 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 return BAD_VALUE;
3745 }
3746
Robert Carr803535b2018-08-02 16:38:15 -07003747 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748
3749 int fd = inputChannel->getFd();
3750 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003751 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003753 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003755 Vector<sp<InputChannel>>& monitoringChannels =
3756 mMonitoringChannelsByDisplay[displayId];
3757 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 }
3759
3760 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3761 } // release lock
3762
3763 // Wake the looper because some connections have changed.
3764 mLooper->wake();
3765 return OK;
3766}
3767
3768status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3769#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003770 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771#endif
3772
3773 { // acquire lock
3774 AutoMutex _l(mLock);
3775
3776 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3777 if (status) {
3778 return status;
3779 }
3780 } // release lock
3781
3782 // Wake the poll loop because removing the connection may have changed the current
3783 // synchronization state.
3784 mLooper->wake();
3785 return OK;
3786}
3787
3788status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3789 bool notify) {
3790 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3791 if (connectionIndex < 0) {
3792 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003793 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 return BAD_VALUE;
3795 }
3796
3797 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3798 mConnectionsByFd.removeItemsAt(connectionIndex);
3799
Robert Carr5c8a0262018-10-03 16:30:44 -07003800 mInputChannelsByToken.erase(inputChannel->getToken());
3801
Michael Wrightd02c5b62014-02-10 15:10:22 -08003802 if (connection->monitor) {
3803 removeMonitorChannelLocked(inputChannel);
3804 }
3805
3806 mLooper->removeFd(inputChannel->getFd());
3807
3808 nsecs_t currentTime = now();
3809 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3810
3811 connection->status = Connection::STATUS_ZOMBIE;
3812 return OK;
3813}
3814
3815void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003816 for (auto it = mMonitoringChannelsByDisplay.begin();
3817 it != mMonitoringChannelsByDisplay.end(); ) {
3818 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3819 const size_t numChannels = monitoringChannels.size();
3820 for (size_t i = 0; i < numChannels; i++) {
3821 if (monitoringChannels[i] == inputChannel) {
3822 monitoringChannels.removeAt(i);
3823 break;
3824 }
3825 }
3826 if (monitoringChannels.empty()) {
3827 it = mMonitoringChannelsByDisplay.erase(it);
3828 } else {
3829 ++it;
3830 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 }
3832}
3833
3834ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003835 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003836 return -1;
3837 }
3838
Robert Carr4e670e52018-08-15 13:26:12 -07003839 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3840 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3841 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3842 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003843 }
3844 }
Robert Carr4e670e52018-08-15 13:26:12 -07003845
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846 return -1;
3847}
3848
3849void InputDispatcher::onDispatchCycleFinishedLocked(
3850 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3851 CommandEntry* commandEntry = postCommandLocked(
3852 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3853 commandEntry->connection = connection;
3854 commandEntry->eventTime = currentTime;
3855 commandEntry->seq = seq;
3856 commandEntry->handled = handled;
3857}
3858
3859void InputDispatcher::onDispatchCycleBrokenLocked(
3860 nsecs_t currentTime, const sp<Connection>& connection) {
3861 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003862 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863
3864 CommandEntry* commandEntry = postCommandLocked(
3865 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3866 commandEntry->connection = connection;
3867}
3868
chaviw0c06c6e2019-01-09 13:27:07 -08003869void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
3870 const sp<InputWindowHandle>& newFocus) {
3871 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
3872 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08003873 CommandEntry* commandEntry = postCommandLocked(
3874 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08003875 commandEntry->oldToken = oldToken;
3876 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003877}
3878
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879void InputDispatcher::onANRLocked(
3880 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3881 const sp<InputWindowHandle>& windowHandle,
3882 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3883 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3884 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3885 ALOGI("Application is not responding: %s. "
3886 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003887 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003888 dispatchLatency, waitDuration, reason);
3889
3890 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003891 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892 struct tm tm;
3893 localtime_r(&t, &tm);
3894 char timestr[64];
3895 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3896 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003897 mLastANRState += INDENT "ANR:\n";
3898 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3899 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3900 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3901 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3902 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3903 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003904 dumpDispatchStateLocked(mLastANRState);
3905
3906 CommandEntry* commandEntry = postCommandLocked(
3907 & InputDispatcher::doNotifyANRLockedInterruptible);
3908 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003909 commandEntry->inputChannel = windowHandle != nullptr ?
3910 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003911 commandEntry->reason = reason;
3912}
3913
3914void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3915 CommandEntry* commandEntry) {
3916 mLock.unlock();
3917
3918 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3919
3920 mLock.lock();
3921}
3922
3923void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3924 CommandEntry* commandEntry) {
3925 sp<Connection> connection = commandEntry->connection;
3926
3927 if (connection->status != Connection::STATUS_ZOMBIE) {
3928 mLock.unlock();
3929
Robert Carr803535b2018-08-02 16:38:15 -07003930 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931
3932 mLock.lock();
3933 }
3934}
3935
Robert Carrf759f162018-11-13 12:57:11 -08003936void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3937 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08003938 sp<IBinder> oldToken = commandEntry->oldToken;
3939 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003940 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08003941 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08003942 mLock.lock();
3943}
3944
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945void InputDispatcher::doNotifyANRLockedInterruptible(
3946 CommandEntry* commandEntry) {
3947 mLock.unlock();
3948
3949 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003950 commandEntry->inputApplicationHandle,
3951 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 commandEntry->reason);
3953
3954 mLock.lock();
3955
3956 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003957 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958}
3959
3960void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3961 CommandEntry* commandEntry) {
3962 KeyEntry* entry = commandEntry->keyEntry;
3963
3964 KeyEvent event;
3965 initializeKeyEvent(&event, entry);
3966
3967 mLock.unlock();
3968
Michael Wright2b3c3302018-03-02 17:19:13 +00003969 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003970 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3971 commandEntry->inputChannel->getToken() : nullptr;
3972 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003974 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3975 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3976 std::to_string(t.duration().count()).c_str());
3977 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978
3979 mLock.lock();
3980
3981 if (delay < 0) {
3982 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3983 } else if (!delay) {
3984 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3985 } else {
3986 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3987 entry->interceptKeyWakeupTime = now() + delay;
3988 }
3989 entry->release();
3990}
3991
3992void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3993 CommandEntry* commandEntry) {
3994 sp<Connection> connection = commandEntry->connection;
3995 nsecs_t finishTime = commandEntry->eventTime;
3996 uint32_t seq = commandEntry->seq;
3997 bool handled = commandEntry->handled;
3998
3999 // Handle post-event policy actions.
4000 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4001 if (dispatchEntry) {
4002 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4003 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004004 std::string msg =
4005 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004006 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004008 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009 }
4010
4011 bool restartEvent;
4012 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4013 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4014 restartEvent = afterKeyEventLockedInterruptible(connection,
4015 dispatchEntry, keyEntry, handled);
4016 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4017 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4018 restartEvent = afterMotionEventLockedInterruptible(connection,
4019 dispatchEntry, motionEntry, handled);
4020 } else {
4021 restartEvent = false;
4022 }
4023
4024 // Dequeue the event and start the next cycle.
4025 // Note that because the lock might have been released, it is possible that the
4026 // contents of the wait queue to have been drained, so we need to double-check
4027 // a few things.
4028 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4029 connection->waitQueue.dequeue(dispatchEntry);
4030 traceWaitQueueLengthLocked(connection);
4031 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4032 connection->outboundQueue.enqueueAtHead(dispatchEntry);
4033 traceOutboundQueueLengthLocked(connection);
4034 } else {
4035 releaseDispatchEntryLocked(dispatchEntry);
4036 }
4037 }
4038
4039 // Start the next dispatch cycle for this connection.
4040 startDispatchCycleLocked(now(), connection);
4041 }
4042}
4043
4044bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4045 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004046 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004047 if (!handled) {
4048 // Report the key as unhandled, since the fallback was not handled.
4049 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4050 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004051 return false;
4052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004054 // Get the fallback key state.
4055 // Clear it out after dispatching the UP.
4056 int32_t originalKeyCode = keyEntry->keyCode;
4057 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4058 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4059 connection->inputState.removeFallbackKey(originalKeyCode);
4060 }
4061
4062 if (handled || !dispatchEntry->hasForegroundTarget()) {
4063 // If the application handles the original key for which we previously
4064 // generated a fallback or if the window is not a foreground window,
4065 // then cancel the associated fallback key, if any.
4066 if (fallbackKeyCode != -1) {
4067 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004069 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4071 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4072 keyEntry->policyFlags);
4073#endif
4074 KeyEvent event;
4075 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004076 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004077
4078 mLock.unlock();
4079
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004080 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4081 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082
4083 mLock.lock();
4084
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004085 // Cancel the fallback key.
4086 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004088 "application handled the original non-fallback key "
4089 "or is no longer a foreground target, "
4090 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 options.keyCode = fallbackKeyCode;
4092 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004093 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004094 connection->inputState.removeFallbackKey(originalKeyCode);
4095 }
4096 } else {
4097 // If the application did not handle a non-fallback key, first check
4098 // that we are in a good state to perform unhandled key event processing
4099 // Then ask the policy what to do with it.
4100 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4101 && keyEntry->repeatCount == 0;
4102 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004104 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4105 "since this is not an initial down. "
4106 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4107 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4108 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004109#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004110 return false;
4111 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004113 // Dispatch the unhandled key to the policy.
4114#if DEBUG_OUTBOUND_EVENT_DETAILS
4115 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4116 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4117 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4118 keyEntry->policyFlags);
4119#endif
4120 KeyEvent event;
4121 initializeKeyEvent(&event, keyEntry);
4122
4123 mLock.unlock();
4124
4125 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4126 &event, keyEntry->policyFlags, &event);
4127
4128 mLock.lock();
4129
4130 if (connection->status != Connection::STATUS_NORMAL) {
4131 connection->inputState.removeFallbackKey(originalKeyCode);
4132 return false;
4133 }
4134
4135 // Latch the fallback keycode for this key on an initial down.
4136 // The fallback keycode cannot change at any other point in the lifecycle.
4137 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004139 fallbackKeyCode = event.getKeyCode();
4140 } else {
4141 fallbackKeyCode = AKEYCODE_UNKNOWN;
4142 }
4143 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4144 }
4145
4146 ALOG_ASSERT(fallbackKeyCode != -1);
4147
4148 // Cancel the fallback key if the policy decides not to send it anymore.
4149 // We will continue to dispatch the key to the policy but we will no
4150 // longer dispatch a fallback key to the application.
4151 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4152 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4153#if DEBUG_OUTBOUND_EVENT_DETAILS
4154 if (fallback) {
4155 ALOGD("Unhandled key event: Policy requested to send key %d"
4156 "as a fallback for %d, but on the DOWN it had requested "
4157 "to send %d instead. Fallback canceled.",
4158 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4159 } else {
4160 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4161 "but on the DOWN it had requested to send %d. "
4162 "Fallback canceled.",
4163 originalKeyCode, fallbackKeyCode);
4164 }
4165#endif
4166
4167 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4168 "canceling fallback, policy no longer desires it");
4169 options.keyCode = fallbackKeyCode;
4170 synthesizeCancelationEventsForConnectionLocked(connection, options);
4171
4172 fallback = false;
4173 fallbackKeyCode = AKEYCODE_UNKNOWN;
4174 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4175 connection->inputState.setFallbackKey(originalKeyCode,
4176 fallbackKeyCode);
4177 }
4178 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179
4180#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004181 {
4182 std::string msg;
4183 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4184 connection->inputState.getFallbackKeys();
4185 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4186 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4187 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004189 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4190 fallbackKeys.size(), msg.c_str());
4191 }
4192#endif
4193
4194 if (fallback) {
4195 // Restart the dispatch cycle using the fallback key.
4196 keyEntry->eventTime = event.getEventTime();
4197 keyEntry->deviceId = event.getDeviceId();
4198 keyEntry->source = event.getSource();
4199 keyEntry->displayId = event.getDisplayId();
4200 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4201 keyEntry->keyCode = fallbackKeyCode;
4202 keyEntry->scanCode = event.getScanCode();
4203 keyEntry->metaState = event.getMetaState();
4204 keyEntry->repeatCount = event.getRepeatCount();
4205 keyEntry->downTime = event.getDownTime();
4206 keyEntry->syntheticRepeat = false;
4207
4208#if DEBUG_OUTBOUND_EVENT_DETAILS
4209 ALOGD("Unhandled key event: Dispatching fallback key. "
4210 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4211 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4212#endif
4213 return true; // restart the event
4214 } else {
4215#if DEBUG_OUTBOUND_EVENT_DETAILS
4216 ALOGD("Unhandled key event: No fallback key.");
4217#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004218
4219 // Report the key as unhandled, since there is no fallback key.
4220 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 }
4222 }
4223 return false;
4224}
4225
4226bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4227 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4228 return false;
4229}
4230
4231void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4232 mLock.unlock();
4233
4234 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4235
4236 mLock.lock();
4237}
4238
4239void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004240 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4242 entry->downTime, entry->eventTime);
4243}
4244
4245void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4246 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4247 // TODO Write some statistics about how long we spend waiting.
4248}
4249
4250void InputDispatcher::traceInboundQueueLengthLocked() {
4251 if (ATRACE_ENABLED()) {
4252 ATRACE_INT("iq", mInboundQueue.count());
4253 }
4254}
4255
4256void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4257 if (ATRACE_ENABLED()) {
4258 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004259 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 ATRACE_INT(counterName, connection->outboundQueue.count());
4261 }
4262}
4263
4264void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4265 if (ATRACE_ENABLED()) {
4266 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004267 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004268 ATRACE_INT(counterName, connection->waitQueue.count());
4269 }
4270}
4271
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004272void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 AutoMutex _l(mLock);
4274
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004275 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276 dumpDispatchStateLocked(dump);
4277
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004278 if (!mLastANRState.empty()) {
4279 dump += "\nInput Dispatcher State at time of last ANR:\n";
4280 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 }
4282}
4283
4284void InputDispatcher::monitor() {
4285 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4286 mLock.lock();
4287 mLooper->wake();
4288 mDispatcherIsAliveCondition.wait(mLock);
4289 mLock.unlock();
4290}
4291
4292
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293// --- InputDispatcher::InjectionState ---
4294
4295InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4296 refCount(1),
4297 injectorPid(injectorPid), injectorUid(injectorUid),
4298 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4299 pendingForegroundDispatches(0) {
4300}
4301
4302InputDispatcher::InjectionState::~InjectionState() {
4303}
4304
4305void InputDispatcher::InjectionState::release() {
4306 refCount -= 1;
4307 if (refCount == 0) {
4308 delete this;
4309 } else {
4310 ALOG_ASSERT(refCount > 0);
4311 }
4312}
4313
4314
4315// --- InputDispatcher::EventEntry ---
4316
Prabir Pradhan42611e02018-11-27 14:04:02 -08004317InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4318 nsecs_t eventTime, uint32_t policyFlags) :
4319 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4320 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004321}
4322
4323InputDispatcher::EventEntry::~EventEntry() {
4324 releaseInjectionState();
4325}
4326
4327void InputDispatcher::EventEntry::release() {
4328 refCount -= 1;
4329 if (refCount == 0) {
4330 delete this;
4331 } else {
4332 ALOG_ASSERT(refCount > 0);
4333 }
4334}
4335
4336void InputDispatcher::EventEntry::releaseInjectionState() {
4337 if (injectionState) {
4338 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004339 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 }
4341}
4342
4343
4344// --- InputDispatcher::ConfigurationChangedEntry ---
4345
Prabir Pradhan42611e02018-11-27 14:04:02 -08004346InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4347 uint32_t sequenceNum, nsecs_t eventTime) :
4348 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349}
4350
4351InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4352}
4353
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004354void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4355 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356}
4357
4358
4359// --- InputDispatcher::DeviceResetEntry ---
4360
Prabir Pradhan42611e02018-11-27 14:04:02 -08004361InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4362 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4363 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 deviceId(deviceId) {
4365}
4366
4367InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4368}
4369
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004370void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4371 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372 deviceId, policyFlags);
4373}
4374
4375
4376// --- InputDispatcher::KeyEntry ---
4377
Prabir Pradhan42611e02018-11-27 14:04:02 -08004378InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004379 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4381 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004382 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004383 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004384 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4385 repeatCount(repeatCount), downTime(downTime),
4386 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4387 interceptKeyWakeupTime(0) {
4388}
4389
4390InputDispatcher::KeyEntry::~KeyEntry() {
4391}
4392
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004393void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004394 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004395 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4396 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004397 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004398 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399}
4400
4401void InputDispatcher::KeyEntry::recycle() {
4402 releaseInjectionState();
4403
4404 dispatchInProgress = false;
4405 syntheticRepeat = false;
4406 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4407 interceptKeyWakeupTime = 0;
4408}
4409
4410
4411// --- InputDispatcher::MotionEntry ---
4412
Prabir Pradhan42611e02018-11-27 14:04:02 -08004413InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004414 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4415 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004416 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4417 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004418 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004419 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4420 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004421 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004423 deviceId(deviceId), source(source), displayId(displayId), action(action),
4424 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004425 classification(classification), edgeFlags(edgeFlags),
4426 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004427 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004428 for (uint32_t i = 0; i < pointerCount; i++) {
4429 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4430 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004431 if (xOffset || yOffset) {
4432 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4433 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004434 }
4435}
4436
4437InputDispatcher::MotionEntry::~MotionEntry() {
4438}
4439
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004440void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004441 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004442 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004443 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004444 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004445 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4446 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004447
Michael Wrightd02c5b62014-02-10 15:10:22 -08004448 for (uint32_t i = 0; i < pointerCount; i++) {
4449 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004450 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004452 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 pointerCoords[i].getX(), pointerCoords[i].getY());
4454 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004455 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004456}
4457
4458
4459// --- InputDispatcher::DispatchEntry ---
4460
4461volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4462
4463InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004464 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4465 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004466 seq(nextSeq()),
4467 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004468 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4469 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4471 eventEntry->refCount += 1;
4472}
4473
4474InputDispatcher::DispatchEntry::~DispatchEntry() {
4475 eventEntry->release();
4476}
4477
4478uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4479 // Sequence number 0 is reserved and will never be returned.
4480 uint32_t seq;
4481 do {
4482 seq = android_atomic_inc(&sNextSeqAtomic);
4483 } while (!seq);
4484 return seq;
4485}
4486
4487
4488// --- InputDispatcher::InputState ---
4489
4490InputDispatcher::InputState::InputState() {
4491}
4492
4493InputDispatcher::InputState::~InputState() {
4494}
4495
4496bool InputDispatcher::InputState::isNeutral() const {
4497 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4498}
4499
4500bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4501 int32_t displayId) const {
4502 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4503 const MotionMemento& memento = mMotionMementos.itemAt(i);
4504 if (memento.deviceId == deviceId
4505 && memento.source == source
4506 && memento.displayId == displayId
4507 && memento.hovering) {
4508 return true;
4509 }
4510 }
4511 return false;
4512}
4513
4514bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4515 int32_t action, int32_t flags) {
4516 switch (action) {
4517 case AKEY_EVENT_ACTION_UP: {
4518 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4519 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4520 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4521 mFallbackKeys.removeItemsAt(i);
4522 } else {
4523 i += 1;
4524 }
4525 }
4526 }
4527 ssize_t index = findKeyMemento(entry);
4528 if (index >= 0) {
4529 mKeyMementos.removeAt(index);
4530 return true;
4531 }
4532 /* FIXME: We can't just drop the key up event because that prevents creating
4533 * popup windows that are automatically shown when a key is held and then
4534 * dismissed when the key is released. The problem is that the popup will
4535 * not have received the original key down, so the key up will be considered
4536 * to be inconsistent with its observed state. We could perhaps handle this
4537 * by synthesizing a key down but that will cause other problems.
4538 *
4539 * So for now, allow inconsistent key up events to be dispatched.
4540 *
4541#if DEBUG_OUTBOUND_EVENT_DETAILS
4542 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4543 "keyCode=%d, scanCode=%d",
4544 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4545#endif
4546 return false;
4547 */
4548 return true;
4549 }
4550
4551 case AKEY_EVENT_ACTION_DOWN: {
4552 ssize_t index = findKeyMemento(entry);
4553 if (index >= 0) {
4554 mKeyMementos.removeAt(index);
4555 }
4556 addKeyMemento(entry, flags);
4557 return true;
4558 }
4559
4560 default:
4561 return true;
4562 }
4563}
4564
4565bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4566 int32_t action, int32_t flags) {
4567 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4568 switch (actionMasked) {
4569 case AMOTION_EVENT_ACTION_UP:
4570 case AMOTION_EVENT_ACTION_CANCEL: {
4571 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4572 if (index >= 0) {
4573 mMotionMementos.removeAt(index);
4574 return true;
4575 }
4576#if DEBUG_OUTBOUND_EVENT_DETAILS
4577 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004578 "displayId=%" PRId32 ", actionMasked=%d",
4579 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580#endif
4581 return false;
4582 }
4583
4584 case AMOTION_EVENT_ACTION_DOWN: {
4585 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4586 if (index >= 0) {
4587 mMotionMementos.removeAt(index);
4588 }
4589 addMotionMemento(entry, flags, false /*hovering*/);
4590 return true;
4591 }
4592
4593 case AMOTION_EVENT_ACTION_POINTER_UP:
4594 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4595 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004596 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4597 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4598 // generate cancellation events for these since they're based in relative rather than
4599 // absolute units.
4600 return true;
4601 }
4602
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004604
4605 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4606 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4607 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4608 // other value and we need to track the motion so we can send cancellation events for
4609 // anything generating fallback events (e.g. DPad keys for joystick movements).
4610 if (index >= 0) {
4611 if (entry->pointerCoords[0].isEmpty()) {
4612 mMotionMementos.removeAt(index);
4613 } else {
4614 MotionMemento& memento = mMotionMementos.editItemAt(index);
4615 memento.setPointers(entry);
4616 }
4617 } else if (!entry->pointerCoords[0].isEmpty()) {
4618 addMotionMemento(entry, flags, false /*hovering*/);
4619 }
4620
4621 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4622 return true;
4623 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 if (index >= 0) {
4625 MotionMemento& memento = mMotionMementos.editItemAt(index);
4626 memento.setPointers(entry);
4627 return true;
4628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629#if DEBUG_OUTBOUND_EVENT_DETAILS
4630 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004631 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4632 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633#endif
4634 return false;
4635 }
4636
4637 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4638 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4639 if (index >= 0) {
4640 mMotionMementos.removeAt(index);
4641 return true;
4642 }
4643#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004644 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4645 "displayId=%" PRId32,
4646 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647#endif
4648 return false;
4649 }
4650
4651 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4652 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4653 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4654 if (index >= 0) {
4655 mMotionMementos.removeAt(index);
4656 }
4657 addMotionMemento(entry, flags, true /*hovering*/);
4658 return true;
4659 }
4660
4661 default:
4662 return true;
4663 }
4664}
4665
4666ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4667 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4668 const KeyMemento& memento = mKeyMementos.itemAt(i);
4669 if (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 return i;
4675 }
4676 }
4677 return -1;
4678}
4679
4680ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4681 bool hovering) const {
4682 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4683 const MotionMemento& memento = mMotionMementos.itemAt(i);
4684 if (memento.deviceId == entry->deviceId
4685 && memento.source == entry->source
4686 && memento.displayId == entry->displayId
4687 && memento.hovering == hovering) {
4688 return i;
4689 }
4690 }
4691 return -1;
4692}
4693
4694void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4695 mKeyMementos.push();
4696 KeyMemento& memento = mKeyMementos.editTop();
4697 memento.deviceId = entry->deviceId;
4698 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004699 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700 memento.keyCode = entry->keyCode;
4701 memento.scanCode = entry->scanCode;
4702 memento.metaState = entry->metaState;
4703 memento.flags = flags;
4704 memento.downTime = entry->downTime;
4705 memento.policyFlags = entry->policyFlags;
4706}
4707
4708void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4709 int32_t flags, bool hovering) {
4710 mMotionMementos.push();
4711 MotionMemento& memento = mMotionMementos.editTop();
4712 memento.deviceId = entry->deviceId;
4713 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004714 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715 memento.flags = flags;
4716 memento.xPrecision = entry->xPrecision;
4717 memento.yPrecision = entry->yPrecision;
4718 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 memento.setPointers(entry);
4720 memento.hovering = hovering;
4721 memento.policyFlags = entry->policyFlags;
4722}
4723
4724void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4725 pointerCount = entry->pointerCount;
4726 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4727 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4728 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4729 }
4730}
4731
4732void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4733 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4734 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4735 const KeyMemento& memento = mKeyMementos.itemAt(i);
4736 if (shouldCancelKey(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004737 outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004738 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4740 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4741 }
4742 }
4743
4744 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4745 const MotionMemento& memento = mMotionMementos.itemAt(i);
4746 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004747 const int32_t action = memento.hovering ?
4748 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan42611e02018-11-27 14:04:02 -08004749 outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004750 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004751 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4752 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004754 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004755 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 }
4757 }
4758}
4759
4760void InputDispatcher::InputState::clear() {
4761 mKeyMementos.clear();
4762 mMotionMementos.clear();
4763 mFallbackKeys.clear();
4764}
4765
4766void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4767 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4768 const MotionMemento& memento = mMotionMementos.itemAt(i);
4769 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4770 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4771 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4772 if (memento.deviceId == otherMemento.deviceId
4773 && memento.source == otherMemento.source
4774 && memento.displayId == otherMemento.displayId) {
4775 other.mMotionMementos.removeAt(j);
4776 } else {
4777 j += 1;
4778 }
4779 }
4780 other.mMotionMementos.push(memento);
4781 }
4782 }
4783}
4784
4785int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4786 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4787 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4788}
4789
4790void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4791 int32_t fallbackKeyCode) {
4792 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4793 if (index >= 0) {
4794 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4795 } else {
4796 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4797 }
4798}
4799
4800void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4801 mFallbackKeys.removeItem(originalKeyCode);
4802}
4803
4804bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4805 const CancelationOptions& options) {
4806 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4807 return false;
4808 }
4809
4810 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4811 return false;
4812 }
4813
4814 switch (options.mode) {
4815 case CancelationOptions::CANCEL_ALL_EVENTS:
4816 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4817 return true;
4818 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4819 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004820 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4821 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 default:
4823 return false;
4824 }
4825}
4826
4827bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4828 const CancelationOptions& options) {
4829 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4830 return false;
4831 }
4832
4833 switch (options.mode) {
4834 case CancelationOptions::CANCEL_ALL_EVENTS:
4835 return true;
4836 case CancelationOptions::CANCEL_POINTER_EVENTS:
4837 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4838 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4839 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004840 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4841 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 default:
4843 return false;
4844 }
4845}
4846
4847
4848// --- InputDispatcher::Connection ---
4849
Robert Carr803535b2018-08-02 16:38:15 -07004850InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4851 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004852 monitor(monitor),
4853 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4854}
4855
4856InputDispatcher::Connection::~Connection() {
4857}
4858
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004859const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004860 if (inputChannel != nullptr) {
4861 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 }
4863 if (monitor) {
4864 return "monitor";
4865 }
4866 return "?";
4867}
4868
4869const char* InputDispatcher::Connection::getStatusLabel() const {
4870 switch (status) {
4871 case STATUS_NORMAL:
4872 return "NORMAL";
4873
4874 case STATUS_BROKEN:
4875 return "BROKEN";
4876
4877 case STATUS_ZOMBIE:
4878 return "ZOMBIE";
4879
4880 default:
4881 return "UNKNOWN";
4882 }
4883}
4884
4885InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004886 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004887 if (entry->seq == seq) {
4888 return entry;
4889 }
4890 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004891 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892}
4893
4894
4895// --- InputDispatcher::CommandEntry ---
4896
4897InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004898 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 seq(0), handled(false) {
4900}
4901
4902InputDispatcher::CommandEntry::~CommandEntry() {
4903}
4904
4905
4906// --- InputDispatcher::TouchState ---
4907
4908InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004909 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910}
4911
4912InputDispatcher::TouchState::~TouchState() {
4913}
4914
4915void InputDispatcher::TouchState::reset() {
4916 down = false;
4917 split = false;
4918 deviceId = -1;
4919 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004920 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004922 portalWindows.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923}
4924
4925void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4926 down = other.down;
4927 split = other.split;
4928 deviceId = other.deviceId;
4929 source = other.source;
4930 displayId = other.displayId;
4931 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004932 portalWindows = other.portalWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933}
4934
4935void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4936 int32_t targetFlags, BitSet32 pointerIds) {
4937 if (targetFlags & InputTarget::FLAG_SPLIT) {
4938 split = true;
4939 }
4940
4941 for (size_t i = 0; i < windows.size(); i++) {
4942 TouchedWindow& touchedWindow = windows.editItemAt(i);
4943 if (touchedWindow.windowHandle == windowHandle) {
4944 touchedWindow.targetFlags |= targetFlags;
4945 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4946 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4947 }
4948 touchedWindow.pointerIds.value |= pointerIds.value;
4949 return;
4950 }
4951 }
4952
4953 windows.push();
4954
4955 TouchedWindow& touchedWindow = windows.editTop();
4956 touchedWindow.windowHandle = windowHandle;
4957 touchedWindow.targetFlags = targetFlags;
4958 touchedWindow.pointerIds = pointerIds;
4959}
4960
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004961void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
4962 size_t numWindows = portalWindows.size();
4963 for (size_t i = 0; i < numWindows; i++) {
4964 sp<InputWindowHandle> portalWindowHandle = portalWindows.itemAt(i);
4965 if (portalWindowHandle == windowHandle) {
4966 return;
4967 }
4968 }
4969 portalWindows.push_back(windowHandle);
4970}
4971
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4973 for (size_t i = 0; i < windows.size(); i++) {
4974 if (windows.itemAt(i).windowHandle == windowHandle) {
4975 windows.removeAt(i);
4976 return;
4977 }
4978 }
4979}
4980
Robert Carr803535b2018-08-02 16:38:15 -07004981void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4982 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004983 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004984 windows.removeAt(i);
4985 return;
4986 }
4987 }
4988}
4989
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4991 for (size_t i = 0 ; i < windows.size(); ) {
4992 TouchedWindow& window = windows.editItemAt(i);
4993 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4994 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4995 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4996 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4997 i += 1;
4998 } else {
4999 windows.removeAt(i);
5000 }
5001 }
5002}
5003
5004sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
5005 for (size_t i = 0; i < windows.size(); i++) {
5006 const TouchedWindow& window = windows.itemAt(i);
5007 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5008 return window.windowHandle;
5009 }
5010 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005011 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005012}
5013
5014bool InputDispatcher::TouchState::isSlippery() const {
5015 // Must have exactly one foreground window.
5016 bool haveSlipperyForegroundWindow = false;
5017 for (size_t i = 0; i < windows.size(); i++) {
5018 const TouchedWindow& window = windows.itemAt(i);
5019 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5020 if (haveSlipperyForegroundWindow
5021 || !(window.windowHandle->getInfo()->layoutParamsFlags
5022 & InputWindowInfo::FLAG_SLIPPERY)) {
5023 return false;
5024 }
5025 haveSlipperyForegroundWindow = true;
5026 }
5027 }
5028 return haveSlipperyForegroundWindow;
5029}
5030
5031
5032// --- InputDispatcherThread ---
5033
5034InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5035 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5036}
5037
5038InputDispatcherThread::~InputDispatcherThread() {
5039}
5040
5041bool InputDispatcherThread::threadLoop() {
5042 mDispatcher->dispatchOnce();
5043 return true;
5044}
5045
5046} // namespace android