blob: 9702fb2742cf55427063e0e7677974b3545599da [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;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676 mPolicy->interceptMotionBeforeQueueing(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();
2824 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 return INPUT_EVENT_INJECTION_FAILED;
2826 }
2827
2828 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2829 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002830 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002832 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2833 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2834 std::to_string(t.duration().count()).c_str());
2835 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 }
2837
2838 mLock.lock();
2839 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2840 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002841 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002842 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2843 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002844 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002846 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002848 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002849 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2850 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 lastInjectedEntry = firstInjectedEntry;
2852 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2853 sampleEventTimes += 1;
2854 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002855 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2856 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002857 motionEvent->getDeviceId(), motionEvent->getSource(),
2858 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002859 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002861 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002863 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002864 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2865 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 lastInjectedEntry->next = nextInjectedEntry;
2867 lastInjectedEntry = nextInjectedEntry;
2868 }
2869 break;
2870 }
2871
2872 default:
2873 ALOGW("Cannot inject event of type %d", event->getType());
2874 return INPUT_EVENT_INJECTION_FAILED;
2875 }
2876
2877 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2878 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2879 injectionState->injectionIsAsync = true;
2880 }
2881
2882 injectionState->refCount += 1;
2883 lastInjectedEntry->injectionState = injectionState;
2884
2885 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002886 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887 EventEntry* nextEntry = entry->next;
2888 needWake |= enqueueInboundEventLocked(entry);
2889 entry = nextEntry;
2890 }
2891
2892 mLock.unlock();
2893
2894 if (needWake) {
2895 mLooper->wake();
2896 }
2897
2898 int32_t injectionResult;
2899 { // acquire lock
2900 AutoMutex _l(mLock);
2901
2902 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2903 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2904 } else {
2905 for (;;) {
2906 injectionResult = injectionState->injectionResult;
2907 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2908 break;
2909 }
2910
2911 nsecs_t remainingTimeout = endTime - now();
2912 if (remainingTimeout <= 0) {
2913#if DEBUG_INJECTION
2914 ALOGD("injectInputEvent - Timed out waiting for injection result "
2915 "to become available.");
2916#endif
2917 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2918 break;
2919 }
2920
2921 mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
2922 }
2923
2924 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2925 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2926 while (injectionState->pendingForegroundDispatches != 0) {
2927#if DEBUG_INJECTION
2928 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2929 injectionState->pendingForegroundDispatches);
2930#endif
2931 nsecs_t remainingTimeout = endTime - now();
2932 if (remainingTimeout <= 0) {
2933#if DEBUG_INJECTION
2934 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2935 "dispatches to finish.");
2936#endif
2937 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2938 break;
2939 }
2940
2941 mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
2942 }
2943 }
2944 }
2945
2946 injectionState->release();
2947 } // release lock
2948
2949#if DEBUG_INJECTION
2950 ALOGD("injectInputEvent - Finished with result %d. "
2951 "injectorPid=%d, injectorUid=%d",
2952 injectionResult, injectorPid, injectorUid);
2953#endif
2954
2955 return injectionResult;
2956}
2957
2958bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2959 return injectorUid == 0
2960 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2961}
2962
2963void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
2964 InjectionState* injectionState = entry->injectionState;
2965 if (injectionState) {
2966#if DEBUG_INJECTION
2967 ALOGD("Setting input event injection result to %d. "
2968 "injectorPid=%d, injectorUid=%d",
2969 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2970#endif
2971
2972 if (injectionState->injectionIsAsync
2973 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2974 // Log the outcome since the injector did not wait for the injection result.
2975 switch (injectionResult) {
2976 case INPUT_EVENT_INJECTION_SUCCEEDED:
2977 ALOGV("Asynchronous input event injection succeeded.");
2978 break;
2979 case INPUT_EVENT_INJECTION_FAILED:
2980 ALOGW("Asynchronous input event injection failed.");
2981 break;
2982 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2983 ALOGW("Asynchronous input event injection permission denied.");
2984 break;
2985 case INPUT_EVENT_INJECTION_TIMED_OUT:
2986 ALOGW("Asynchronous input event injection timed out.");
2987 break;
2988 }
2989 }
2990
2991 injectionState->injectionResult = injectionResult;
2992 mInjectionResultAvailableCondition.broadcast();
2993 }
2994}
2995
2996void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
2997 InjectionState* injectionState = entry->injectionState;
2998 if (injectionState) {
2999 injectionState->pendingForegroundDispatches += 1;
3000 }
3001}
3002
3003void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
3004 InjectionState* injectionState = entry->injectionState;
3005 if (injectionState) {
3006 injectionState->pendingForegroundDispatches -= 1;
3007
3008 if (injectionState->pendingForegroundDispatches == 0) {
3009 mInjectionSyncFinishedCondition.broadcast();
3010 }
3011 }
3012}
3013
Arthur Hungb92218b2018-08-14 12:00:21 +08003014Vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(int32_t displayId) const {
3015 std::unordered_map<int32_t, Vector<sp<InputWindowHandle>>>::const_iterator it =
3016 mWindowHandlesByDisplay.find(displayId);
3017 if(it != mWindowHandlesByDisplay.end()) {
3018 return it->second;
3019 }
3020
3021 // Return an empty one if nothing found.
3022 return Vector<sp<InputWindowHandle>>();
3023}
3024
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003026 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003027 for (auto& it : mWindowHandlesByDisplay) {
3028 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3029 size_t numWindows = windowHandles.size();
3030 for (size_t i = 0; i < numWindows; i++) {
3031 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
chaviwfbe5d9c2018-12-26 12:23:37 -08003032 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003033 return windowHandle;
3034 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003035 }
3036 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003037 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038}
3039
3040bool InputDispatcher::hasWindowHandleLocked(
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003041 const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003042 for (auto& it : mWindowHandlesByDisplay) {
3043 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
3044 size_t numWindows = windowHandles.size();
3045 for (size_t i = 0; i < numWindows; i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003046 if (windowHandles.itemAt(i)->getToken()
3047 == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003048 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003049 ALOGE("Found window %s in display %" PRId32
3050 ", but it should belong to display %" PRId32,
3051 windowHandle->getName().c_str(), it.first,
3052 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003053 }
3054 return true;
3055 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 }
3057 }
3058 return false;
3059}
3060
Robert Carr5c8a0262018-10-03 16:30:44 -07003061sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3062 size_t count = mInputChannelsByToken.count(token);
3063 if (count == 0) {
3064 return nullptr;
3065 }
3066 return mInputChannelsByToken.at(token);
3067}
3068
Arthur Hungb92218b2018-08-14 12:00:21 +08003069/**
3070 * Called from InputManagerService, update window handle list by displayId that can receive input.
3071 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3072 * If set an empty list, remove all handles from the specific display.
3073 * For focused handle, check if need to change and send a cancel event to previous one.
3074 * For removed handle, check if need to send a cancel event if already in touch.
3075 */
3076void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle>>& inputWindowHandles,
3077 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003079 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080#endif
3081 { // acquire lock
3082 AutoMutex _l(mLock);
3083
Arthur Hungb92218b2018-08-14 12:00:21 +08003084 // Copy old handles for release if they are no longer present.
3085 const Vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003086
Tiger Huang721e26f2018-07-24 22:26:19 +08003087 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003089
3090 if (inputWindowHandles.isEmpty()) {
3091 // Remove all handles on a display if there are no windows left.
3092 mWindowHandlesByDisplay.erase(displayId);
3093 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003094 // Since we compare the pointer of input window handles across window updates, we need
3095 // to make sure the handle object for the same window stays unchanged across updates.
3096 const Vector<sp<InputWindowHandle>>& oldHandles = mWindowHandlesByDisplay[displayId];
3097 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
3098 for (size_t i = 0; i < oldHandles.size(); i++) {
3099 const sp<InputWindowHandle>& handle = oldHandles.itemAt(i);
3100 oldHandlesByTokens[handle->getToken()] = handle;
3101 }
3102
3103 const size_t numWindows = inputWindowHandles.size();
3104 Vector<sp<InputWindowHandle>> newHandles;
Arthur Hungb92218b2018-08-14 12:00:21 +08003105 for (size_t i = 0; i < numWindows; i++) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003106 const sp<InputWindowHandle>& handle = inputWindowHandles.itemAt(i);
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003107 if (!handle->updateInfo() || (getInputChannelLocked(handle->getToken()) == nullptr
3108 && handle->getInfo()->portalToDisplayId == ADISPLAY_ID_NONE)) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003109 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003110 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003111 continue;
3112 }
3113
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003114 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003115 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003116 handle->getName().c_str(), displayId,
3117 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003118 continue;
3119 }
3120
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003121 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3122 const sp<InputWindowHandle> oldHandle =
3123 oldHandlesByTokens.at(handle->getToken());
3124 oldHandle->updateFrom(handle);
3125 newHandles.push_back(oldHandle);
3126 } else {
3127 newHandles.push_back(handle);
3128 }
3129 }
3130
3131 for (size_t i = 0; i < newHandles.size(); i++) {
3132 const sp<InputWindowHandle>& windowHandle = newHandles.itemAt(i);
Arthur Hung7ab76b12019-01-09 19:17:20 +08003133 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3134 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3135 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003136 newFocusedWindowHandle = windowHandle;
3137 }
3138 if (windowHandle == mLastHoverWindowHandle) {
3139 foundHoveredWindow = true;
3140 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003141 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003142
3143 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003144 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145 }
3146
3147 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003148 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149 }
3150
Tiger Huang721e26f2018-07-24 22:26:19 +08003151 sp<InputWindowHandle> oldFocusedWindowHandle =
3152 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3153
3154 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3155 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003157 ALOGD("Focus left window: %s in display %" PRId32,
3158 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003160 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3161 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003162 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3164 "focus left window");
3165 synthesizeCancelationEventsForInputChannelLocked(
3166 focusedInputChannel, options);
3167 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003168 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003170 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003172 ALOGD("Focus entered window: %s in display %" PRId32,
3173 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003175 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 }
Robert Carrf759f162018-11-13 12:57:11 -08003177
3178 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003179 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003180 }
3181
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 }
3183
Arthur Hungb92218b2018-08-14 12:00:21 +08003184 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3185 if (stateIndex >= 0) {
3186 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003187 for (size_t i = 0; i < state.windows.size(); ) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003188 TouchedWindow& touchedWindow = state.windows.editItemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003189 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003191 ALOGD("Touched window was removed: %s in display %" PRId32,
3192 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003193#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003194 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003195 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003196 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003197 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3198 "touched window was removed");
3199 synthesizeCancelationEventsForInputChannelLocked(
3200 touchedInputChannel, options);
3201 }
Ivan Lozano96f12992017-11-09 14:45:38 -08003202 state.windows.removeAt(i);
3203 } else {
3204 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206 }
3207 }
3208
3209 // Release information for windows that are no longer present.
3210 // This ensures that unused input channels are released promptly.
3211 // Otherwise, they might stick around until the window handle is destroyed
3212 // which might not happen until the next GC.
Arthur Hungb92218b2018-08-14 12:00:21 +08003213 size_t numWindows = oldWindowHandles.size();
3214 for (size_t i = 0; i < numWindows; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215 const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003216 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003218 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003220 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 }
3222 }
3223 } // release lock
3224
3225 // Wake up poll loop since it may need to make new input dispatching choices.
3226 mLooper->wake();
3227}
3228
3229void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003230 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003232 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233#endif
3234 { // acquire lock
3235 AutoMutex _l(mLock);
3236
Tiger Huang721e26f2018-07-24 22:26:19 +08003237 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3238 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003239 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003240 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3241 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003243 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003245 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003247 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003249 oldFocusedApplicationHandle->releaseInfo();
3250 oldFocusedApplicationHandle.clear();
3251 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003252 }
3253
3254#if DEBUG_FOCUS
3255 //logDispatchStateLocked();
3256#endif
3257 } // release lock
3258
3259 // Wake up poll loop since it may need to make new input dispatching choices.
3260 mLooper->wake();
3261}
3262
Tiger Huang721e26f2018-07-24 22:26:19 +08003263/**
3264 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3265 * the display not specified.
3266 *
3267 * We track any unreleased events for each window. If a window loses the ability to receive the
3268 * released event, we will send a cancel event to it. So when the focused display is changed, we
3269 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3270 * display. The display-specified events won't be affected.
3271 */
3272void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3273#if DEBUG_FOCUS
3274 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3275#endif
3276 { // acquire lock
3277 AutoMutex _l(mLock);
3278
3279 if (mFocusedDisplayId != displayId) {
3280 sp<InputWindowHandle> oldFocusedWindowHandle =
3281 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3282 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003283 sp<InputChannel> inputChannel =
3284 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003285 if (inputChannel != nullptr) {
3286 CancelationOptions options(
3287 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3288 "The display which contains this window no longer has focus.");
3289 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3290 }
3291 }
3292 mFocusedDisplayId = displayId;
3293
3294 // Sanity check
3295 sp<InputWindowHandle> newFocusedWindowHandle =
3296 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003297 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003298
Tiger Huang721e26f2018-07-24 22:26:19 +08003299 if (newFocusedWindowHandle == nullptr) {
3300 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3301 if (!mFocusedWindowHandlesByDisplay.empty()) {
3302 ALOGE("But another display has a focused window:");
3303 for (auto& it : mFocusedWindowHandlesByDisplay) {
3304 const int32_t displayId = it.first;
3305 const sp<InputWindowHandle>& windowHandle = it.second;
3306 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3307 displayId, windowHandle->getName().c_str());
3308 }
3309 }
3310 }
3311 }
3312
3313#if DEBUG_FOCUS
3314 logDispatchStateLocked();
3315#endif
3316 } // release lock
3317
3318 // Wake up poll loop since it may need to make new input dispatching choices.
3319 mLooper->wake();
3320}
3321
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3323#if DEBUG_FOCUS
3324 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3325#endif
3326
3327 bool changed;
3328 { // acquire lock
3329 AutoMutex _l(mLock);
3330
3331 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3332 if (mDispatchFrozen && !frozen) {
3333 resetANRTimeoutsLocked();
3334 }
3335
3336 if (mDispatchEnabled && !enabled) {
3337 resetAndDropEverythingLocked("dispatcher is being disabled");
3338 }
3339
3340 mDispatchEnabled = enabled;
3341 mDispatchFrozen = frozen;
3342 changed = true;
3343 } else {
3344 changed = false;
3345 }
3346
3347#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003348 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003349#endif
3350 } // release lock
3351
3352 if (changed) {
3353 // Wake up poll loop since it may need to make new input dispatching choices.
3354 mLooper->wake();
3355 }
3356}
3357
3358void InputDispatcher::setInputFilterEnabled(bool enabled) {
3359#if DEBUG_FOCUS
3360 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3361#endif
3362
3363 { // acquire lock
3364 AutoMutex _l(mLock);
3365
3366 if (mInputFilterEnabled == enabled) {
3367 return;
3368 }
3369
3370 mInputFilterEnabled = enabled;
3371 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3372 } // release lock
3373
3374 // Wake up poll loop since there might be work to do to drop everything.
3375 mLooper->wake();
3376}
3377
chaviwfbe5d9c2018-12-26 12:23:37 -08003378bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3379 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003381 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003383 return true;
3384 }
3385
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 { // acquire lock
3387 AutoMutex _l(mLock);
3388
chaviwfbe5d9c2018-12-26 12:23:37 -08003389 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3390 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003391 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003392 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 return false;
3394 }
chaviw4f2dd402018-12-26 15:30:27 -08003395#if DEBUG_FOCUS
3396 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3397 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3398#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3400#if DEBUG_FOCUS
3401 ALOGD("Cannot transfer focus because windows are on different displays.");
3402#endif
3403 return false;
3404 }
3405
3406 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003407 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3408 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3409 for (size_t i = 0; i < state.windows.size(); i++) {
3410 const TouchedWindow& touchedWindow = state.windows[i];
3411 if (touchedWindow.windowHandle == fromWindowHandle) {
3412 int32_t oldTargetFlags = touchedWindow.targetFlags;
3413 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414
Jeff Brownf086ddb2014-02-11 14:28:48 -08003415 state.windows.removeAt(i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416
Jeff Brownf086ddb2014-02-11 14:28:48 -08003417 int32_t newTargetFlags = oldTargetFlags
3418 & (InputTarget::FLAG_FOREGROUND
3419 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3420 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421
Jeff Brownf086ddb2014-02-11 14:28:48 -08003422 found = true;
3423 goto Found;
3424 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 }
3426 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003427Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428
3429 if (! found) {
3430#if DEBUG_FOCUS
3431 ALOGD("Focus transfer failed because from window did not have focus.");
3432#endif
3433 return false;
3434 }
3435
chaviwfbe5d9c2018-12-26 12:23:37 -08003436
3437 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3438 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3440 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3441 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3442 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3443 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3444
3445 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3446 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3447 "transferring touch focus from this window to another window");
3448 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3449 }
3450
3451#if DEBUG_FOCUS
3452 logDispatchStateLocked();
3453#endif
3454 } // release lock
3455
3456 // Wake up poll loop since it may need to make new input dispatching choices.
3457 mLooper->wake();
3458 return true;
3459}
3460
3461void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3462#if DEBUG_FOCUS
3463 ALOGD("Resetting and dropping all events (%s).", reason);
3464#endif
3465
3466 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3467 synthesizeCancelationEventsForAllConnectionsLocked(options);
3468
3469 resetKeyRepeatLocked();
3470 releasePendingEventLocked();
3471 drainInboundQueueLocked();
3472 resetANRTimeoutsLocked();
3473
Jeff Brownf086ddb2014-02-11 14:28:48 -08003474 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003476 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477}
3478
3479void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003480 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481 dumpDispatchStateLocked(dump);
3482
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003483 std::istringstream stream(dump);
3484 std::string line;
3485
3486 while (std::getline(stream, line, '\n')) {
3487 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488 }
3489}
3490
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003491void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3492 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3493 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003494 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495
Tiger Huang721e26f2018-07-24 22:26:19 +08003496 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3497 dump += StringPrintf(INDENT "FocusedApplications:\n");
3498 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3499 const int32_t displayId = it.first;
3500 const sp<InputApplicationHandle>& applicationHandle = it.second;
3501 dump += StringPrintf(
3502 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3503 displayId,
3504 applicationHandle->getName().c_str(),
3505 applicationHandle->getDispatchingTimeout(
3506 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3507 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003509 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003511
3512 if (!mFocusedWindowHandlesByDisplay.empty()) {
3513 dump += StringPrintf(INDENT "FocusedWindows:\n");
3514 for (auto& it : mFocusedWindowHandlesByDisplay) {
3515 const int32_t displayId = it.first;
3516 const sp<InputWindowHandle>& windowHandle = it.second;
3517 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3518 displayId, windowHandle->getName().c_str());
3519 }
3520 } else {
3521 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3522 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523
Jeff Brownf086ddb2014-02-11 14:28:48 -08003524 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003525 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003526 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3527 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003528 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003529 state.displayId, toString(state.down), toString(state.split),
3530 state.deviceId, state.source);
3531 if (!state.windows.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003532 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003533 for (size_t i = 0; i < state.windows.size(); i++) {
3534 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003535 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3536 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003537 touchedWindow.pointerIds.value,
3538 touchedWindow.targetFlags);
3539 }
3540 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003541 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003542 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003543 if (!state.portalWindows.isEmpty()) {
3544 dump += INDENT3 "Portal windows:\n";
3545 for (size_t i = 0; i < state.portalWindows.size(); i++) {
3546 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows.itemAt(i);
3547 dump += StringPrintf(INDENT4 "%zu: name='%s'\n",
3548 i, portalWindowHandle->getName().c_str());
3549 }
3550 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003551 }
3552 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003553 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003554 }
3555
Arthur Hungb92218b2018-08-14 12:00:21 +08003556 if (!mWindowHandlesByDisplay.empty()) {
3557 for (auto& it : mWindowHandlesByDisplay) {
3558 const Vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003559 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hungb92218b2018-08-14 12:00:21 +08003560 if (!windowHandles.isEmpty()) {
3561 dump += INDENT2 "Windows:\n";
3562 for (size_t i = 0; i < windowHandles.size(); i++) {
3563 const sp<InputWindowHandle>& windowHandle = windowHandles.itemAt(i);
3564 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565
Arthur Hungb92218b2018-08-14 12:00:21 +08003566 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003567 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, "
Arthur Hungb92218b2018-08-14 12:00:21 +08003568 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003569 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003570 "touchableRegion=",
3571 i, windowInfo->name.c_str(), windowInfo->displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003572 windowInfo->portalToDisplayId,
Arthur Hungb92218b2018-08-14 12:00:21 +08003573 toString(windowInfo->paused),
3574 toString(windowInfo->hasFocus),
3575 toString(windowInfo->hasWallpaper),
3576 toString(windowInfo->visible),
3577 toString(windowInfo->canReceiveKeys),
3578 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3579 windowInfo->layer,
3580 windowInfo->frameLeft, windowInfo->frameTop,
3581 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003582 windowInfo->globalScaleFactor,
3583 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003584 dumpRegion(dump, windowInfo->touchableRegion);
3585 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3586 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3587 windowInfo->ownerPid, windowInfo->ownerUid,
3588 windowInfo->dispatchingTimeout / 1000000.0);
3589 }
3590 } else {
3591 dump += INDENT2 "Windows: <none>\n";
3592 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 }
3594 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003595 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 }
3597
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003598 if (!mMonitoringChannelsByDisplay.empty()) {
3599 for (auto& it : mMonitoringChannelsByDisplay) {
3600 const Vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003601 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003602 const size_t numChannels = monitoringChannels.size();
3603 for (size_t i = 0; i < numChannels; i++) {
3604 const sp<InputChannel>& channel = monitoringChannels[i];
3605 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3606 }
3607 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003609 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003610 }
3611
3612 nsecs_t currentTime = now();
3613
3614 // Dump recently dispatched or dropped events from oldest to newest.
3615 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003616 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003618 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003620 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 (currentTime - entry->eventTime) * 0.000001f);
3622 }
3623 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003624 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003625 }
3626
3627 // Dump event currently being dispatched.
3628 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003629 dump += INDENT "PendingEvent:\n";
3630 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003632 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3634 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003635 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 }
3637
3638 // Dump inbound events from oldest to newest.
3639 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003640 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003642 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003644 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 (currentTime - entry->eventTime) * 0.000001f);
3646 }
3647 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003648 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 }
3650
Michael Wright78f24442014-08-06 15:55:28 -07003651 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003652 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003653 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3654 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3655 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003656 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003657 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3658 }
3659 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003660 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003661 }
3662
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003664 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003665 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3666 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003667 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003669 i, connection->getInputChannelName().c_str(),
3670 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003671 connection->getStatusLabel(), toString(connection->monitor),
3672 toString(connection->inputPublisherBlocked));
3673
3674 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003675 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 connection->outboundQueue.count());
3677 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3678 entry = entry->next) {
3679 dump.append(INDENT4);
3680 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003681 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682 entry->targetFlags, entry->resolvedAction,
3683 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3684 }
3685 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003686 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 }
3688
3689 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003690 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003691 connection->waitQueue.count());
3692 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3693 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003694 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003695 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003696 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 "age=%0.1fms, wait=%0.1fms\n",
3698 entry->targetFlags, entry->resolvedAction,
3699 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3700 (currentTime - entry->deliveryTime) * 0.000001f);
3701 }
3702 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003703 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003704 }
3705 }
3706 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003707 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 }
3709
3710 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003711 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 (mAppSwitchDueTime - now()) / 1000000.0);
3713 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003714 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 }
3716
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003717 dump += INDENT "Configuration:\n";
3718 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003720 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003721 mConfig.keyRepeatTimeout * 0.000001f);
3722}
3723
Robert Carr803535b2018-08-02 16:38:15 -07003724status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003725#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003726 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3727 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003728#endif
3729
3730 { // acquire lock
3731 AutoMutex _l(mLock);
3732
Robert Carr4e670e52018-08-15 13:26:12 -07003733 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3734 // treat inputChannel as monitor channel for displayId.
3735 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3736 if (monitor) {
3737 inputChannel->setToken(new BBinder());
3738 }
3739
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740 if (getConnectionIndexLocked(inputChannel) >= 0) {
3741 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003742 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743 return BAD_VALUE;
3744 }
3745
Robert Carr803535b2018-08-02 16:38:15 -07003746 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747
3748 int fd = inputChannel->getFd();
3749 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003750 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003752 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 if (monitor) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003754 Vector<sp<InputChannel>>& monitoringChannels =
3755 mMonitoringChannelsByDisplay[displayId];
3756 monitoringChannels.push(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757 }
3758
3759 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3760 } // release lock
3761
3762 // Wake the looper because some connections have changed.
3763 mLooper->wake();
3764 return OK;
3765}
3766
3767status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3768#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003769 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770#endif
3771
3772 { // acquire lock
3773 AutoMutex _l(mLock);
3774
3775 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3776 if (status) {
3777 return status;
3778 }
3779 } // release lock
3780
3781 // Wake the poll loop because removing the connection may have changed the current
3782 // synchronization state.
3783 mLooper->wake();
3784 return OK;
3785}
3786
3787status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3788 bool notify) {
3789 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3790 if (connectionIndex < 0) {
3791 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003792 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003793 return BAD_VALUE;
3794 }
3795
3796 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3797 mConnectionsByFd.removeItemsAt(connectionIndex);
3798
Robert Carr5c8a0262018-10-03 16:30:44 -07003799 mInputChannelsByToken.erase(inputChannel->getToken());
3800
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 if (connection->monitor) {
3802 removeMonitorChannelLocked(inputChannel);
3803 }
3804
3805 mLooper->removeFd(inputChannel->getFd());
3806
3807 nsecs_t currentTime = now();
3808 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3809
3810 connection->status = Connection::STATUS_ZOMBIE;
3811 return OK;
3812}
3813
3814void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003815 for (auto it = mMonitoringChannelsByDisplay.begin();
3816 it != mMonitoringChannelsByDisplay.end(); ) {
3817 Vector<sp<InputChannel>>& monitoringChannels = it->second;
3818 const size_t numChannels = monitoringChannels.size();
3819 for (size_t i = 0; i < numChannels; i++) {
3820 if (monitoringChannels[i] == inputChannel) {
3821 monitoringChannels.removeAt(i);
3822 break;
3823 }
3824 }
3825 if (monitoringChannels.empty()) {
3826 it = mMonitoringChannelsByDisplay.erase(it);
3827 } else {
3828 ++it;
3829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003830 }
3831}
3832
3833ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003834 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003835 return -1;
3836 }
3837
Robert Carr4e670e52018-08-15 13:26:12 -07003838 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3839 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3840 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3841 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 }
3843 }
Robert Carr4e670e52018-08-15 13:26:12 -07003844
Michael Wrightd02c5b62014-02-10 15:10:22 -08003845 return -1;
3846}
3847
3848void InputDispatcher::onDispatchCycleFinishedLocked(
3849 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3850 CommandEntry* commandEntry = postCommandLocked(
3851 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3852 commandEntry->connection = connection;
3853 commandEntry->eventTime = currentTime;
3854 commandEntry->seq = seq;
3855 commandEntry->handled = handled;
3856}
3857
3858void InputDispatcher::onDispatchCycleBrokenLocked(
3859 nsecs_t currentTime, const sp<Connection>& connection) {
3860 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003861 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862
3863 CommandEntry* commandEntry = postCommandLocked(
3864 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3865 commandEntry->connection = connection;
3866}
3867
chaviw0c06c6e2019-01-09 13:27:07 -08003868void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
3869 const sp<InputWindowHandle>& newFocus) {
3870 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
3871 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08003872 CommandEntry* commandEntry = postCommandLocked(
3873 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08003874 commandEntry->oldToken = oldToken;
3875 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003876}
3877
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878void InputDispatcher::onANRLocked(
3879 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3880 const sp<InputWindowHandle>& windowHandle,
3881 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3882 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3883 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3884 ALOGI("Application is not responding: %s. "
3885 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003886 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003887 dispatchLatency, waitDuration, reason);
3888
3889 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003890 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891 struct tm tm;
3892 localtime_r(&t, &tm);
3893 char timestr[64];
3894 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3895 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003896 mLastANRState += INDENT "ANR:\n";
3897 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3898 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
3899 getApplicationWindowLabelLocked(applicationHandle, windowHandle).c_str());
3900 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3901 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3902 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 dumpDispatchStateLocked(mLastANRState);
3904
3905 CommandEntry* commandEntry = postCommandLocked(
3906 & InputDispatcher::doNotifyANRLockedInterruptible);
3907 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003908 commandEntry->inputChannel = windowHandle != nullptr ?
3909 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003910 commandEntry->reason = reason;
3911}
3912
3913void InputDispatcher::doNotifyConfigurationChangedInterruptible(
3914 CommandEntry* commandEntry) {
3915 mLock.unlock();
3916
3917 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3918
3919 mLock.lock();
3920}
3921
3922void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3923 CommandEntry* commandEntry) {
3924 sp<Connection> connection = commandEntry->connection;
3925
3926 if (connection->status != Connection::STATUS_ZOMBIE) {
3927 mLock.unlock();
3928
Robert Carr803535b2018-08-02 16:38:15 -07003929 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930
3931 mLock.lock();
3932 }
3933}
3934
Robert Carrf759f162018-11-13 12:57:11 -08003935void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3936 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08003937 sp<IBinder> oldToken = commandEntry->oldToken;
3938 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003939 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08003940 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08003941 mLock.lock();
3942}
3943
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944void InputDispatcher::doNotifyANRLockedInterruptible(
3945 CommandEntry* commandEntry) {
3946 mLock.unlock();
3947
3948 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003949 commandEntry->inputApplicationHandle,
3950 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 commandEntry->reason);
3952
3953 mLock.lock();
3954
3955 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003956 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957}
3958
3959void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3960 CommandEntry* commandEntry) {
3961 KeyEntry* entry = commandEntry->keyEntry;
3962
3963 KeyEvent event;
3964 initializeKeyEvent(&event, entry);
3965
3966 mLock.unlock();
3967
Michael Wright2b3c3302018-03-02 17:19:13 +00003968 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003969 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3970 commandEntry->inputChannel->getToken() : nullptr;
3971 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003973 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3974 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3975 std::to_string(t.duration().count()).c_str());
3976 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977
3978 mLock.lock();
3979
3980 if (delay < 0) {
3981 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3982 } else if (!delay) {
3983 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3984 } else {
3985 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3986 entry->interceptKeyWakeupTime = now() + delay;
3987 }
3988 entry->release();
3989}
3990
3991void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
3992 CommandEntry* commandEntry) {
3993 sp<Connection> connection = commandEntry->connection;
3994 nsecs_t finishTime = commandEntry->eventTime;
3995 uint32_t seq = commandEntry->seq;
3996 bool handled = commandEntry->handled;
3997
3998 // Handle post-event policy actions.
3999 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4000 if (dispatchEntry) {
4001 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4002 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004003 std::string msg =
4004 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004005 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004007 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008 }
4009
4010 bool restartEvent;
4011 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4012 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4013 restartEvent = afterKeyEventLockedInterruptible(connection,
4014 dispatchEntry, keyEntry, handled);
4015 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4016 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4017 restartEvent = afterMotionEventLockedInterruptible(connection,
4018 dispatchEntry, motionEntry, handled);
4019 } else {
4020 restartEvent = false;
4021 }
4022
4023 // Dequeue the event and start the next cycle.
4024 // Note that because the lock might have been released, it is possible that the
4025 // contents of the wait queue to have been drained, so we need to double-check
4026 // a few things.
4027 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4028 connection->waitQueue.dequeue(dispatchEntry);
4029 traceWaitQueueLengthLocked(connection);
4030 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4031 connection->outboundQueue.enqueueAtHead(dispatchEntry);
4032 traceOutboundQueueLengthLocked(connection);
4033 } else {
4034 releaseDispatchEntryLocked(dispatchEntry);
4035 }
4036 }
4037
4038 // Start the next dispatch cycle for this connection.
4039 startDispatchCycleLocked(now(), connection);
4040 }
4041}
4042
4043bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4044 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004045 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004046 if (!handled) {
4047 // Report the key as unhandled, since the fallback was not handled.
4048 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4049 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004050 return false;
4051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004053 // Get the fallback key state.
4054 // Clear it out after dispatching the UP.
4055 int32_t originalKeyCode = keyEntry->keyCode;
4056 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4057 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4058 connection->inputState.removeFallbackKey(originalKeyCode);
4059 }
4060
4061 if (handled || !dispatchEntry->hasForegroundTarget()) {
4062 // If the application handles the original key for which we previously
4063 // generated a fallback or if the window is not a foreground window,
4064 // then cancel the associated fallback key, if any.
4065 if (fallbackKeyCode != -1) {
4066 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004068 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004069 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4070 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4071 keyEntry->policyFlags);
4072#endif
4073 KeyEvent event;
4074 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004075 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076
4077 mLock.unlock();
4078
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004079 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4080 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081
4082 mLock.lock();
4083
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004084 // Cancel the fallback key.
4085 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004087 "application handled the original non-fallback key "
4088 "or is no longer a foreground target, "
4089 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 options.keyCode = fallbackKeyCode;
4091 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004093 connection->inputState.removeFallbackKey(originalKeyCode);
4094 }
4095 } else {
4096 // If the application did not handle a non-fallback key, first check
4097 // that we are in a good state to perform unhandled key event processing
4098 // Then ask the policy what to do with it.
4099 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4100 && keyEntry->repeatCount == 0;
4101 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004103 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4104 "since this is not an initial down. "
4105 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4106 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4107 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004109 return false;
4110 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004112 // Dispatch the unhandled key to the policy.
4113#if DEBUG_OUTBOUND_EVENT_DETAILS
4114 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4115 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4116 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4117 keyEntry->policyFlags);
4118#endif
4119 KeyEvent event;
4120 initializeKeyEvent(&event, keyEntry);
4121
4122 mLock.unlock();
4123
4124 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4125 &event, keyEntry->policyFlags, &event);
4126
4127 mLock.lock();
4128
4129 if (connection->status != Connection::STATUS_NORMAL) {
4130 connection->inputState.removeFallbackKey(originalKeyCode);
4131 return false;
4132 }
4133
4134 // Latch the fallback keycode for this key on an initial down.
4135 // The fallback keycode cannot change at any other point in the lifecycle.
4136 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004138 fallbackKeyCode = event.getKeyCode();
4139 } else {
4140 fallbackKeyCode = AKEYCODE_UNKNOWN;
4141 }
4142 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4143 }
4144
4145 ALOG_ASSERT(fallbackKeyCode != -1);
4146
4147 // Cancel the fallback key if the policy decides not to send it anymore.
4148 // We will continue to dispatch the key to the policy but we will no
4149 // longer dispatch a fallback key to the application.
4150 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4151 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4152#if DEBUG_OUTBOUND_EVENT_DETAILS
4153 if (fallback) {
4154 ALOGD("Unhandled key event: Policy requested to send key %d"
4155 "as a fallback for %d, but on the DOWN it had requested "
4156 "to send %d instead. Fallback canceled.",
4157 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4158 } else {
4159 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4160 "but on the DOWN it had requested to send %d. "
4161 "Fallback canceled.",
4162 originalKeyCode, fallbackKeyCode);
4163 }
4164#endif
4165
4166 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4167 "canceling fallback, policy no longer desires it");
4168 options.keyCode = fallbackKeyCode;
4169 synthesizeCancelationEventsForConnectionLocked(connection, options);
4170
4171 fallback = false;
4172 fallbackKeyCode = AKEYCODE_UNKNOWN;
4173 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4174 connection->inputState.setFallbackKey(originalKeyCode,
4175 fallbackKeyCode);
4176 }
4177 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178
4179#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004180 {
4181 std::string msg;
4182 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4183 connection->inputState.getFallbackKeys();
4184 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4185 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4186 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004188 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4189 fallbackKeys.size(), msg.c_str());
4190 }
4191#endif
4192
4193 if (fallback) {
4194 // Restart the dispatch cycle using the fallback key.
4195 keyEntry->eventTime = event.getEventTime();
4196 keyEntry->deviceId = event.getDeviceId();
4197 keyEntry->source = event.getSource();
4198 keyEntry->displayId = event.getDisplayId();
4199 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4200 keyEntry->keyCode = fallbackKeyCode;
4201 keyEntry->scanCode = event.getScanCode();
4202 keyEntry->metaState = event.getMetaState();
4203 keyEntry->repeatCount = event.getRepeatCount();
4204 keyEntry->downTime = event.getDownTime();
4205 keyEntry->syntheticRepeat = false;
4206
4207#if DEBUG_OUTBOUND_EVENT_DETAILS
4208 ALOGD("Unhandled key event: Dispatching fallback key. "
4209 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4210 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4211#endif
4212 return true; // restart the event
4213 } else {
4214#if DEBUG_OUTBOUND_EVENT_DETAILS
4215 ALOGD("Unhandled key event: No fallback key.");
4216#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004217
4218 // Report the key as unhandled, since there is no fallback key.
4219 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 }
4221 }
4222 return false;
4223}
4224
4225bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4226 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4227 return false;
4228}
4229
4230void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4231 mLock.unlock();
4232
4233 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4234
4235 mLock.lock();
4236}
4237
4238void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004239 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4241 entry->downTime, entry->eventTime);
4242}
4243
4244void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
4245 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4246 // TODO Write some statistics about how long we spend waiting.
4247}
4248
4249void InputDispatcher::traceInboundQueueLengthLocked() {
4250 if (ATRACE_ENABLED()) {
4251 ATRACE_INT("iq", mInboundQueue.count());
4252 }
4253}
4254
4255void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
4256 if (ATRACE_ENABLED()) {
4257 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004258 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 ATRACE_INT(counterName, connection->outboundQueue.count());
4260 }
4261}
4262
4263void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
4264 if (ATRACE_ENABLED()) {
4265 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004266 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 ATRACE_INT(counterName, connection->waitQueue.count());
4268 }
4269}
4270
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004271void InputDispatcher::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 AutoMutex _l(mLock);
4273
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004274 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 dumpDispatchStateLocked(dump);
4276
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004277 if (!mLastANRState.empty()) {
4278 dump += "\nInput Dispatcher State at time of last ANR:\n";
4279 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 }
4281}
4282
4283void InputDispatcher::monitor() {
4284 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
4285 mLock.lock();
4286 mLooper->wake();
4287 mDispatcherIsAliveCondition.wait(mLock);
4288 mLock.unlock();
4289}
4290
4291
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292// --- InputDispatcher::InjectionState ---
4293
4294InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4295 refCount(1),
4296 injectorPid(injectorPid), injectorUid(injectorUid),
4297 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4298 pendingForegroundDispatches(0) {
4299}
4300
4301InputDispatcher::InjectionState::~InjectionState() {
4302}
4303
4304void InputDispatcher::InjectionState::release() {
4305 refCount -= 1;
4306 if (refCount == 0) {
4307 delete this;
4308 } else {
4309 ALOG_ASSERT(refCount > 0);
4310 }
4311}
4312
4313
4314// --- InputDispatcher::EventEntry ---
4315
Prabir Pradhan42611e02018-11-27 14:04:02 -08004316InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4317 nsecs_t eventTime, uint32_t policyFlags) :
4318 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4319 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320}
4321
4322InputDispatcher::EventEntry::~EventEntry() {
4323 releaseInjectionState();
4324}
4325
4326void InputDispatcher::EventEntry::release() {
4327 refCount -= 1;
4328 if (refCount == 0) {
4329 delete this;
4330 } else {
4331 ALOG_ASSERT(refCount > 0);
4332 }
4333}
4334
4335void InputDispatcher::EventEntry::releaseInjectionState() {
4336 if (injectionState) {
4337 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004338 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 }
4340}
4341
4342
4343// --- InputDispatcher::ConfigurationChangedEntry ---
4344
Prabir Pradhan42611e02018-11-27 14:04:02 -08004345InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4346 uint32_t sequenceNum, nsecs_t eventTime) :
4347 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348}
4349
4350InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4351}
4352
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004353void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4354 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355}
4356
4357
4358// --- InputDispatcher::DeviceResetEntry ---
4359
Prabir Pradhan42611e02018-11-27 14:04:02 -08004360InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4361 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4362 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363 deviceId(deviceId) {
4364}
4365
4366InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4367}
4368
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004369void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4370 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371 deviceId, policyFlags);
4372}
4373
4374
4375// --- InputDispatcher::KeyEntry ---
4376
Prabir Pradhan42611e02018-11-27 14:04:02 -08004377InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004378 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004379 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4380 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004381 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004382 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4384 repeatCount(repeatCount), downTime(downTime),
4385 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4386 interceptKeyWakeupTime(0) {
4387}
4388
4389InputDispatcher::KeyEntry::~KeyEntry() {
4390}
4391
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004392void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004393 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004394 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4395 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004396 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004397 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004398}
4399
4400void InputDispatcher::KeyEntry::recycle() {
4401 releaseInjectionState();
4402
4403 dispatchInProgress = false;
4404 syntheticRepeat = false;
4405 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4406 interceptKeyWakeupTime = 0;
4407}
4408
4409
4410// --- InputDispatcher::MotionEntry ---
4411
Prabir Pradhan42611e02018-11-27 14:04:02 -08004412InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004413 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4414 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004415 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4416 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004417 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004418 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4419 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004420 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004421 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004422 deviceId(deviceId), source(source), displayId(displayId), action(action),
4423 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004424 classification(classification), edgeFlags(edgeFlags),
4425 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004426 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 for (uint32_t i = 0; i < pointerCount; i++) {
4428 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4429 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004430 if (xOffset || yOffset) {
4431 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4432 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004433 }
4434}
4435
4436InputDispatcher::MotionEntry::~MotionEntry() {
4437}
4438
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004439void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004440 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004441 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004442 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004443 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004444 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4445 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004446
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447 for (uint32_t i = 0; i < pointerCount; i++) {
4448 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004449 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004451 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004452 pointerCoords[i].getX(), pointerCoords[i].getY());
4453 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004454 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004455}
4456
4457
4458// --- InputDispatcher::DispatchEntry ---
4459
4460volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4461
4462InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004463 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4464 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465 seq(nextSeq()),
4466 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004467 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4468 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4470 eventEntry->refCount += 1;
4471}
4472
4473InputDispatcher::DispatchEntry::~DispatchEntry() {
4474 eventEntry->release();
4475}
4476
4477uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4478 // Sequence number 0 is reserved and will never be returned.
4479 uint32_t seq;
4480 do {
4481 seq = android_atomic_inc(&sNextSeqAtomic);
4482 } while (!seq);
4483 return seq;
4484}
4485
4486
4487// --- InputDispatcher::InputState ---
4488
4489InputDispatcher::InputState::InputState() {
4490}
4491
4492InputDispatcher::InputState::~InputState() {
4493}
4494
4495bool InputDispatcher::InputState::isNeutral() const {
4496 return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
4497}
4498
4499bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4500 int32_t displayId) const {
4501 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4502 const MotionMemento& memento = mMotionMementos.itemAt(i);
4503 if (memento.deviceId == deviceId
4504 && memento.source == source
4505 && memento.displayId == displayId
4506 && memento.hovering) {
4507 return true;
4508 }
4509 }
4510 return false;
4511}
4512
4513bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4514 int32_t action, int32_t flags) {
4515 switch (action) {
4516 case AKEY_EVENT_ACTION_UP: {
4517 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4518 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4519 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4520 mFallbackKeys.removeItemsAt(i);
4521 } else {
4522 i += 1;
4523 }
4524 }
4525 }
4526 ssize_t index = findKeyMemento(entry);
4527 if (index >= 0) {
4528 mKeyMementos.removeAt(index);
4529 return true;
4530 }
4531 /* FIXME: We can't just drop the key up event because that prevents creating
4532 * popup windows that are automatically shown when a key is held and then
4533 * dismissed when the key is released. The problem is that the popup will
4534 * not have received the original key down, so the key up will be considered
4535 * to be inconsistent with its observed state. We could perhaps handle this
4536 * by synthesizing a key down but that will cause other problems.
4537 *
4538 * So for now, allow inconsistent key up events to be dispatched.
4539 *
4540#if DEBUG_OUTBOUND_EVENT_DETAILS
4541 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4542 "keyCode=%d, scanCode=%d",
4543 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4544#endif
4545 return false;
4546 */
4547 return true;
4548 }
4549
4550 case AKEY_EVENT_ACTION_DOWN: {
4551 ssize_t index = findKeyMemento(entry);
4552 if (index >= 0) {
4553 mKeyMementos.removeAt(index);
4554 }
4555 addKeyMemento(entry, flags);
4556 return true;
4557 }
4558
4559 default:
4560 return true;
4561 }
4562}
4563
4564bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4565 int32_t action, int32_t flags) {
4566 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4567 switch (actionMasked) {
4568 case AMOTION_EVENT_ACTION_UP:
4569 case AMOTION_EVENT_ACTION_CANCEL: {
4570 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4571 if (index >= 0) {
4572 mMotionMementos.removeAt(index);
4573 return true;
4574 }
4575#if DEBUG_OUTBOUND_EVENT_DETAILS
4576 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004577 "displayId=%" PRId32 ", actionMasked=%d",
4578 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579#endif
4580 return false;
4581 }
4582
4583 case AMOTION_EVENT_ACTION_DOWN: {
4584 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4585 if (index >= 0) {
4586 mMotionMementos.removeAt(index);
4587 }
4588 addMotionMemento(entry, flags, false /*hovering*/);
4589 return true;
4590 }
4591
4592 case AMOTION_EVENT_ACTION_POINTER_UP:
4593 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4594 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004595 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4596 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4597 // generate cancellation events for these since they're based in relative rather than
4598 // absolute units.
4599 return true;
4600 }
4601
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004603
4604 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4605 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4606 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4607 // other value and we need to track the motion so we can send cancellation events for
4608 // anything generating fallback events (e.g. DPad keys for joystick movements).
4609 if (index >= 0) {
4610 if (entry->pointerCoords[0].isEmpty()) {
4611 mMotionMementos.removeAt(index);
4612 } else {
4613 MotionMemento& memento = mMotionMementos.editItemAt(index);
4614 memento.setPointers(entry);
4615 }
4616 } else if (!entry->pointerCoords[0].isEmpty()) {
4617 addMotionMemento(entry, flags, false /*hovering*/);
4618 }
4619
4620 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4621 return true;
4622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623 if (index >= 0) {
4624 MotionMemento& memento = mMotionMementos.editItemAt(index);
4625 memento.setPointers(entry);
4626 return true;
4627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628#if DEBUG_OUTBOUND_EVENT_DETAILS
4629 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004630 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4631 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632#endif
4633 return false;
4634 }
4635
4636 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4637 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4638 if (index >= 0) {
4639 mMotionMementos.removeAt(index);
4640 return true;
4641 }
4642#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004643 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4644 "displayId=%" PRId32,
4645 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004646#endif
4647 return false;
4648 }
4649
4650 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4651 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4652 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4653 if (index >= 0) {
4654 mMotionMementos.removeAt(index);
4655 }
4656 addMotionMemento(entry, flags, true /*hovering*/);
4657 return true;
4658 }
4659
4660 default:
4661 return true;
4662 }
4663}
4664
4665ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4666 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4667 const KeyMemento& memento = mKeyMementos.itemAt(i);
4668 if (memento.deviceId == entry->deviceId
4669 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004670 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671 && memento.keyCode == entry->keyCode
4672 && memento.scanCode == entry->scanCode) {
4673 return i;
4674 }
4675 }
4676 return -1;
4677}
4678
4679ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4680 bool hovering) const {
4681 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4682 const MotionMemento& memento = mMotionMementos.itemAt(i);
4683 if (memento.deviceId == entry->deviceId
4684 && memento.source == entry->source
4685 && memento.displayId == entry->displayId
4686 && memento.hovering == hovering) {
4687 return i;
4688 }
4689 }
4690 return -1;
4691}
4692
4693void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
4694 mKeyMementos.push();
4695 KeyMemento& memento = mKeyMementos.editTop();
4696 memento.deviceId = entry->deviceId;
4697 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004698 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699 memento.keyCode = entry->keyCode;
4700 memento.scanCode = entry->scanCode;
4701 memento.metaState = entry->metaState;
4702 memento.flags = flags;
4703 memento.downTime = entry->downTime;
4704 memento.policyFlags = entry->policyFlags;
4705}
4706
4707void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4708 int32_t flags, bool hovering) {
4709 mMotionMementos.push();
4710 MotionMemento& memento = mMotionMementos.editTop();
4711 memento.deviceId = entry->deviceId;
4712 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004713 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714 memento.flags = flags;
4715 memento.xPrecision = entry->xPrecision;
4716 memento.yPrecision = entry->yPrecision;
4717 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718 memento.setPointers(entry);
4719 memento.hovering = hovering;
4720 memento.policyFlags = entry->policyFlags;
4721}
4722
4723void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4724 pointerCount = entry->pointerCount;
4725 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4726 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4727 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4728 }
4729}
4730
4731void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
4732 Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4733 for (size_t i = 0; i < mKeyMementos.size(); i++) {
4734 const KeyMemento& memento = mKeyMementos.itemAt(i);
4735 if (shouldCancelKey(memento, options)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08004736 outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004737 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004738 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4739 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4740 }
4741 }
4742
4743 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4744 const MotionMemento& memento = mMotionMementos.itemAt(i);
4745 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004746 const int32_t action = memento.hovering ?
4747 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Prabir Pradhan42611e02018-11-27 14:04:02 -08004748 outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004749 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004750 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4751 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004753 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004754 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 }
4756 }
4757}
4758
4759void InputDispatcher::InputState::clear() {
4760 mKeyMementos.clear();
4761 mMotionMementos.clear();
4762 mFallbackKeys.clear();
4763}
4764
4765void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4766 for (size_t i = 0; i < mMotionMementos.size(); i++) {
4767 const MotionMemento& memento = mMotionMementos.itemAt(i);
4768 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4769 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
4770 const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
4771 if (memento.deviceId == otherMemento.deviceId
4772 && memento.source == otherMemento.source
4773 && memento.displayId == otherMemento.displayId) {
4774 other.mMotionMementos.removeAt(j);
4775 } else {
4776 j += 1;
4777 }
4778 }
4779 other.mMotionMementos.push(memento);
4780 }
4781 }
4782}
4783
4784int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4785 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4786 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4787}
4788
4789void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4790 int32_t fallbackKeyCode) {
4791 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4792 if (index >= 0) {
4793 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4794 } else {
4795 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4796 }
4797}
4798
4799void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4800 mFallbackKeys.removeItem(originalKeyCode);
4801}
4802
4803bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4804 const CancelationOptions& options) {
4805 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4806 return false;
4807 }
4808
4809 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4810 return false;
4811 }
4812
4813 switch (options.mode) {
4814 case CancelationOptions::CANCEL_ALL_EVENTS:
4815 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4816 return true;
4817 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4818 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004819 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4820 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821 default:
4822 return false;
4823 }
4824}
4825
4826bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4827 const CancelationOptions& options) {
4828 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4829 return false;
4830 }
4831
4832 switch (options.mode) {
4833 case CancelationOptions::CANCEL_ALL_EVENTS:
4834 return true;
4835 case CancelationOptions::CANCEL_POINTER_EVENTS:
4836 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4837 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4838 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004839 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4840 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 default:
4842 return false;
4843 }
4844}
4845
4846
4847// --- InputDispatcher::Connection ---
4848
Robert Carr803535b2018-08-02 16:38:15 -07004849InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4850 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 monitor(monitor),
4852 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4853}
4854
4855InputDispatcher::Connection::~Connection() {
4856}
4857
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004858const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004859 if (inputChannel != nullptr) {
4860 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004861 }
4862 if (monitor) {
4863 return "monitor";
4864 }
4865 return "?";
4866}
4867
4868const char* InputDispatcher::Connection::getStatusLabel() const {
4869 switch (status) {
4870 case STATUS_NORMAL:
4871 return "NORMAL";
4872
4873 case STATUS_BROKEN:
4874 return "BROKEN";
4875
4876 case STATUS_ZOMBIE:
4877 return "ZOMBIE";
4878
4879 default:
4880 return "UNKNOWN";
4881 }
4882}
4883
4884InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004885 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886 if (entry->seq == seq) {
4887 return entry;
4888 }
4889 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004890 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891}
4892
4893
4894// --- InputDispatcher::CommandEntry ---
4895
4896InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004897 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898 seq(0), handled(false) {
4899}
4900
4901InputDispatcher::CommandEntry::~CommandEntry() {
4902}
4903
4904
4905// --- InputDispatcher::TouchState ---
4906
4907InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004908 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909}
4910
4911InputDispatcher::TouchState::~TouchState() {
4912}
4913
4914void InputDispatcher::TouchState::reset() {
4915 down = false;
4916 split = false;
4917 deviceId = -1;
4918 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004919 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004920 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004921 portalWindows.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922}
4923
4924void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4925 down = other.down;
4926 split = other.split;
4927 deviceId = other.deviceId;
4928 source = other.source;
4929 displayId = other.displayId;
4930 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004931 portalWindows = other.portalWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932}
4933
4934void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4935 int32_t targetFlags, BitSet32 pointerIds) {
4936 if (targetFlags & InputTarget::FLAG_SPLIT) {
4937 split = true;
4938 }
4939
4940 for (size_t i = 0; i < windows.size(); i++) {
4941 TouchedWindow& touchedWindow = windows.editItemAt(i);
4942 if (touchedWindow.windowHandle == windowHandle) {
4943 touchedWindow.targetFlags |= targetFlags;
4944 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4945 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4946 }
4947 touchedWindow.pointerIds.value |= pointerIds.value;
4948 return;
4949 }
4950 }
4951
4952 windows.push();
4953
4954 TouchedWindow& touchedWindow = windows.editTop();
4955 touchedWindow.windowHandle = windowHandle;
4956 touchedWindow.targetFlags = targetFlags;
4957 touchedWindow.pointerIds = pointerIds;
4958}
4959
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004960void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
4961 size_t numWindows = portalWindows.size();
4962 for (size_t i = 0; i < numWindows; i++) {
4963 sp<InputWindowHandle> portalWindowHandle = portalWindows.itemAt(i);
4964 if (portalWindowHandle == windowHandle) {
4965 return;
4966 }
4967 }
4968 portalWindows.push_back(windowHandle);
4969}
4970
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4972 for (size_t i = 0; i < windows.size(); i++) {
4973 if (windows.itemAt(i).windowHandle == windowHandle) {
4974 windows.removeAt(i);
4975 return;
4976 }
4977 }
4978}
4979
Robert Carr803535b2018-08-02 16:38:15 -07004980void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4981 for (size_t i = 0; i < windows.size(); i++) {
Robert Carr5c8a0262018-10-03 16:30:44 -07004982 if (windows.itemAt(i).windowHandle->getToken() == token) {
Robert Carr803535b2018-08-02 16:38:15 -07004983 windows.removeAt(i);
4984 return;
4985 }
4986 }
4987}
4988
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4990 for (size_t i = 0 ; i < windows.size(); ) {
4991 TouchedWindow& window = windows.editItemAt(i);
4992 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4993 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4994 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
4995 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
4996 i += 1;
4997 } else {
4998 windows.removeAt(i);
4999 }
5000 }
5001}
5002
5003sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
5004 for (size_t i = 0; i < windows.size(); i++) {
5005 const TouchedWindow& window = windows.itemAt(i);
5006 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5007 return window.windowHandle;
5008 }
5009 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005010 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011}
5012
5013bool InputDispatcher::TouchState::isSlippery() const {
5014 // Must have exactly one foreground window.
5015 bool haveSlipperyForegroundWindow = false;
5016 for (size_t i = 0; i < windows.size(); i++) {
5017 const TouchedWindow& window = windows.itemAt(i);
5018 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5019 if (haveSlipperyForegroundWindow
5020 || !(window.windowHandle->getInfo()->layoutParamsFlags
5021 & InputWindowInfo::FLAG_SLIPPERY)) {
5022 return false;
5023 }
5024 haveSlipperyForegroundWindow = true;
5025 }
5026 }
5027 return haveSlipperyForegroundWindow;
5028}
5029
5030
5031// --- InputDispatcherThread ---
5032
5033InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5034 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5035}
5036
5037InputDispatcherThread::~InputDispatcherThread() {
5038}
5039
5040bool InputDispatcherThread::threadLoop() {
5041 mDispatcher->dispatchOnce();
5042 return true;
5043}
5044
5045} // namespace android