blob: b921d954dc59ec8fc19ac7a904d1a80bcb78dc27 [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
Michael Wright3dd60e22019-03-27 22:06:44 +000020#define LOG_NDEBUG 0
Michael Wrightd02c5b62014-02-10 15:10:22 -080021
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>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080049#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <limits.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080051#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070052#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080053#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054#include <unistd.h>
55
Michael Wright2b3c3302018-03-02 17:19:13 +000056#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057#include <android-base/stringprintf.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070058#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070059#include <utils/Trace.h>
60#include <powermanager/PowerManager.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
Michael Wright3dd60e22019-03-27 22:06:44 +0000112static std::string dispatchModeToString(int32_t dispatchMode) {
113 switch (dispatchMode) {
114 case InputTarget::FLAG_DISPATCH_AS_IS:
115 return "DISPATCH_AS_IS";
116 case InputTarget::FLAG_DISPATCH_AS_OUTSIDE:
117 return "DISPATCH_AS_OUTSIDE";
118 case InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER:
119 return "DISPATCH_AS_HOVER_ENTER";
120 case InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT:
121 return "DISPATCH_AS_HOVER_EXIT";
122 case InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT:
123 return "DISPATCH_AS_SLIPPERY_EXIT";
124 case InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER:
125 return "DISPATCH_AS_SLIPPERY_ENTER";
126 }
127 return StringPrintf("%" PRId32, dispatchMode);
128}
129
Michael Wrightd02c5b62014-02-10 15:10:22 -0800130static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
131 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
132 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
133}
134
135static bool isValidKeyAction(int32_t action) {
136 switch (action) {
137 case AKEY_EVENT_ACTION_DOWN:
138 case AKEY_EVENT_ACTION_UP:
139 return true;
140 default:
141 return false;
142 }
143}
144
145static bool validateKeyEvent(int32_t action) {
146 if (! isValidKeyAction(action)) {
147 ALOGE("Key event has invalid action code 0x%x", action);
148 return false;
149 }
150 return true;
151}
152
Michael Wright7b159c92015-05-14 14:48:03 +0100153static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800154 switch (action & AMOTION_EVENT_ACTION_MASK) {
155 case AMOTION_EVENT_ACTION_DOWN:
156 case AMOTION_EVENT_ACTION_UP:
157 case AMOTION_EVENT_ACTION_CANCEL:
158 case AMOTION_EVENT_ACTION_MOVE:
159 case AMOTION_EVENT_ACTION_OUTSIDE:
160 case AMOTION_EVENT_ACTION_HOVER_ENTER:
161 case AMOTION_EVENT_ACTION_HOVER_MOVE:
162 case AMOTION_EVENT_ACTION_HOVER_EXIT:
163 case AMOTION_EVENT_ACTION_SCROLL:
164 return true;
165 case AMOTION_EVENT_ACTION_POINTER_DOWN:
166 case AMOTION_EVENT_ACTION_POINTER_UP: {
167 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800168 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800169 }
Michael Wright7b159c92015-05-14 14:48:03 +0100170 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
171 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
172 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800173 default:
174 return false;
175 }
176}
177
Michael Wright7b159c92015-05-14 14:48:03 +0100178static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800179 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100180 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181 ALOGE("Motion event has invalid action code 0x%x", action);
182 return false;
183 }
184 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000185 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186 pointerCount, MAX_POINTERS);
187 return false;
188 }
189 BitSet32 pointerIdBits;
190 for (size_t i = 0; i < pointerCount; i++) {
191 int32_t id = pointerProperties[i].id;
192 if (id < 0 || id > MAX_POINTER_ID) {
193 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
194 id, MAX_POINTER_ID);
195 return false;
196 }
197 if (pointerIdBits.hasBit(id)) {
198 ALOGE("Motion event has duplicate pointer id %d", id);
199 return false;
200 }
201 pointerIdBits.markBit(id);
202 }
203 return true;
204}
205
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800206static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800208 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 return;
210 }
211
212 bool first = true;
213 Region::const_iterator cur = region.begin();
214 Region::const_iterator const tail = region.end();
215 while (cur != tail) {
216 if (first) {
217 first = false;
218 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800219 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800221 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 cur++;
223 }
224}
225
Tiger Huang721e26f2018-07-24 22:26:19 +0800226template<typename T, typename U>
227static T getValueByKey(std::unordered_map<U, T>& map, U key) {
228 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
229 return it != map.end() ? it->second : T{};
230}
231
Michael Wrightd02c5b62014-02-10 15:10:22 -0800232
233// --- InputDispatcher ---
234
235InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
236 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700237 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100238 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700239 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800240 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800241 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
243 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800244 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245
Yi Kong9b14ac62018-07-17 13:48:38 -0700246 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247
248 policy->getDispatcherConfiguration(&mConfig);
249}
250
251InputDispatcher::~InputDispatcher() {
252 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800253 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800254
255 resetKeyRepeatLocked();
256 releasePendingEventLocked();
257 drainInboundQueueLocked();
258 }
259
260 while (mConnectionsByFd.size() != 0) {
261 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
262 }
263}
264
265void InputDispatcher::dispatchOnce() {
266 nsecs_t nextWakeupTime = LONG_LONG_MAX;
267 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800268 std::scoped_lock _l(mLock);
269 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800270
271 // Run a dispatch loop if there are no pending commands.
272 // The dispatch loop might enqueue commands to run afterwards.
273 if (!haveCommandsLocked()) {
274 dispatchOnceInnerLocked(&nextWakeupTime);
275 }
276
277 // Run all pending commands if there are any.
278 // If any commands were run then force the next poll to wake up immediately.
279 if (runCommandsLockedInterruptible()) {
280 nextWakeupTime = LONG_LONG_MIN;
281 }
282 } // release lock
283
284 // Wait for callback or timeout or wake. (make sure we round up, not down)
285 nsecs_t currentTime = now();
286 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
287 mLooper->pollOnce(timeoutMillis);
288}
289
290void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
291 nsecs_t currentTime = now();
292
Jeff Browndc5992e2014-04-11 01:27:26 -0700293 // Reset the key repeat timer whenever normal dispatch is suspended while the
294 // device is in a non-interactive state. This is to ensure that we abort a key
295 // repeat if the device is just coming out of sleep.
296 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800297 resetKeyRepeatLocked();
298 }
299
300 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
301 if (mDispatchFrozen) {
302#if DEBUG_FOCUS
303 ALOGD("Dispatch frozen. Waiting some more.");
304#endif
305 return;
306 }
307
308 // Optimize latency of app switches.
309 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
310 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
311 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
312 if (mAppSwitchDueTime < *nextWakeupTime) {
313 *nextWakeupTime = mAppSwitchDueTime;
314 }
315
316 // Ready to start a new event.
317 // If we don't already have a pending event, go grab one.
318 if (! mPendingEvent) {
319 if (mInboundQueue.isEmpty()) {
320 if (isAppSwitchDue) {
321 // The inbound queue is empty so the app switch key we were waiting
322 // for will never arrive. Stop waiting for it.
323 resetPendingAppSwitchLocked(false);
324 isAppSwitchDue = false;
325 }
326
327 // Synthesize a key repeat if appropriate.
328 if (mKeyRepeatState.lastKeyEntry) {
329 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
330 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
331 } else {
332 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
333 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
334 }
335 }
336 }
337
338 // Nothing to do if there is no pending event.
339 if (!mPendingEvent) {
340 return;
341 }
342 } else {
343 // Inbound queue has at least one entry.
344 mPendingEvent = mInboundQueue.dequeueAtHead();
345 traceInboundQueueLengthLocked();
346 }
347
348 // Poke user activity for this event.
349 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
350 pokeUserActivityLocked(mPendingEvent);
351 }
352
353 // Get ready to dispatch the event.
354 resetANRTimeoutsLocked();
355 }
356
357 // Now we have an event to dispatch.
358 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700359 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800360 bool done = false;
361 DropReason dropReason = DROP_REASON_NOT_DROPPED;
362 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
363 dropReason = DROP_REASON_POLICY;
364 } else if (!mDispatchEnabled) {
365 dropReason = DROP_REASON_DISABLED;
366 }
367
368 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700369 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800370 }
371
372 switch (mPendingEvent->type) {
373 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
374 ConfigurationChangedEntry* typedEntry =
375 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
376 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
377 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
378 break;
379 }
380
381 case EventEntry::TYPE_DEVICE_RESET: {
382 DeviceResetEntry* typedEntry =
383 static_cast<DeviceResetEntry*>(mPendingEvent);
384 done = dispatchDeviceResetLocked(currentTime, typedEntry);
385 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
386 break;
387 }
388
389 case EventEntry::TYPE_KEY: {
390 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
391 if (isAppSwitchDue) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800392 if (isAppSwitchKeyEvent(typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800393 resetPendingAppSwitchLocked(true);
394 isAppSwitchDue = false;
395 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
396 dropReason = DROP_REASON_APP_SWITCH;
397 }
398 }
399 if (dropReason == DROP_REASON_NOT_DROPPED
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800400 && isStaleEvent(currentTime, typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800401 dropReason = DROP_REASON_STALE;
402 }
403 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
404 dropReason = DROP_REASON_BLOCKED;
405 }
406 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
407 break;
408 }
409
410 case EventEntry::TYPE_MOTION: {
411 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
412 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
413 dropReason = DROP_REASON_APP_SWITCH;
414 }
415 if (dropReason == DROP_REASON_NOT_DROPPED
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800416 && isStaleEvent(currentTime, typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417 dropReason = DROP_REASON_STALE;
418 }
419 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
420 dropReason = DROP_REASON_BLOCKED;
421 }
422 done = dispatchMotionLocked(currentTime, typedEntry,
423 &dropReason, nextWakeupTime);
424 break;
425 }
426
427 default:
428 ALOG_ASSERT(false);
429 break;
430 }
431
432 if (done) {
433 if (dropReason != DROP_REASON_NOT_DROPPED) {
434 dropInboundEventLocked(mPendingEvent, dropReason);
435 }
Michael Wright3a981722015-06-10 15:26:13 +0100436 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437
438 releasePendingEventLocked();
439 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
440 }
441}
442
443bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
444 bool needWake = mInboundQueue.isEmpty();
445 mInboundQueue.enqueueAtTail(entry);
446 traceInboundQueueLengthLocked();
447
448 switch (entry->type) {
449 case EventEntry::TYPE_KEY: {
450 // Optimize app switch latency.
451 // If the application takes too long to catch up then we drop all events preceding
452 // the app switch key.
453 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800454 if (isAppSwitchKeyEvent(keyEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
456 mAppSwitchSawKeyDown = true;
457 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
458 if (mAppSwitchSawKeyDown) {
459#if DEBUG_APP_SWITCH
460 ALOGD("App switch is pending!");
461#endif
462 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
463 mAppSwitchSawKeyDown = false;
464 needWake = true;
465 }
466 }
467 }
468 break;
469 }
470
471 case EventEntry::TYPE_MOTION: {
472 // Optimize case where the current application is unresponsive and the user
473 // decides to touch a window in a different application.
474 // If the application takes too long to catch up then we drop all events preceding
475 // the touch into the other window.
476 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
477 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
478 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
479 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Robert Carr740167f2018-10-11 19:03:41 -0700480 && mInputTargetWaitApplicationToken != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481 int32_t displayId = motionEntry->displayId;
482 int32_t x = int32_t(motionEntry->pointerCoords[0].
483 getAxisValue(AMOTION_EVENT_AXIS_X));
484 int32_t y = int32_t(motionEntry->pointerCoords[0].
485 getAxisValue(AMOTION_EVENT_AXIS_Y));
486 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700487 if (touchedWindowHandle != nullptr
Robert Carr740167f2018-10-11 19:03:41 -0700488 && touchedWindowHandle->getApplicationToken()
489 != mInputTargetWaitApplicationToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490 // User touched a different application than the one we are waiting on.
491 // Flag the event, and start pruning the input queue.
492 mNextUnblockedEvent = motionEntry;
493 needWake = true;
494 }
495 }
496 break;
497 }
498 }
499
500 return needWake;
501}
502
503void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
504 entry->refCount += 1;
505 mRecentQueue.enqueueAtTail(entry);
506 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
507 mRecentQueue.dequeueAtHead()->release();
508 }
509}
510
511sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800512 int32_t x, int32_t y, bool addOutsideTargets, bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800514 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
515 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516 const InputWindowInfo* windowInfo = windowHandle->getInfo();
517 if (windowInfo->displayId == displayId) {
518 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519
520 if (windowInfo->visible) {
521 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
522 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
523 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
524 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800525 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
526 if (portalToDisplayId != ADISPLAY_ID_NONE
527 && portalToDisplayId != displayId) {
528 if (addPortalWindows) {
529 // For the monitoring channels of the display.
530 mTempTouchState.addPortalWindow(windowHandle);
531 }
532 return findTouchedWindowAtLocked(
533 portalToDisplayId, x, y, addOutsideTargets, addPortalWindows);
534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535 // Found window.
536 return windowHandle;
537 }
538 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800539
540 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
541 mTempTouchState.addOrUpdateWindow(
542 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 }
546 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700547 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548}
549
Michael Wright3dd60e22019-03-27 22:06:44 +0000550std::vector<InputDispatcher::TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
551 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
552 std::vector<TouchedMonitor> touchedMonitors;
553
554 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
555 addGestureMonitors(monitors, touchedMonitors);
556 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
557 const InputWindowInfo* windowInfo = portalWindow->getInfo();
558 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
559 addGestureMonitors(monitors, touchedMonitors,
560 -windowInfo->frameLeft, -windowInfo->frameTop);
561 }
562 return touchedMonitors;
563}
564
565void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
566 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset, float yOffset) {
567 if (monitors.empty()) {
568 return;
569 }
570 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
571 for (const Monitor& monitor : monitors) {
572 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
573 }
574}
575
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
577 const char* reason;
578 switch (dropReason) {
579 case DROP_REASON_POLICY:
580#if DEBUG_INBOUND_EVENT_DETAILS
581 ALOGD("Dropped event because policy consumed it.");
582#endif
583 reason = "inbound event was dropped because the policy consumed it";
584 break;
585 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100586 if (mLastDropReason != DROP_REASON_DISABLED) {
587 ALOGI("Dropped event because input dispatch is disabled.");
588 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 reason = "inbound event was dropped because input dispatch is disabled";
590 break;
591 case DROP_REASON_APP_SWITCH:
592 ALOGI("Dropped event because of pending overdue app switch.");
593 reason = "inbound event was dropped because of pending overdue app switch";
594 break;
595 case DROP_REASON_BLOCKED:
596 ALOGI("Dropped event because the current application is not responding and the user "
597 "has started interacting with a different application.");
598 reason = "inbound event was dropped because the current application is not responding "
599 "and the user has started interacting with a different application";
600 break;
601 case DROP_REASON_STALE:
602 ALOGI("Dropped event because it is stale.");
603 reason = "inbound event was dropped because it is stale";
604 break;
605 default:
606 ALOG_ASSERT(false);
607 return;
608 }
609
610 switch (entry->type) {
611 case EventEntry::TYPE_KEY: {
612 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
613 synthesizeCancelationEventsForAllConnectionsLocked(options);
614 break;
615 }
616 case EventEntry::TYPE_MOTION: {
617 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
618 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
619 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
620 synthesizeCancelationEventsForAllConnectionsLocked(options);
621 } else {
622 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
623 synthesizeCancelationEventsForAllConnectionsLocked(options);
624 }
625 break;
626 }
627 }
628}
629
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800630static bool isAppSwitchKeyCode(int32_t keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631 return keyCode == AKEYCODE_HOME
632 || keyCode == AKEYCODE_ENDCALL
633 || keyCode == AKEYCODE_APP_SWITCH;
634}
635
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800636bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
638 && isAppSwitchKeyCode(keyEntry->keyCode)
639 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
640 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
641}
642
643bool InputDispatcher::isAppSwitchPendingLocked() {
644 return mAppSwitchDueTime != LONG_LONG_MAX;
645}
646
647void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
648 mAppSwitchDueTime = LONG_LONG_MAX;
649
650#if DEBUG_APP_SWITCH
651 if (handled) {
652 ALOGD("App switch has arrived.");
653 } else {
654 ALOGD("App switch was abandoned.");
655 }
656#endif
657}
658
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800659bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
661}
662
663bool InputDispatcher::haveCommandsLocked() const {
664 return !mCommandQueue.isEmpty();
665}
666
667bool InputDispatcher::runCommandsLockedInterruptible() {
668 if (mCommandQueue.isEmpty()) {
669 return false;
670 }
671
672 do {
673 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
674
675 Command command = commandEntry->command;
676 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
677
678 commandEntry->connection.clear();
679 delete commandEntry;
680 } while (! mCommandQueue.isEmpty());
681 return true;
682}
683
684InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
685 CommandEntry* commandEntry = new CommandEntry(command);
686 mCommandQueue.enqueueAtTail(commandEntry);
687 return commandEntry;
688}
689
690void InputDispatcher::drainInboundQueueLocked() {
691 while (! mInboundQueue.isEmpty()) {
692 EventEntry* entry = mInboundQueue.dequeueAtHead();
693 releaseInboundEventLocked(entry);
694 }
695 traceInboundQueueLengthLocked();
696}
697
698void InputDispatcher::releasePendingEventLocked() {
699 if (mPendingEvent) {
700 resetANRTimeoutsLocked();
701 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700702 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 }
704}
705
706void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
707 InjectionState* injectionState = entry->injectionState;
708 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
709#if DEBUG_DISPATCH_CYCLE
710 ALOGD("Injected inbound event was dropped.");
711#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800712 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800713 }
714 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700715 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800716 }
717 addRecentEventLocked(entry);
718 entry->release();
719}
720
721void InputDispatcher::resetKeyRepeatLocked() {
722 if (mKeyRepeatState.lastKeyEntry) {
723 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700724 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 }
726}
727
728InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
729 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
730
731 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700732 uint32_t policyFlags = entry->policyFlags &
733 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800734 if (entry->refCount == 1) {
735 entry->recycle();
736 entry->eventTime = currentTime;
737 entry->policyFlags = policyFlags;
738 entry->repeatCount += 1;
739 } else {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800740 KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100741 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 entry->action, entry->flags, entry->keyCode, entry->scanCode,
743 entry->metaState, entry->repeatCount + 1, entry->downTime);
744
745 mKeyRepeatState.lastKeyEntry = newEntry;
746 entry->release();
747
748 entry = newEntry;
749 }
750 entry->syntheticRepeat = true;
751
752 // Increment reference count since we keep a reference to the event in
753 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
754 entry->refCount += 1;
755
756 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
757 return entry;
758}
759
760bool InputDispatcher::dispatchConfigurationChangedLocked(
761 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
762#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700763 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764#endif
765
766 // Reset key repeating in case a keyboard device was added or removed or something.
767 resetKeyRepeatLocked();
768
769 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
770 CommandEntry* commandEntry = postCommandLocked(
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800771 & InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772 commandEntry->eventTime = entry->eventTime;
773 return true;
774}
775
776bool InputDispatcher::dispatchDeviceResetLocked(
777 nsecs_t currentTime, DeviceResetEntry* entry) {
778#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700779 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
780 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781#endif
782
783 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
784 "device was reset");
785 options.deviceId = entry->deviceId;
786 synthesizeCancelationEventsForAllConnectionsLocked(options);
787 return true;
788}
789
790bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
791 DropReason* dropReason, nsecs_t* nextWakeupTime) {
792 // Preprocessing.
793 if (! entry->dispatchInProgress) {
794 if (entry->repeatCount == 0
795 && entry->action == AKEY_EVENT_ACTION_DOWN
796 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
797 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
798 if (mKeyRepeatState.lastKeyEntry
799 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
800 // We have seen two identical key downs in a row which indicates that the device
801 // driver is automatically generating key repeats itself. We take note of the
802 // repeat here, but we disable our own next key repeat timer since it is clear that
803 // we will not need to synthesize key repeats ourselves.
804 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
805 resetKeyRepeatLocked();
806 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
807 } else {
808 // Not a repeat. Save key down state in case we do see a repeat later.
809 resetKeyRepeatLocked();
810 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
811 }
812 mKeyRepeatState.lastKeyEntry = entry;
813 entry->refCount += 1;
814 } else if (! entry->syntheticRepeat) {
815 resetKeyRepeatLocked();
816 }
817
818 if (entry->repeatCount == 1) {
819 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
820 } else {
821 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
822 }
823
824 entry->dispatchInProgress = true;
825
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800826 logOutboundKeyDetails("dispatchKey - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 }
828
829 // Handle case where the policy asked us to try again later last time.
830 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
831 if (currentTime < entry->interceptKeyWakeupTime) {
832 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
833 *nextWakeupTime = entry->interceptKeyWakeupTime;
834 }
835 return false; // wait until next wakeup
836 }
837 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
838 entry->interceptKeyWakeupTime = 0;
839 }
840
841 // Give the policy a chance to intercept the key.
842 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
843 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
844 CommandEntry* commandEntry = postCommandLocked(
845 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800846 sp<InputWindowHandle> focusedWindowHandle =
847 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
848 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700849 commandEntry->inputChannel =
850 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 }
852 commandEntry->keyEntry = entry;
853 entry->refCount += 1;
854 return false; // wait for the command to run
855 } else {
856 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
857 }
858 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
859 if (*dropReason == DROP_REASON_NOT_DROPPED) {
860 *dropReason = DROP_REASON_POLICY;
861 }
862 }
863
864 // Clean up if dropping the event.
865 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800866 setInjectionResult(entry, *dropReason == DROP_REASON_POLICY
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800868 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 return true;
870 }
871
872 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800873 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
875 entry, inputTargets, nextWakeupTime);
876 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
877 return false;
878 }
879
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800880 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
882 return true;
883 }
884
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800885 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000886 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887
888 // Dispatch the key.
889 dispatchEventLocked(currentTime, entry, inputTargets);
890 return true;
891}
892
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800893void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100895 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
896 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800897 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100899 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800901 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902#endif
903}
904
905bool InputDispatcher::dispatchMotionLocked(
906 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000907 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 // Preprocessing.
909 if (! entry->dispatchInProgress) {
910 entry->dispatchInProgress = true;
911
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800912 logOutboundMotionDetails("dispatchMotion - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913 }
914
915 // Clean up if dropping the event.
916 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800917 setInjectionResult(entry, *dropReason == DROP_REASON_POLICY
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
919 return true;
920 }
921
922 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
923
924 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800925 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926
927 bool conflictingPointerActions = false;
928 int32_t injectionResult;
929 if (isPointerEvent) {
930 // Pointer event. (eg. touchscreen)
931 injectionResult = findTouchedWindowTargetsLocked(currentTime,
932 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
933 } else {
934 // Non touch event. (eg. trackball)
935 injectionResult = findFocusedWindowTargetsLocked(currentTime,
936 entry, inputTargets, nextWakeupTime);
937 }
938 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
939 return false;
940 }
941
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800942 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100944 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
945 CancelationOptions::Mode mode(isPointerEvent ?
946 CancelationOptions::CANCEL_POINTER_EVENTS :
947 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
948 CancelationOptions options(mode, "input event injection failed");
949 synthesizeCancelationEventsForMonitorsLocked(options);
950 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951 return true;
952 }
953
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800954 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000955 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800957 if (isPointerEvent) {
958 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
959 if (stateIndex >= 0) {
960 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800961 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800962 // The event has gone through these portal windows, so we add monitoring targets of
963 // the corresponding displays as well.
964 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800965 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +0000966 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800967 -windowInfo->frameLeft, -windowInfo->frameTop);
968 }
969 }
970 }
971 }
972
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 // Dispatch the motion.
974 if (conflictingPointerActions) {
975 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
976 "conflicting pointer actions");
977 synthesizeCancelationEventsForAllConnectionsLocked(options);
978 }
979 dispatchEventLocked(currentTime, entry, inputTargets);
980 return true;
981}
982
983
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800984void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800985#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800986 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
987 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100988 "action=0x%x, actionButton=0x%x, flags=0x%x, "
989 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800990 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800992 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100993 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994 entry->metaState, entry->buttonState,
995 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800996 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997
998 for (uint32_t i = 0; i < entry->pointerCount; i++) {
999 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1000 "x=%f, y=%f, pressure=%f, size=%f, "
1001 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08001002 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 i, entry->pointerProperties[i].id,
1004 entry->pointerProperties[i].toolType,
1005 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1006 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1007 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1008 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1009 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1010 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1011 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1012 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08001013 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014 }
1015#endif
1016}
1017
1018void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001019 EventEntry* eventEntry, const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001020 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021#if DEBUG_DISPATCH_CYCLE
1022 ALOGD("dispatchEventToCurrentInputTargets");
1023#endif
1024
1025 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1026
1027 pokeUserActivityLocked(eventEntry);
1028
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001029 for (const InputTarget& inputTarget : inputTargets) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
1031 if (connectionIndex >= 0) {
1032 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1033 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1034 } else {
1035#if DEBUG_FOCUS
1036 ALOGD("Dropping event delivery to target with channel '%s' because it "
1037 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001038 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039#endif
1040 }
1041 }
1042}
1043
1044int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1045 const EventEntry* entry,
1046 const sp<InputApplicationHandle>& applicationHandle,
1047 const sp<InputWindowHandle>& windowHandle,
1048 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001049 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1051#if DEBUG_FOCUS
1052 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1053#endif
1054 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1055 mInputTargetWaitStartTime = currentTime;
1056 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1057 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001058 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 }
1060 } else {
1061 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1062#if DEBUG_FOCUS
1063 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001064 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 reason);
1066#endif
1067 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001068 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001070 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071 timeout = applicationHandle->getDispatchingTimeout(
1072 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1073 } else {
1074 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1075 }
1076
1077 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1078 mInputTargetWaitStartTime = currentTime;
1079 mInputTargetWaitTimeoutTime = currentTime + timeout;
1080 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001081 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001082
Yi Kong9b14ac62018-07-17 13:48:38 -07001083 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001084 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 }
Robert Carr740167f2018-10-11 19:03:41 -07001086 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1087 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 }
1089 }
1090 }
1091
1092 if (mInputTargetWaitTimeoutExpired) {
1093 return INPUT_EVENT_INJECTION_TIMED_OUT;
1094 }
1095
1096 if (currentTime >= mInputTargetWaitTimeoutTime) {
1097 onANRLocked(currentTime, applicationHandle, windowHandle,
1098 entry->eventTime, mInputTargetWaitStartTime, reason);
1099
1100 // Force poll loop to wake up immediately on next iteration once we get the
1101 // ANR response back from the policy.
1102 *nextWakeupTime = LONG_LONG_MIN;
1103 return INPUT_EVENT_INJECTION_PENDING;
1104 } else {
1105 // Force poll loop to wake up when timeout is due.
1106 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1107 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1108 }
1109 return INPUT_EVENT_INJECTION_PENDING;
1110 }
1111}
1112
Robert Carr803535b2018-08-02 16:38:15 -07001113void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1114 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1115 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1116 state.removeWindowByToken(token);
1117 }
1118}
1119
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1121 const sp<InputChannel>& inputChannel) {
1122 if (newTimeout > 0) {
1123 // Extend the timeout.
1124 mInputTargetWaitTimeoutTime = now() + newTimeout;
1125 } else {
1126 // Give up.
1127 mInputTargetWaitTimeoutExpired = true;
1128
1129 // Input state will not be realistic. Mark it out of sync.
1130 if (inputChannel.get()) {
1131 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1132 if (connectionIndex >= 0) {
1133 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001134 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001135
Robert Carr803535b2018-08-02 16:38:15 -07001136 if (token != nullptr) {
1137 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001138 }
1139
1140 if (connection->status == Connection::STATUS_NORMAL) {
1141 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1142 "application not responding");
1143 synthesizeCancelationEventsForConnectionLocked(connection, options);
1144 }
1145 }
1146 }
1147 }
1148}
1149
1150nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1151 nsecs_t currentTime) {
1152 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1153 return currentTime - mInputTargetWaitStartTime;
1154 }
1155 return 0;
1156}
1157
1158void InputDispatcher::resetANRTimeoutsLocked() {
1159#if DEBUG_FOCUS
1160 ALOGD("Resetting ANR timeouts.");
1161#endif
1162
1163 // Reset input target wait timeout.
1164 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001165 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166}
1167
Tiger Huang721e26f2018-07-24 22:26:19 +08001168/**
1169 * Get the display id that the given event should go to. If this event specifies a valid display id,
1170 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1171 * Focused display is the display that the user most recently interacted with.
1172 */
1173int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1174 int32_t displayId;
1175 switch (entry->type) {
1176 case EventEntry::TYPE_KEY: {
1177 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1178 displayId = typedEntry->displayId;
1179 break;
1180 }
1181 case EventEntry::TYPE_MOTION: {
1182 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1183 displayId = typedEntry->displayId;
1184 break;
1185 }
1186 default: {
1187 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1188 return ADISPLAY_ID_NONE;
1189 }
1190 }
1191 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1192}
1193
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001195 const EventEntry* entry, std::vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001197 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198
Tiger Huang721e26f2018-07-24 22:26:19 +08001199 int32_t displayId = getTargetDisplayId(entry);
1200 sp<InputWindowHandle> focusedWindowHandle =
1201 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1202 sp<InputApplicationHandle> focusedApplicationHandle =
1203 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1204
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 // If there is no currently focused window and no focused application
1206 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001207 if (focusedWindowHandle == nullptr) {
1208 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001210 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 "Waiting because no window has focus but there is a "
1212 "focused application that may eventually add a window "
1213 "when it finishes starting up.");
1214 goto Unresponsive;
1215 }
1216
Arthur Hung3b413f22018-10-26 18:05:34 +08001217 ALOGI("Dropping event because there is no focused window or focused application in display "
1218 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001219 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1220 goto Failed;
1221 }
1222
1223 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001224 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1226 goto Failed;
1227 }
1228
Jeff Brownffb49772014-10-10 19:01:34 -07001229 // Check whether the window is ready for more input.
1230 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001231 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001232 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001234 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 goto Unresponsive;
1236 }
1237
1238 // Success! Output targets.
1239 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001240 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1242 inputTargets);
1243
1244 // Done.
1245Failed:
1246Unresponsive:
1247 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001248 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249#if DEBUG_FOCUS
1250 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1251 "timeSpentWaitingForApplication=%0.1fms",
1252 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1253#endif
1254 return injectionResult;
1255}
1256
1257int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001258 const MotionEntry* entry, std::vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001260 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 enum InjectionPermission {
1262 INJECTION_PERMISSION_UNKNOWN,
1263 INJECTION_PERMISSION_GRANTED,
1264 INJECTION_PERMISSION_DENIED
1265 };
1266
Michael Wrightd02c5b62014-02-10 15:10:22 -08001267 // For security reasons, we defer updating the touch state until we are sure that
1268 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001269 int32_t displayId = entry->displayId;
1270 int32_t action = entry->action;
1271 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1272
1273 // Update the touch state as needed based on the properties of the touch event.
1274 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1275 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1276 sp<InputWindowHandle> newHoverWindowHandle;
1277
Jeff Brownf086ddb2014-02-11 14:28:48 -08001278 // Copy current touch state into mTempTouchState.
1279 // This state is always reset at the end of this function, so if we don't find state
1280 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001281 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001282 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1283 if (oldStateIndex >= 0) {
1284 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1285 mTempTouchState.copyFrom(*oldState);
1286 }
1287
1288 bool isSplit = mTempTouchState.split;
1289 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1290 && (mTempTouchState.deviceId != entry->deviceId
1291 || mTempTouchState.source != entry->source
1292 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1294 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1295 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1296 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1297 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1298 || isHoverAction);
1299 bool wrongDevice = false;
1300 if (newGesture) {
1301 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001302 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001304 ALOGD("Dropping event because a pointer for a different device is already down "
1305 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001307 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001308 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1309 switchedDevice = false;
1310 wrongDevice = true;
1311 goto Failed;
1312 }
1313 mTempTouchState.reset();
1314 mTempTouchState.down = down;
1315 mTempTouchState.deviceId = entry->deviceId;
1316 mTempTouchState.source = entry->source;
1317 mTempTouchState.displayId = displayId;
1318 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001319 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1320#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001321 ALOGI("Dropping move event because a pointer for a different device is already active "
1322 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001323#endif
1324 // TODO: test multiple simultaneous input streams.
1325 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1326 switchedDevice = false;
1327 wrongDevice = true;
1328 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001329 }
1330
1331 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1332 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1333
1334 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1335 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1336 getAxisValue(AMOTION_EVENT_AXIS_X));
1337 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1338 getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wright3dd60e22019-03-27 22:06:44 +00001339 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001340 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +00001341 displayId, x, y, isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
1342
1343 std::vector<TouchedMonitor> newGestureMonitors = isDown
1344 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1345 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001346
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001348 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001349 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1350 // New window supports splitting.
1351 isSplit = true;
1352 } else if (isSplit) {
1353 // New window does not support splitting but we have already split events.
1354 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001355 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001356 }
1357
1358 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001359 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001360 // Try to assign the pointer to the first foreground window we find, if there is one.
1361 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001362 }
1363
1364 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1365 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
1366 "(%d, %d) in display %" PRId32 ".", x, y, displayId);
1367 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1368 goto Failed;
1369 }
1370
1371 if (newTouchedWindowHandle != nullptr) {
1372 // Set target flags.
1373 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1374 if (isSplit) {
1375 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001377 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1378 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1379 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1380 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1381 }
1382
1383 // Update hover state.
1384 if (isHoverAction) {
1385 newHoverWindowHandle = newTouchedWindowHandle;
1386 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1387 newHoverWindowHandle = mLastHoverWindowHandle;
1388 }
1389
1390 // Update the temporary touch state.
1391 BitSet32 pointerIds;
1392 if (isSplit) {
1393 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1394 pointerIds.markBit(pointerId);
1395 }
1396 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 }
1398
Michael Wright3dd60e22019-03-27 22:06:44 +00001399 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 } else {
1401 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1402
1403 // If the pointer is not currently down, then ignore the event.
1404 if (! mTempTouchState.down) {
1405#if DEBUG_FOCUS
1406 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001407 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408#endif
1409 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1410 goto Failed;
1411 }
1412
1413 // Check whether touches should slip outside of the current foreground window.
1414 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1415 && entry->pointerCount == 1
1416 && mTempTouchState.isSlippery()) {
1417 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1418 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1419
1420 sp<InputWindowHandle> oldTouchedWindowHandle =
1421 mTempTouchState.getFirstForegroundWindowHandle();
1422 sp<InputWindowHandle> newTouchedWindowHandle =
1423 findTouchedWindowAtLocked(displayId, x, y);
1424 if (oldTouchedWindowHandle != newTouchedWindowHandle
Michael Wright3dd60e22019-03-27 22:06:44 +00001425 && oldTouchedWindowHandle != nullptr
Yi Kong9b14ac62018-07-17 13:48:38 -07001426 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001428 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001429 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001430 newTouchedWindowHandle->getName().c_str(),
1431 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001432#endif
1433 // Make a slippery exit from the old window.
1434 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1435 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1436
1437 // Make a slippery entrance into the new window.
1438 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1439 isSplit = true;
1440 }
1441
1442 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1443 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1444 if (isSplit) {
1445 targetFlags |= InputTarget::FLAG_SPLIT;
1446 }
1447 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1448 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1449 }
1450
1451 BitSet32 pointerIds;
1452 if (isSplit) {
1453 pointerIds.markBit(entry->pointerProperties[0].id);
1454 }
1455 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1456 }
1457 }
1458 }
1459
1460 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1461 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001462 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463#if DEBUG_HOVER
1464 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001465 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466#endif
1467 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1468 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1469 }
1470
1471 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001472 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001473#if DEBUG_HOVER
1474 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001475 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476#endif
1477 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1478 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1479 }
1480 }
1481
1482 // Check permission to inject into all touched foreground windows and ensure there
1483 // is at least one touched foreground window.
1484 {
1485 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001486 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1488 haveForegroundWindow = true;
1489 if (! checkInjectionPermission(touchedWindow.windowHandle,
1490 entry->injectionState)) {
1491 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1492 injectionPermission = INJECTION_PERMISSION_DENIED;
1493 goto Failed;
1494 }
1495 }
1496 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001497 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1498 if (!haveForegroundWindow && !hasGestureMonitor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499#if DEBUG_FOCUS
Michael Wright3dd60e22019-03-27 22:06:44 +00001500 ALOGD("Dropping event because there is no touched foreground window in display %"
1501 PRId32 " or gesture monitor to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502#endif
1503 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1504 goto Failed;
1505 }
1506
1507 // Permission granted to injection into all touched foreground windows.
1508 injectionPermission = INJECTION_PERMISSION_GRANTED;
1509 }
1510
1511 // Check whether windows listening for outside touches are owned by the same UID. If it is
1512 // set the policy flag that we will not reveal coordinate information to this window.
1513 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1514 sp<InputWindowHandle> foregroundWindowHandle =
1515 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001516 if (foregroundWindowHandle) {
1517 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1518 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1519 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1520 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1521 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1522 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1523 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001525 }
1526 }
1527 }
1528 }
1529
1530 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001531 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001533 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001534 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001535 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001536 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001538 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001539 goto Unresponsive;
1540 }
1541 }
1542 }
1543
1544 // If this is the first pointer going down and the touched window has a wallpaper
1545 // then also add the touched wallpaper windows so they are locked in for the duration
1546 // of the touch gesture.
1547 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1548 // engine only supports touch events. We would need to add a mechanism similar
1549 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1550 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1551 sp<InputWindowHandle> foregroundWindowHandle =
1552 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001553 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001554 const std::vector<sp<InputWindowHandle>> windowHandles =
1555 getWindowHandlesLocked(displayId);
1556 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 const InputWindowInfo* info = windowHandle->getInfo();
1558 if (info->displayId == displayId
1559 && windowHandle->getInfo()->layoutParamsType
1560 == InputWindowInfo::TYPE_WALLPAPER) {
1561 mTempTouchState.addOrUpdateWindow(windowHandle,
1562 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001563 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 | InputTarget::FLAG_DISPATCH_AS_IS,
1565 BitSet32(0));
1566 }
1567 }
1568 }
1569 }
1570
1571 // Success! Output targets.
1572 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1573
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001574 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1576 touchedWindow.pointerIds, inputTargets);
1577 }
1578
Michael Wright3dd60e22019-03-27 22:06:44 +00001579 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1580 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
1581 touchedMonitor.yOffset, inputTargets);
1582 }
1583
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 // Drop the outside or hover touch windows since we will not care about them
1585 // in the next iteration.
1586 mTempTouchState.filterNonAsIsTouchWindows();
1587
1588Failed:
1589 // Check injection permission once and for all.
1590 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001591 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 injectionPermission = INJECTION_PERMISSION_GRANTED;
1593 } else {
1594 injectionPermission = INJECTION_PERMISSION_DENIED;
1595 }
1596 }
1597
1598 // Update final pieces of touch state if the injector had permission.
1599 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1600 if (!wrongDevice) {
1601 if (switchedDevice) {
1602#if DEBUG_FOCUS
1603 ALOGD("Conflicting pointer actions: Switched to a different device.");
1604#endif
1605 *outConflictingPointerActions = true;
1606 }
1607
1608 if (isHoverAction) {
1609 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001610 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611#if DEBUG_FOCUS
1612 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1613#endif
1614 *outConflictingPointerActions = true;
1615 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001616 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001617 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1618 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001619 mTempTouchState.deviceId = entry->deviceId;
1620 mTempTouchState.source = entry->source;
1621 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622 }
1623 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1624 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1625 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001626 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1628 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001629 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630#if DEBUG_FOCUS
1631 ALOGD("Conflicting pointer actions: Down received while already down.");
1632#endif
1633 *outConflictingPointerActions = true;
1634 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001635 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1636 // One pointer went up.
1637 if (isSplit) {
1638 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1639 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1640
1641 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001642 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001643 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1644 touchedWindow.pointerIds.clearBit(pointerId);
1645 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001646 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 continue;
1648 }
1649 }
1650 i += 1;
1651 }
1652 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001653 }
1654
1655 // Save changes unless the action was scroll in which case the temporary touch
1656 // state was only valid for this one action.
1657 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1658 if (mTempTouchState.displayId >= 0) {
1659 if (oldStateIndex >= 0) {
1660 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1661 } else {
1662 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1663 }
1664 } else if (oldStateIndex >= 0) {
1665 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001667 }
1668
1669 // Update hover state.
1670 mLastHoverWindowHandle = newHoverWindowHandle;
1671 }
1672 } else {
1673#if DEBUG_FOCUS
1674 ALOGD("Not updating touch focus because injection was denied.");
1675#endif
1676 }
1677
1678Unresponsive:
1679 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1680 mTempTouchState.reset();
1681
1682 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001683 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001684#if DEBUG_FOCUS
1685 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1686 "timeSpentWaitingForApplication=%0.1fms",
1687 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1688#endif
1689 return injectionResult;
1690}
1691
1692void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001693 int32_t targetFlags, BitSet32 pointerIds, std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001694 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1695 if (inputChannel == nullptr) {
1696 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1697 return;
1698 }
1699
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001701 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001702 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001703 target.flags = targetFlags;
1704 target.xOffset = - windowInfo->frameLeft;
1705 target.yOffset = - windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001706 target.globalScaleFactor = windowInfo->globalScaleFactor;
1707 target.windowXScale = windowInfo->windowXScale;
1708 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001709 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001710 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711}
1712
Michael Wright3dd60e22019-03-27 22:06:44 +00001713void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
1714 int32_t displayId, float xOffset, float yOffset) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001715
Michael Wright3dd60e22019-03-27 22:06:44 +00001716 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1717 mGlobalMonitorsByDisplay.find(displayId);
1718
1719 if (it != mGlobalMonitorsByDisplay.end()) {
1720 const std::vector<Monitor>& monitors = it->second;
1721 for (const Monitor& monitor : monitors) {
1722 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001723 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 }
1725}
1726
Michael Wright3dd60e22019-03-27 22:06:44 +00001727void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor,
1728 float xOffset, float yOffset, std::vector<InputTarget>& inputTargets) {
1729 InputTarget target;
1730 target.inputChannel = monitor.inputChannel;
1731 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1732 target.xOffset = xOffset;
1733 target.yOffset = yOffset;
1734 target.pointerIds.clear();
1735 target.globalScaleFactor = 1.0f;
1736 inputTargets.push_back(target);
1737}
1738
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1740 const InjectionState* injectionState) {
1741 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001742 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1744 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001745 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1747 "owned by uid %d",
1748 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001749 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 windowHandle->getInfo()->ownerUid);
1751 } else {
1752 ALOGW("Permission denied: injecting event from pid %d uid %d",
1753 injectionState->injectorPid, injectionState->injectorUid);
1754 }
1755 return false;
1756 }
1757 return true;
1758}
1759
1760bool InputDispatcher::isWindowObscuredAtPointLocked(
1761 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1762 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001763 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1764 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765 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->frameContainsPoint(x, y)) {
1773 return true;
1774 }
1775 }
1776 return false;
1777}
1778
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001779
1780bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1781 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001782 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001783 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001784 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001785 if (otherHandle == windowHandle) {
1786 break;
1787 }
1788
1789 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1790 if (otherInfo->displayId == displayId
1791 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1792 && otherInfo->overlaps(windowInfo)) {
1793 return true;
1794 }
1795 }
1796 return false;
1797}
1798
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001799std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001800 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1801 const char* targetType) {
1802 // If the window is paused then keep waiting.
1803 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001804 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001805 }
1806
1807 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001808 ssize_t connectionIndex = getConnectionIndexLocked(
1809 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001810 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001811 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001812 "registered with the input dispatcher. The window may be in the process "
1813 "of being removed.", targetType);
1814 }
1815
1816 // If the connection is dead then keep waiting.
1817 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1818 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001819 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001820 "The window may be in the process of being removed.", targetType,
1821 connection->getStatusLabel());
1822 }
1823
1824 // If the connection is backed up then keep waiting.
1825 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001826 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001827 "Outbound queue length: %d. Wait queue length: %d.",
1828 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1829 }
1830
1831 // Ensure that the dispatch queues aren't too far backed up for this event.
1832 if (eventEntry->type == EventEntry::TYPE_KEY) {
1833 // If the event is a key event, then we must wait for all previous events to
1834 // complete before delivering it because previous events may have the
1835 // side-effect of transferring focus to a different window and we want to
1836 // ensure that the following keys are sent to the new window.
1837 //
1838 // Suppose the user touches a button in a window then immediately presses "A".
1839 // If the button causes a pop-up window to appear then we want to ensure that
1840 // the "A" key is delivered to the new pop-up window. This is because users
1841 // often anticipate pending UI changes when typing on a keyboard.
1842 // To obtain this behavior, we must serialize key events with respect to all
1843 // prior input events.
1844 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001845 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001846 "finished processing all of the input events that were previously "
1847 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1848 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 }
Jeff Brownffb49772014-10-10 19:01:34 -07001850 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001851 // Touch events can always be sent to a window immediately because the user intended
1852 // to touch whatever was visible at the time. Even if focus changes or a new
1853 // window appears moments later, the touch event was meant to be delivered to
1854 // whatever window happened to be on screen at the time.
1855 //
1856 // Generic motion events, such as trackball or joystick events are a little trickier.
1857 // Like key events, generic motion events are delivered to the focused window.
1858 // Unlike key events, generic motion events don't tend to transfer focus to other
1859 // windows and it is not important for them to be serialized. So we prefer to deliver
1860 // generic motion events as soon as possible to improve efficiency and reduce lag
1861 // through batching.
1862 //
1863 // The one case where we pause input event delivery is when the wait queue is piling
1864 // up with lots of events because the application is not responding.
1865 // This condition ensures that ANRs are detected reliably.
1866 if (!connection->waitQueue.isEmpty()
1867 && currentTime >= connection->waitQueue.head->deliveryTime
1868 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001869 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001870 "finished processing certain input events that were delivered to it over "
1871 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1872 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1873 connection->waitQueue.count(),
1874 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 }
1876 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001877 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001878}
1879
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001880std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 const sp<InputApplicationHandle>& applicationHandle,
1882 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001883 if (applicationHandle != nullptr) {
1884 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001885 std::string label(applicationHandle->getName());
1886 label += " - ";
1887 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 return label;
1889 } else {
1890 return applicationHandle->getName();
1891 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001892 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 return windowHandle->getName();
1894 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001895 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001896 }
1897}
1898
1899void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001900 int32_t displayId = getTargetDisplayId(eventEntry);
1901 sp<InputWindowHandle> focusedWindowHandle =
1902 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1903 if (focusedWindowHandle != nullptr) {
1904 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1906#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001907 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908#endif
1909 return;
1910 }
1911 }
1912
1913 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1914 switch (eventEntry->type) {
1915 case EventEntry::TYPE_MOTION: {
1916 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1917 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1918 return;
1919 }
1920
1921 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1922 eventType = USER_ACTIVITY_EVENT_TOUCH;
1923 }
1924 break;
1925 }
1926 case EventEntry::TYPE_KEY: {
1927 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1928 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1929 return;
1930 }
1931 eventType = USER_ACTIVITY_EVENT_BUTTON;
1932 break;
1933 }
1934 }
1935
1936 CommandEntry* commandEntry = postCommandLocked(
1937 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1938 commandEntry->eventTime = eventEntry->eventTime;
1939 commandEntry->userActivityEventType = eventType;
1940}
1941
1942void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1943 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001944 if (ATRACE_ENABLED()) {
1945 std::string message = StringPrintf(
1946 "prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
1947 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
1948 ATRACE_NAME(message.c_str());
1949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950#if DEBUG_DISPATCH_CYCLE
1951 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Robert Carre07e1032018-11-26 12:55:53 -08001952 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1953 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001954 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001956 inputTarget->globalScaleFactor,
1957 inputTarget->windowXScale, inputTarget->windowYScale,
1958 inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959#endif
1960
1961 // Skip this event if the connection status is not normal.
1962 // We don't want to enqueue additional outbound events if the connection is broken.
1963 if (connection->status != Connection::STATUS_NORMAL) {
1964#if DEBUG_DISPATCH_CYCLE
1965 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001966 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001967#endif
1968 return;
1969 }
1970
1971 // Split a motion event if needed.
1972 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1973 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1974
1975 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1976 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1977 MotionEntry* splitMotionEntry = splitMotionEvent(
1978 originalMotionEntry, inputTarget->pointerIds);
1979 if (!splitMotionEntry) {
1980 return; // split event was dropped
1981 }
1982#if DEBUG_FOCUS
1983 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001984 connection->getInputChannelName().c_str());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001985 logOutboundMotionDetails(" ", splitMotionEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001986#endif
1987 enqueueDispatchEntriesLocked(currentTime, connection,
1988 splitMotionEntry, inputTarget);
1989 splitMotionEntry->release();
1990 return;
1991 }
1992 }
1993
1994 // Not splitting. Enqueue dispatch entries for the event as is.
1995 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1996}
1997
1998void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1999 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002000 if (ATRACE_ENABLED()) {
2001 std::string message = StringPrintf(
2002 "enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
2003 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
2004 ATRACE_NAME(message.c_str());
2005 }
2006
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 bool wasEmpty = connection->outboundQueue.isEmpty();
2008
2009 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002010 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002012 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002014 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002016 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002018 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002020 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
2022
2023 // If the outbound queue was previously empty, start the dispatch cycle going.
2024 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
2025 startDispatchCycleLocked(currentTime, connection);
2026 }
2027}
2028
chaviw8c9cf542019-03-25 13:02:48 -07002029void InputDispatcher::enqueueDispatchEntryLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
2031 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002032 if (ATRACE_ENABLED()) {
2033 std::string message = StringPrintf(
2034 "enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2035 connection->getInputChannelName().c_str(),
2036 dispatchModeToString(dispatchMode).c_str());
2037 ATRACE_NAME(message.c_str());
2038 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 int32_t inputTargetFlags = inputTarget->flags;
2040 if (!(inputTargetFlags & dispatchMode)) {
2041 return;
2042 }
2043 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2044
2045 // This is a new event.
2046 // Enqueue a new dispatch entry onto the outbound queue for this connection.
2047 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
2048 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08002049 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2050 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051
2052 // Apply target flags and update the connection's input state.
2053 switch (eventEntry->type) {
2054 case EventEntry::TYPE_KEY: {
2055 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2056 dispatchEntry->resolvedAction = keyEntry->action;
2057 dispatchEntry->resolvedFlags = keyEntry->flags;
2058
2059 if (!connection->inputState.trackKey(keyEntry,
2060 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2061#if DEBUG_DISPATCH_CYCLE
2062 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002063 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064#endif
2065 delete dispatchEntry;
2066 return; // skip the inconsistent event
2067 }
2068 break;
2069 }
2070
2071 case EventEntry::TYPE_MOTION: {
2072 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2073 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2074 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2075 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2076 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2077 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2078 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2079 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2080 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2081 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2082 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2083 } else {
2084 dispatchEntry->resolvedAction = motionEntry->action;
2085 }
2086 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2087 && !connection->inputState.isHovering(
2088 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2089#if DEBUG_DISPATCH_CYCLE
2090 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002091 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092#endif
2093 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2094 }
2095
2096 dispatchEntry->resolvedFlags = motionEntry->flags;
2097 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2098 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2099 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002100 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2101 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2102 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103
2104 if (!connection->inputState.trackMotion(motionEntry,
2105 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2106#if DEBUG_DISPATCH_CYCLE
2107 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002108 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109#endif
2110 delete dispatchEntry;
2111 return; // skip the inconsistent event
2112 }
chaviw8c9cf542019-03-25 13:02:48 -07002113
chaviwfd6d3512019-03-25 13:23:49 -07002114 dispatchPointerDownOutsideFocus(motionEntry->source,
chaviw8c9cf542019-03-25 13:02:48 -07002115 dispatchEntry->resolvedAction, inputTarget->inputChannel->getToken());
2116
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 break;
2118 }
2119 }
2120
2121 // Remember that we are waiting for this dispatch to complete.
2122 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002123 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 }
2125
2126 // Enqueue the dispatch entry.
2127 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002128 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002129
2130}
2131
chaviwfd6d3512019-03-25 13:23:49 -07002132void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
chaviw8c9cf542019-03-25 13:02:48 -07002133 const sp<IBinder>& newToken) {
2134 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002135 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2136 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002137 return;
2138 }
2139
2140 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2141 if (inputWindowHandle == nullptr) {
2142 return;
2143 }
2144
chaviw8c9cf542019-03-25 13:02:48 -07002145 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002146 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002147
2148 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2149
2150 if (!hasFocusChanged) {
2151 return;
2152 }
2153
chaviwfd6d3512019-03-25 13:23:49 -07002154 CommandEntry* commandEntry = postCommandLocked(
2155 & InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
2156 commandEntry->newToken = newToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157}
2158
2159void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2160 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002161 if (ATRACE_ENABLED()) {
2162 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
2163 connection->getInputChannelName().c_str());
2164 ATRACE_NAME(message.c_str());
2165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002166#if DEBUG_DISPATCH_CYCLE
2167 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002168 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169#endif
2170
2171 while (connection->status == Connection::STATUS_NORMAL
2172 && !connection->outboundQueue.isEmpty()) {
2173 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2174 dispatchEntry->deliveryTime = currentTime;
2175
2176 // Publish the event.
2177 status_t status;
2178 EventEntry* eventEntry = dispatchEntry->eventEntry;
2179 switch (eventEntry->type) {
2180 case EventEntry::TYPE_KEY: {
2181 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2182
2183 // Publish the key event.
2184 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002185 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002186 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2187 keyEntry->keyCode, keyEntry->scanCode,
2188 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2189 keyEntry->eventTime);
2190 break;
2191 }
2192
2193 case EventEntry::TYPE_MOTION: {
2194 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2195
2196 PointerCoords scaledCoords[MAX_POINTERS];
2197 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2198
2199 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002200 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2202 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002203 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2204 float wxs = dispatchEntry->windowXScale;
2205 float wys = dispatchEntry->windowYScale;
2206 xOffset = dispatchEntry->xOffset * wxs;
2207 yOffset = dispatchEntry->yOffset * wys;
2208 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002209 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002211 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002212 }
2213 usingCoords = scaledCoords;
2214 }
2215 } else {
2216 xOffset = 0.0f;
2217 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218
2219 // We don't want the dispatch target to know.
2220 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002221 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 scaledCoords[i].clear();
2223 }
2224 usingCoords = scaledCoords;
2225 }
2226 }
2227
2228 // Publish the motion event.
2229 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002230 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002231 dispatchEntry->resolvedAction, motionEntry->actionButton,
2232 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002233 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification,
Michael Wright7b159c92015-05-14 14:48:03 +01002234 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002235 motionEntry->downTime, motionEntry->eventTime,
2236 motionEntry->pointerCount, motionEntry->pointerProperties,
2237 usingCoords);
2238 break;
2239 }
2240
2241 default:
2242 ALOG_ASSERT(false);
2243 return;
2244 }
2245
2246 // Check the result.
2247 if (status) {
2248 if (status == WOULD_BLOCK) {
2249 if (connection->waitQueue.isEmpty()) {
2250 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2251 "This is unexpected because the wait queue is empty, so the pipe "
2252 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002253 "event to it, status=%d", connection->getInputChannelName().c_str(),
2254 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2256 } else {
2257 // Pipe is full and we are waiting for the app to finish process some events
2258 // before sending more events to it.
2259#if DEBUG_DISPATCH_CYCLE
2260 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2261 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002262 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263#endif
2264 connection->inputPublisherBlocked = true;
2265 }
2266 } else {
2267 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002268 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2270 }
2271 return;
2272 }
2273
2274 // Re-enqueue the event on the wait queue.
2275 connection->outboundQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002276 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002277 connection->waitQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002278 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 }
2280}
2281
2282void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2283 const sp<Connection>& connection, uint32_t seq, bool handled) {
2284#if DEBUG_DISPATCH_CYCLE
2285 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002286 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287#endif
2288
2289 connection->inputPublisherBlocked = false;
2290
2291 if (connection->status == Connection::STATUS_BROKEN
2292 || connection->status == Connection::STATUS_ZOMBIE) {
2293 return;
2294 }
2295
2296 // Notify other system components and prepare to start the next dispatch cycle.
2297 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2298}
2299
2300void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2301 const sp<Connection>& connection, bool notify) {
2302#if DEBUG_DISPATCH_CYCLE
2303 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002304 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305#endif
2306
2307 // Clear the dispatch queues.
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002308 drainDispatchQueue(&connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002309 traceOutboundQueueLength(connection);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002310 drainDispatchQueue(&connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002311 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002312
2313 // The connection appears to be unrecoverably broken.
2314 // Ignore already broken or zombie connections.
2315 if (connection->status == Connection::STATUS_NORMAL) {
2316 connection->status = Connection::STATUS_BROKEN;
2317
2318 if (notify) {
2319 // Notify other system components.
2320 onDispatchCycleBrokenLocked(currentTime, connection);
2321 }
2322 }
2323}
2324
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002325void InputDispatcher::drainDispatchQueue(Queue<DispatchEntry>* queue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 while (!queue->isEmpty()) {
2327 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002328 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 }
2330}
2331
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002332void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002334 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 }
2336 delete dispatchEntry;
2337}
2338
2339int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2340 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2341
2342 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002343 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344
2345 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2346 if (connectionIndex < 0) {
2347 ALOGE("Received spurious receive callback for unknown input channel. "
2348 "fd=%d, events=0x%x", fd, events);
2349 return 0; // remove the callback
2350 }
2351
2352 bool notify;
2353 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2354 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2355 if (!(events & ALOOPER_EVENT_INPUT)) {
2356 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002357 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 return 1;
2359 }
2360
2361 nsecs_t currentTime = now();
2362 bool gotOne = false;
2363 status_t status;
2364 for (;;) {
2365 uint32_t seq;
2366 bool handled;
2367 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2368 if (status) {
2369 break;
2370 }
2371 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2372 gotOne = true;
2373 }
2374 if (gotOne) {
2375 d->runCommandsLockedInterruptible();
2376 if (status == WOULD_BLOCK) {
2377 return 1;
2378 }
2379 }
2380
2381 notify = status != DEAD_OBJECT || !connection->monitor;
2382 if (notify) {
2383 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002384 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385 }
2386 } else {
2387 // Monitor channels are never explicitly unregistered.
2388 // We do it automatically when the remote endpoint is closed so don't warn
2389 // about them.
2390 notify = !connection->monitor;
2391 if (notify) {
2392 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002393 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 }
2395 }
2396
2397 // Unregister the channel.
2398 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2399 return 0; // remove the callback
2400 } // release lock
2401}
2402
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002403void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked (
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 const CancelationOptions& options) {
2405 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2406 synthesizeCancelationEventsForConnectionLocked(
2407 mConnectionsByFd.valueAt(i), options);
2408 }
2409}
2410
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002411void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked (
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002412 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002413 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2414 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2415}
2416
2417void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2418 const CancelationOptions& options,
2419 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2420 for (const auto& it : monitorsByDisplay) {
2421 const std::vector<Monitor>& monitors = it.second;
2422 for (const Monitor& monitor : monitors) {
2423 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002424 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002425 }
2426}
2427
Michael Wrightd02c5b62014-02-10 15:10:22 -08002428void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2429 const sp<InputChannel>& channel, const CancelationOptions& options) {
2430 ssize_t index = getConnectionIndexLocked(channel);
2431 if (index >= 0) {
2432 synthesizeCancelationEventsForConnectionLocked(
2433 mConnectionsByFd.valueAt(index), options);
2434 }
2435}
2436
2437void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2438 const sp<Connection>& connection, const CancelationOptions& options) {
2439 if (connection->status == Connection::STATUS_BROKEN) {
2440 return;
2441 }
2442
2443 nsecs_t currentTime = now();
2444
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002445 std::vector<EventEntry*> cancelationEvents;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446 connection->inputState.synthesizeCancelationEvents(currentTime,
2447 cancelationEvents, options);
2448
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002449 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002450#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002451 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002453 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454 options.reason, options.mode);
2455#endif
2456 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002457 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 switch (cancelationEventEntry->type) {
2459 case EventEntry::TYPE_KEY:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002460 logOutboundKeyDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002461 static_cast<KeyEntry*>(cancelationEventEntry));
2462 break;
2463 case EventEntry::TYPE_MOTION:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002464 logOutboundMotionDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002465 static_cast<MotionEntry*>(cancelationEventEntry));
2466 break;
2467 }
2468
2469 InputTarget target;
chaviwfbe5d9c2018-12-26 12:23:37 -08002470 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(
2471 connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002472 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2474 target.xOffset = -windowInfo->frameLeft;
2475 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002476 target.globalScaleFactor = windowInfo->globalScaleFactor;
2477 target.windowXScale = windowInfo->windowXScale;
2478 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002479 } else {
2480 target.xOffset = 0;
2481 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002482 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
2484 target.inputChannel = connection->inputChannel;
2485 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2486
chaviw8c9cf542019-03-25 13:02:48 -07002487 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2489
2490 cancelationEventEntry->release();
2491 }
2492
2493 startDispatchCycleLocked(currentTime, connection);
2494 }
2495}
2496
2497InputDispatcher::MotionEntry*
2498InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2499 ALOG_ASSERT(pointerIds.value != 0);
2500
2501 uint32_t splitPointerIndexMap[MAX_POINTERS];
2502 PointerProperties splitPointerProperties[MAX_POINTERS];
2503 PointerCoords splitPointerCoords[MAX_POINTERS];
2504
2505 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2506 uint32_t splitPointerCount = 0;
2507
2508 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2509 originalPointerIndex++) {
2510 const PointerProperties& pointerProperties =
2511 originalMotionEntry->pointerProperties[originalPointerIndex];
2512 uint32_t pointerId = uint32_t(pointerProperties.id);
2513 if (pointerIds.hasBit(pointerId)) {
2514 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2515 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2516 splitPointerCoords[splitPointerCount].copyFrom(
2517 originalMotionEntry->pointerCoords[originalPointerIndex]);
2518 splitPointerCount += 1;
2519 }
2520 }
2521
2522 if (splitPointerCount != pointerIds.count()) {
2523 // This is bad. We are missing some of the pointers that we expected to deliver.
2524 // Most likely this indicates that we received an ACTION_MOVE events that has
2525 // different pointer ids than we expected based on the previous ACTION_DOWN
2526 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2527 // in this way.
2528 ALOGW("Dropping split motion event because the pointer count is %d but "
2529 "we expected there to be %d pointers. This probably means we received "
2530 "a broken sequence of pointer ids from the input device.",
2531 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002532 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002533 }
2534
2535 int32_t action = originalMotionEntry->action;
2536 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2537 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2538 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2539 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2540 const PointerProperties& pointerProperties =
2541 originalMotionEntry->pointerProperties[originalPointerIndex];
2542 uint32_t pointerId = uint32_t(pointerProperties.id);
2543 if (pointerIds.hasBit(pointerId)) {
2544 if (pointerIds.count() == 1) {
2545 // The first/last pointer went down/up.
2546 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2547 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2548 } else {
2549 // A secondary pointer went down/up.
2550 uint32_t splitPointerIndex = 0;
2551 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2552 splitPointerIndex += 1;
2553 }
2554 action = maskedAction | (splitPointerIndex
2555 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2556 }
2557 } else {
2558 // An unrelated pointer changed.
2559 action = AMOTION_EVENT_ACTION_MOVE;
2560 }
2561 }
2562
2563 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002564 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565 originalMotionEntry->eventTime,
2566 originalMotionEntry->deviceId,
2567 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002568 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 originalMotionEntry->policyFlags,
2570 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002571 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002572 originalMotionEntry->flags,
2573 originalMotionEntry->metaState,
2574 originalMotionEntry->buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002575 originalMotionEntry->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576 originalMotionEntry->edgeFlags,
2577 originalMotionEntry->xPrecision,
2578 originalMotionEntry->yPrecision,
2579 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002580 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581
2582 if (originalMotionEntry->injectionState) {
2583 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2584 splitMotionEntry->injectionState->refCount += 1;
2585 }
2586
2587 return splitMotionEntry;
2588}
2589
2590void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2591#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002592 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593#endif
2594
2595 bool needWake;
2596 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002597 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598
Prabir Pradhan42611e02018-11-27 14:04:02 -08002599 ConfigurationChangedEntry* newEntry =
2600 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 needWake = enqueueInboundEventLocked(newEntry);
2602 } // release lock
2603
2604 if (needWake) {
2605 mLooper->wake();
2606 }
2607}
2608
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002609/**
2610 * If one of the meta shortcuts is detected, process them here:
2611 * Meta + Backspace -> generate BACK
2612 * Meta + Enter -> generate HOME
2613 * This will potentially overwrite keyCode and metaState.
2614 */
2615void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2616 int32_t& keyCode, int32_t& metaState) {
2617 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2618 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2619 if (keyCode == AKEYCODE_DEL) {
2620 newKeyCode = AKEYCODE_BACK;
2621 } else if (keyCode == AKEYCODE_ENTER) {
2622 newKeyCode = AKEYCODE_HOME;
2623 }
2624 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002625 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002626 struct KeyReplacement replacement = {keyCode, deviceId};
2627 mReplacedKeys.add(replacement, newKeyCode);
2628 keyCode = newKeyCode;
2629 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2630 }
2631 } else if (action == AKEY_EVENT_ACTION_UP) {
2632 // In order to maintain a consistent stream of up and down events, check to see if the key
2633 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2634 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002635 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002636 struct KeyReplacement replacement = {keyCode, deviceId};
2637 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2638 if (index >= 0) {
2639 keyCode = mReplacedKeys.valueAt(index);
2640 mReplacedKeys.removeItemsAt(index);
2641 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2642 }
2643 }
2644}
2645
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2647#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002648 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002649 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002650 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002651 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002653 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654#endif
2655 if (!validateKeyEvent(args->action)) {
2656 return;
2657 }
2658
2659 uint32_t policyFlags = args->policyFlags;
2660 int32_t flags = args->flags;
2661 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002662 // InputDispatcher tracks and generates key repeats on behalf of
2663 // whatever notifies it, so repeatCount should always be set to 0
2664 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2666 policyFlags |= POLICY_FLAG_VIRTUAL;
2667 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2668 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 if (policyFlags & POLICY_FLAG_FUNCTION) {
2670 metaState |= AMETA_FUNCTION_ON;
2671 }
2672
2673 policyFlags |= POLICY_FLAG_TRUSTED;
2674
Michael Wright78f24442014-08-06 15:55:28 -07002675 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002676 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002677
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002679 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002680 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 args->downTime, args->eventTime);
2682
Michael Wright2b3c3302018-03-02 17:19:13 +00002683 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002685 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2686 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2687 std::to_string(t.duration().count()).c_str());
2688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 bool needWake;
2691 { // acquire lock
2692 mLock.lock();
2693
2694 if (shouldSendKeyToInputFilterLocked(args)) {
2695 mLock.unlock();
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
Prabir Pradhan42611e02018-11-27 14:04:02 -08002705 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002706 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002707 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 metaState, repeatCount, args->downTime);
2709
2710 needWake = enqueueInboundEventLocked(newEntry);
2711 mLock.unlock();
2712 } // release lock
2713
2714 if (needWake) {
2715 mLooper->wake();
2716 }
2717}
2718
2719bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2720 return mInputFilterEnabled;
2721}
2722
2723void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2724#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002725 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2726 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002727 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002728 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2729 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002730 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002731 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002732 for (uint32_t i = 0; i < args->pointerCount; i++) {
2733 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2734 "x=%f, y=%f, pressure=%f, size=%f, "
2735 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2736 "orientation=%f",
2737 i, args->pointerProperties[i].id,
2738 args->pointerProperties[i].toolType,
2739 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2740 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2741 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2742 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2743 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2744 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2745 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2746 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2747 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2748 }
2749#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002750 if (!validateMotionEvent(args->action, args->actionButton,
2751 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 return;
2753 }
2754
2755 uint32_t policyFlags = args->policyFlags;
2756 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002757
2758 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002759 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002760 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2761 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2762 std::to_string(t.duration().count()).c_str());
2763 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764
2765 bool needWake;
2766 { // acquire lock
2767 mLock.lock();
2768
2769 if (shouldSendMotionToInputFilterLocked(args)) {
2770 mLock.unlock();
2771
2772 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002773 event.initialize(args->deviceId, args->source, args->displayId,
2774 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002775 args->flags, args->edgeFlags, args->metaState, args->buttonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002776 args->classification, 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 args->downTime, args->eventTime,
2778 args->pointerCount, args->pointerProperties, args->pointerCoords);
2779
2780 policyFlags |= POLICY_FLAG_FILTERED;
2781 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2782 return; // event was consumed by the filter
2783 }
2784
2785 mLock.lock();
2786 }
2787
2788 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002789 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002790 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002791 args->action, args->actionButton, args->flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002792 args->metaState, args->buttonState, args->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002794 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795
2796 needWake = enqueueInboundEventLocked(newEntry);
2797 mLock.unlock();
2798 } // release lock
2799
2800 if (needWake) {
2801 mLooper->wake();
2802 }
2803}
2804
2805bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002806 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807}
2808
2809void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2810#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002811 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2812 "switchMask=0x%08x",
2813 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814#endif
2815
2816 uint32_t policyFlags = args->policyFlags;
2817 policyFlags |= POLICY_FLAG_TRUSTED;
2818 mPolicy->notifySwitch(args->eventTime,
2819 args->switchValues, args->switchMask, policyFlags);
2820}
2821
2822void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2823#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002824 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 args->eventTime, args->deviceId);
2826#endif
2827
2828 bool needWake;
2829 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002830 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831
Prabir Pradhan42611e02018-11-27 14:04:02 -08002832 DeviceResetEntry* newEntry =
2833 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 needWake = enqueueInboundEventLocked(newEntry);
2835 } // release lock
2836
2837 if (needWake) {
2838 mLooper->wake();
2839 }
2840}
2841
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002842int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2844 uint32_t policyFlags) {
2845#if DEBUG_INBOUND_EVENT_DETAILS
2846 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002847 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2848 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849#endif
2850
2851 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2852
2853 policyFlags |= POLICY_FLAG_INJECTED;
2854 if (hasInjectionPermission(injectorPid, injectorUid)) {
2855 policyFlags |= POLICY_FLAG_TRUSTED;
2856 }
2857
2858 EventEntry* firstInjectedEntry;
2859 EventEntry* lastInjectedEntry;
2860 switch (event->getType()) {
2861 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002862 KeyEvent keyEvent;
2863 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2864 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865 if (! validateKeyEvent(action)) {
2866 return INPUT_EVENT_INJECTION_FAILED;
2867 }
2868
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002869 int32_t flags = keyEvent.getFlags();
2870 int32_t keyCode = keyEvent.getKeyCode();
2871 int32_t metaState = keyEvent.getMetaState();
2872 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2873 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002874 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002875 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002876 keyEvent.getDownTime(), keyEvent.getEventTime());
2877
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2879 policyFlags |= POLICY_FLAG_VIRTUAL;
2880 }
2881
2882 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002883 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002884 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002885 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2886 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2887 std::to_string(t.duration().count()).c_str());
2888 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002889 }
2890
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002892 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002893 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002895 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2896 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897 lastInjectedEntry = firstInjectedEntry;
2898 break;
2899 }
2900
2901 case AINPUT_EVENT_TYPE_MOTION: {
2902 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903 int32_t action = motionEvent->getAction();
2904 size_t pointerCount = motionEvent->getPointerCount();
2905 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002906 int32_t actionButton = motionEvent->getActionButton();
Charles Chen3611f1f2019-01-29 17:26:18 +08002907 int32_t displayId = motionEvent->getDisplayId();
Michael Wright7b159c92015-05-14 14:48:03 +01002908 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909 return INPUT_EVENT_INJECTION_FAILED;
2910 }
2911
2912 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2913 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002914 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002915 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002916 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2917 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2918 std::to_string(t.duration().count()).c_str());
2919 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002920 }
2921
2922 mLock.lock();
2923 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2924 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002925 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002926 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2927 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002928 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002930 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002932 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002933 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2934 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002935 lastInjectedEntry = firstInjectedEntry;
2936 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2937 sampleEventTimes += 1;
2938 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002939 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2940 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002941 motionEvent->getDeviceId(), motionEvent->getSource(),
2942 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002943 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002945 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002946 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002947 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002948 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2949 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950 lastInjectedEntry->next = nextInjectedEntry;
2951 lastInjectedEntry = nextInjectedEntry;
2952 }
2953 break;
2954 }
2955
2956 default:
2957 ALOGW("Cannot inject event of type %d", event->getType());
2958 return INPUT_EVENT_INJECTION_FAILED;
2959 }
2960
2961 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2962 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2963 injectionState->injectionIsAsync = true;
2964 }
2965
2966 injectionState->refCount += 1;
2967 lastInjectedEntry->injectionState = injectionState;
2968
2969 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002970 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002971 EventEntry* nextEntry = entry->next;
2972 needWake |= enqueueInboundEventLocked(entry);
2973 entry = nextEntry;
2974 }
2975
2976 mLock.unlock();
2977
2978 if (needWake) {
2979 mLooper->wake();
2980 }
2981
2982 int32_t injectionResult;
2983 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002984 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002985
2986 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2987 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2988 } else {
2989 for (;;) {
2990 injectionResult = injectionState->injectionResult;
2991 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2992 break;
2993 }
2994
2995 nsecs_t remainingTimeout = endTime - now();
2996 if (remainingTimeout <= 0) {
2997#if DEBUG_INJECTION
2998 ALOGD("injectInputEvent - Timed out waiting for injection result "
2999 "to become available.");
3000#endif
3001 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3002 break;
3003 }
3004
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003005 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003006 }
3007
3008 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
3009 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
3010 while (injectionState->pendingForegroundDispatches != 0) {
3011#if DEBUG_INJECTION
3012 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
3013 injectionState->pendingForegroundDispatches);
3014#endif
3015 nsecs_t remainingTimeout = endTime - now();
3016 if (remainingTimeout <= 0) {
3017#if DEBUG_INJECTION
3018 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3019 "dispatches to finish.");
3020#endif
3021 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3022 break;
3023 }
3024
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003025 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003026 }
3027 }
3028 }
3029
3030 injectionState->release();
3031 } // release lock
3032
3033#if DEBUG_INJECTION
3034 ALOGD("injectInputEvent - Finished with result %d. "
3035 "injectorPid=%d, injectorUid=%d",
3036 injectionResult, injectorPid, injectorUid);
3037#endif
3038
3039 return injectionResult;
3040}
3041
3042bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3043 return injectorUid == 0
3044 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3045}
3046
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003047void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003048 InjectionState* injectionState = entry->injectionState;
3049 if (injectionState) {
3050#if DEBUG_INJECTION
3051 ALOGD("Setting input event injection result to %d. "
3052 "injectorPid=%d, injectorUid=%d",
3053 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
3054#endif
3055
3056 if (injectionState->injectionIsAsync
3057 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
3058 // Log the outcome since the injector did not wait for the injection result.
3059 switch (injectionResult) {
3060 case INPUT_EVENT_INJECTION_SUCCEEDED:
3061 ALOGV("Asynchronous input event injection succeeded.");
3062 break;
3063 case INPUT_EVENT_INJECTION_FAILED:
3064 ALOGW("Asynchronous input event injection failed.");
3065 break;
3066 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3067 ALOGW("Asynchronous input event injection permission denied.");
3068 break;
3069 case INPUT_EVENT_INJECTION_TIMED_OUT:
3070 ALOGW("Asynchronous input event injection timed out.");
3071 break;
3072 }
3073 }
3074
3075 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003076 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077 }
3078}
3079
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003080void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003081 InjectionState* injectionState = entry->injectionState;
3082 if (injectionState) {
3083 injectionState->pendingForegroundDispatches += 1;
3084 }
3085}
3086
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003087void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088 InjectionState* injectionState = entry->injectionState;
3089 if (injectionState) {
3090 injectionState->pendingForegroundDispatches -= 1;
3091
3092 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003093 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094 }
3095 }
3096}
3097
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003098std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3099 int32_t displayId) const {
3100 std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>::const_iterator it =
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003101 mWindowHandlesByDisplay.find(displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003102 if(it != mWindowHandlesByDisplay.end()) {
3103 return it->second;
3104 }
3105
3106 // Return an empty one if nothing found.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003107 return std::vector<sp<InputWindowHandle>>();
Arthur Hungb92218b2018-08-14 12:00:21 +08003108}
3109
Michael Wrightd02c5b62014-02-10 15:10:22 -08003110sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003111 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003112 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003113 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3114 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003115 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003116 return windowHandle;
3117 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118 }
3119 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003120 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003121}
3122
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003123bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003124 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003125 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3126 for (const sp<InputWindowHandle>& handle : windowHandles) {
3127 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003128 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003129 ALOGE("Found window %s in display %" PRId32
3130 ", but it should belong to display %" PRId32,
3131 windowHandle->getName().c_str(), it.first,
3132 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003133 }
3134 return true;
3135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136 }
3137 }
3138 return false;
3139}
3140
Robert Carr5c8a0262018-10-03 16:30:44 -07003141sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3142 size_t count = mInputChannelsByToken.count(token);
3143 if (count == 0) {
3144 return nullptr;
3145 }
3146 return mInputChannelsByToken.at(token);
3147}
3148
Arthur Hungb92218b2018-08-14 12:00:21 +08003149/**
3150 * Called from InputManagerService, update window handle list by displayId that can receive input.
3151 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3152 * If set an empty list, remove all handles from the specific display.
3153 * For focused handle, check if need to change and send a cancel event to previous one.
3154 * For removed handle, check if need to send a cancel event if already in touch.
3155 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003156void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
chaviw291d88a2019-02-14 10:33:58 -08003157 int32_t displayId, const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003159 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160#endif
3161 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003162 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163
Arthur Hungb92218b2018-08-14 12:00:21 +08003164 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003165 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3166 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003167
Tiger Huang721e26f2018-07-24 22:26:19 +08003168 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003170
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003171 if (inputWindowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003172 // Remove all handles on a display if there are no windows left.
3173 mWindowHandlesByDisplay.erase(displayId);
3174 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003175 // Since we compare the pointer of input window handles across window updates, we need
3176 // to make sure the handle object for the same window stays unchanged across updates.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003177 const std::vector<sp<InputWindowHandle>>& oldHandles =
3178 mWindowHandlesByDisplay[displayId];
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003179 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003180 for (const sp<InputWindowHandle>& handle : oldHandles) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003181 oldHandlesByTokens[handle->getToken()] = handle;
3182 }
3183
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003184 std::vector<sp<InputWindowHandle>> newHandles;
3185 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
Siarhei Vishniakou3a179dc2019-01-30 09:50:04 -08003186 if (!handle->updateInfo()) {
3187 // handle no longer valid
3188 continue;
3189 }
3190 const InputWindowInfo* info = handle->getInfo();
3191
3192 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3193 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3194 const bool noInputChannel =
3195 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3196 const bool canReceiveInput =
3197 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3198 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3199 if (canReceiveInput && !noInputChannel) {
3200 ALOGE("Window handle %s has no registered input channel",
3201 handle->getName().c_str());
3202 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003203 continue;
3204 }
3205
Siarhei Vishniakou3a179dc2019-01-30 09:50:04 -08003206 if (info->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003207 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Siarhei Vishniakou3a179dc2019-01-30 09:50:04 -08003208 handle->getName().c_str(), displayId, info->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003209 continue;
3210 }
3211
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003212 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3213 const sp<InputWindowHandle> oldHandle =
3214 oldHandlesByTokens.at(handle->getToken());
3215 oldHandle->updateFrom(handle);
3216 newHandles.push_back(oldHandle);
3217 } else {
3218 newHandles.push_back(handle);
3219 }
3220 }
3221
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003222 for (const sp<InputWindowHandle>& windowHandle : newHandles) {
Arthur Hung7ab76b12019-01-09 19:17:20 +08003223 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3224 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3225 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003226 newFocusedWindowHandle = windowHandle;
3227 }
3228 if (windowHandle == mLastHoverWindowHandle) {
3229 foundHoveredWindow = true;
3230 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003231 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003232
3233 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003234 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 }
3236
3237 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003238 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 }
3240
Tiger Huang721e26f2018-07-24 22:26:19 +08003241 sp<InputWindowHandle> oldFocusedWindowHandle =
3242 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3243
3244 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3245 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003247 ALOGD("Focus left window: %s in display %" PRId32,
3248 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003250 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3251 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003252 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3254 "focus left window");
3255 synthesizeCancelationEventsForInputChannelLocked(
3256 focusedInputChannel, options);
3257 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003258 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003260 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003262 ALOGD("Focus entered window: %s in display %" PRId32,
3263 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003265 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266 }
Robert Carrf759f162018-11-13 12:57:11 -08003267
3268 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003269 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003270 }
3271
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272 }
3273
Arthur Hungb92218b2018-08-14 12:00:21 +08003274 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3275 if (stateIndex >= 0) {
3276 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003277 for (size_t i = 0; i < state.windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003278 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003279 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003281 ALOGD("Touched window was removed: %s in display %" PRId32,
3282 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003284 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003285 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003286 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003287 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3288 "touched window was removed");
3289 synthesizeCancelationEventsForInputChannelLocked(
3290 touchedInputChannel, options);
3291 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003292 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003293 } else {
3294 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003295 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 }
3297 }
3298
3299 // Release information for windows that are no longer present.
3300 // This ensures that unused input channels are released promptly.
3301 // Otherwise, they might stick around until the window handle is destroyed
3302 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003303 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003304 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003306 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003308 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 }
3310 }
3311 } // release lock
3312
3313 // Wake up poll loop since it may need to make new input dispatching choices.
3314 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003315
3316 if (setInputWindowsListener) {
3317 setInputWindowsListener->onSetInputWindowsFinished();
3318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319}
3320
3321void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003322 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003324 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325#endif
3326 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003327 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328
Tiger Huang721e26f2018-07-24 22:26:19 +08003329 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3330 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003331 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003332 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3333 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003336 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003338 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003340 oldFocusedApplicationHandle.clear();
3341 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 }
3343
3344#if DEBUG_FOCUS
3345 //logDispatchStateLocked();
3346#endif
3347 } // release lock
3348
3349 // Wake up poll loop since it may need to make new input dispatching choices.
3350 mLooper->wake();
3351}
3352
Tiger Huang721e26f2018-07-24 22:26:19 +08003353/**
3354 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3355 * the display not specified.
3356 *
3357 * We track any unreleased events for each window. If a window loses the ability to receive the
3358 * released event, we will send a cancel event to it. So when the focused display is changed, we
3359 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3360 * display. The display-specified events won't be affected.
3361 */
3362void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3363#if DEBUG_FOCUS
3364 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3365#endif
3366 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003367 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003368
3369 if (mFocusedDisplayId != displayId) {
3370 sp<InputWindowHandle> oldFocusedWindowHandle =
3371 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3372 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003373 sp<InputChannel> inputChannel =
3374 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003375 if (inputChannel != nullptr) {
3376 CancelationOptions options(
Michael Wright3dd60e22019-03-27 22:06:44 +00003377 CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Tiger Huang721e26f2018-07-24 22:26:19 +08003378 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003379 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003380 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3381 }
3382 }
3383 mFocusedDisplayId = displayId;
3384
3385 // Sanity check
3386 sp<InputWindowHandle> newFocusedWindowHandle =
3387 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003388 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003389
Tiger Huang721e26f2018-07-24 22:26:19 +08003390 if (newFocusedWindowHandle == nullptr) {
3391 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3392 if (!mFocusedWindowHandlesByDisplay.empty()) {
3393 ALOGE("But another display has a focused window:");
3394 for (auto& it : mFocusedWindowHandlesByDisplay) {
3395 const int32_t displayId = it.first;
3396 const sp<InputWindowHandle>& windowHandle = it.second;
3397 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3398 displayId, windowHandle->getName().c_str());
3399 }
3400 }
3401 }
3402 }
3403
3404#if DEBUG_FOCUS
3405 logDispatchStateLocked();
3406#endif
3407 } // release lock
3408
3409 // Wake up poll loop since it may need to make new input dispatching choices.
3410 mLooper->wake();
3411}
3412
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3414#if DEBUG_FOCUS
3415 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3416#endif
3417
3418 bool changed;
3419 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003420 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421
3422 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3423 if (mDispatchFrozen && !frozen) {
3424 resetANRTimeoutsLocked();
3425 }
3426
3427 if (mDispatchEnabled && !enabled) {
3428 resetAndDropEverythingLocked("dispatcher is being disabled");
3429 }
3430
3431 mDispatchEnabled = enabled;
3432 mDispatchFrozen = frozen;
3433 changed = true;
3434 } else {
3435 changed = false;
3436 }
3437
3438#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003439 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440#endif
3441 } // release lock
3442
3443 if (changed) {
3444 // Wake up poll loop since it may need to make new input dispatching choices.
3445 mLooper->wake();
3446 }
3447}
3448
3449void InputDispatcher::setInputFilterEnabled(bool enabled) {
3450#if DEBUG_FOCUS
3451 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3452#endif
3453
3454 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003455 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456
3457 if (mInputFilterEnabled == enabled) {
3458 return;
3459 }
3460
3461 mInputFilterEnabled = enabled;
3462 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3463 } // release lock
3464
3465 // Wake up poll loop since there might be work to do to drop everything.
3466 mLooper->wake();
3467}
3468
chaviwfbe5d9c2018-12-26 12:23:37 -08003469bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3470 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003472 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003474 return true;
3475 }
3476
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003478 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479
chaviwfbe5d9c2018-12-26 12:23:37 -08003480 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3481 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003482 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003483 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484 return false;
3485 }
chaviw4f2dd402018-12-26 15:30:27 -08003486#if DEBUG_FOCUS
3487 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3488 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3489#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003490 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3491#if DEBUG_FOCUS
3492 ALOGD("Cannot transfer focus because windows are on different displays.");
3493#endif
3494 return false;
3495 }
3496
3497 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003498 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3499 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3500 for (size_t i = 0; i < state.windows.size(); i++) {
3501 const TouchedWindow& touchedWindow = state.windows[i];
3502 if (touchedWindow.windowHandle == fromWindowHandle) {
3503 int32_t oldTargetFlags = touchedWindow.targetFlags;
3504 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003505
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003506 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507
Jeff Brownf086ddb2014-02-11 14:28:48 -08003508 int32_t newTargetFlags = oldTargetFlags
3509 & (InputTarget::FLAG_FOREGROUND
3510 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3511 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512
Jeff Brownf086ddb2014-02-11 14:28:48 -08003513 found = true;
3514 goto Found;
3515 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516 }
3517 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003518Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519
3520 if (! found) {
3521#if DEBUG_FOCUS
3522 ALOGD("Focus transfer failed because from window did not have focus.");
3523#endif
3524 return false;
3525 }
3526
chaviwfbe5d9c2018-12-26 12:23:37 -08003527
3528 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3529 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3531 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3532 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3533 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3534 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3535
3536 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3537 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3538 "transferring touch focus from this window to another window");
3539 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3540 }
3541
3542#if DEBUG_FOCUS
3543 logDispatchStateLocked();
3544#endif
3545 } // release lock
3546
3547 // Wake up poll loop since it may need to make new input dispatching choices.
3548 mLooper->wake();
3549 return true;
3550}
3551
3552void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3553#if DEBUG_FOCUS
3554 ALOGD("Resetting and dropping all events (%s).", reason);
3555#endif
3556
3557 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3558 synthesizeCancelationEventsForAllConnectionsLocked(options);
3559
3560 resetKeyRepeatLocked();
3561 releasePendingEventLocked();
3562 drainInboundQueueLocked();
3563 resetANRTimeoutsLocked();
3564
Jeff Brownf086ddb2014-02-11 14:28:48 -08003565 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003567 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003568}
3569
3570void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003571 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 dumpDispatchStateLocked(dump);
3573
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003574 std::istringstream stream(dump);
3575 std::string line;
3576
3577 while (std::getline(stream, line, '\n')) {
3578 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003579 }
3580}
3581
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003582void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003583 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3584 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3585 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003586 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587
Tiger Huang721e26f2018-07-24 22:26:19 +08003588 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3589 dump += StringPrintf(INDENT "FocusedApplications:\n");
3590 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3591 const int32_t displayId = it.first;
3592 const sp<InputApplicationHandle>& applicationHandle = it.second;
3593 dump += StringPrintf(
3594 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3595 displayId,
3596 applicationHandle->getName().c_str(),
3597 applicationHandle->getDispatchingTimeout(
3598 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003601 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003603
3604 if (!mFocusedWindowHandlesByDisplay.empty()) {
3605 dump += StringPrintf(INDENT "FocusedWindows:\n");
3606 for (auto& it : mFocusedWindowHandlesByDisplay) {
3607 const int32_t displayId = it.first;
3608 const sp<InputWindowHandle>& windowHandle = it.second;
3609 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3610 displayId, windowHandle->getName().c_str());
3611 }
3612 } else {
3613 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615
Jeff Brownf086ddb2014-02-11 14:28:48 -08003616 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003617 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003618 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3619 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003620 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003621 state.displayId, toString(state.down), toString(state.split),
3622 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003623 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003624 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003625 for (size_t i = 0; i < state.windows.size(); i++) {
3626 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003627 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3628 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003629 touchedWindow.pointerIds.value,
3630 touchedWindow.targetFlags);
3631 }
3632 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003633 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003634 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003635 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003636 dump += INDENT3 "Portal windows:\n";
3637 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003638 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003639 dump += StringPrintf(INDENT4 "%zu: name='%s'\n",
3640 i, portalWindowHandle->getName().c_str());
3641 }
3642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 }
3644 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003645 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 }
3647
Arthur Hungb92218b2018-08-14 12:00:21 +08003648 if (!mWindowHandlesByDisplay.empty()) {
3649 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003650 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003651 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003652 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003653 dump += INDENT2 "Windows:\n";
3654 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003655 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003656 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657
Arthur Hungb92218b2018-08-14 12:00:21 +08003658 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003659 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, "
Arthur Hungb92218b2018-08-14 12:00:21 +08003660 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003661 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003662 "touchableRegion=",
3663 i, windowInfo->name.c_str(), windowInfo->displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003664 windowInfo->portalToDisplayId,
Arthur Hungb92218b2018-08-14 12:00:21 +08003665 toString(windowInfo->paused),
3666 toString(windowInfo->hasFocus),
3667 toString(windowInfo->hasWallpaper),
3668 toString(windowInfo->visible),
3669 toString(windowInfo->canReceiveKeys),
3670 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3671 windowInfo->layer,
3672 windowInfo->frameLeft, windowInfo->frameTop,
3673 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003674 windowInfo->globalScaleFactor,
3675 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003676 dumpRegion(dump, windowInfo->touchableRegion);
3677 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3678 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3679 windowInfo->ownerPid, windowInfo->ownerUid,
3680 windowInfo->dispatchingTimeout / 1000000.0);
3681 }
3682 } else {
3683 dump += INDENT2 "Windows: <none>\n";
3684 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003685 }
3686 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003687 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 }
3689
Michael Wright3dd60e22019-03-27 22:06:44 +00003690 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
3691 for (auto& it : mGlobalMonitorsByDisplay) {
3692 const std::vector<Monitor>& monitors = it.second;
3693 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3694 dumpMonitors(dump, monitors);
3695 }
3696 for (auto& it : mGestureMonitorsByDisplay) {
3697 const std::vector<Monitor>& monitors = it.second;
3698 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3699 dumpMonitors(dump, monitors);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003700 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003702 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 }
3704
3705 nsecs_t currentTime = now();
3706
3707 // Dump recently dispatched or dropped events from oldest to newest.
3708 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003709 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003711 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003713 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 (currentTime - entry->eventTime) * 0.000001f);
3715 }
3716 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003717 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 }
3719
3720 // Dump event currently being dispatched.
3721 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003722 dump += INDENT "PendingEvent:\n";
3723 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003725 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3727 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003728 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 }
3730
3731 // Dump inbound events from oldest to newest.
3732 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003733 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003735 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003737 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003738 (currentTime - entry->eventTime) * 0.000001f);
3739 }
3740 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003741 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 }
3743
Michael Wright78f24442014-08-06 15:55:28 -07003744 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003745 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003746 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3747 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3748 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003749 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003750 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3751 }
3752 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003753 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003754 }
3755
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003757 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3759 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003760 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003762 i, connection->getInputChannelName().c_str(),
3763 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 connection->getStatusLabel(), toString(connection->monitor),
3765 toString(connection->inputPublisherBlocked));
3766
3767 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003768 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 connection->outboundQueue.count());
3770 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3771 entry = entry->next) {
3772 dump.append(INDENT4);
3773 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003774 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003775 entry->targetFlags, entry->resolvedAction,
3776 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3777 }
3778 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003779 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003780 }
3781
3782 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003783 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 connection->waitQueue.count());
3785 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3786 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003787 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003789 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 "age=%0.1fms, wait=%0.1fms\n",
3791 entry->targetFlags, entry->resolvedAction,
3792 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3793 (currentTime - entry->deliveryTime) * 0.000001f);
3794 }
3795 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003796 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003797 }
3798 }
3799 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003800 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003801 }
3802
3803 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003804 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 (mAppSwitchDueTime - now()) / 1000000.0);
3806 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003807 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003808 }
3809
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003810 dump += INDENT "Configuration:\n";
3811 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003813 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 mConfig.keyRepeatTimeout * 0.000001f);
3815}
3816
Michael Wright3dd60e22019-03-27 22:06:44 +00003817void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3818 const size_t numMonitors = monitors.size();
3819 for (size_t i = 0; i < numMonitors; i++) {
3820 const Monitor& monitor = monitors[i];
3821 const sp<InputChannel>& channel = monitor.inputChannel;
3822 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3823 dump += "\n";
3824 }
3825}
3826
3827status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3828 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003830 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3831 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003832#endif
3833
3834 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003835 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003836
3837 if (getConnectionIndexLocked(inputChannel) >= 0) {
3838 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003839 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003840 return BAD_VALUE;
3841 }
3842
Michael Wright3dd60e22019-03-27 22:06:44 +00003843 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844
3845 int fd = inputChannel->getFd();
3846 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003847 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848
Michael Wrightd02c5b62014-02-10 15:10:22 -08003849 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3850 } // release lock
3851
3852 // Wake the looper because some connections have changed.
3853 mLooper->wake();
3854 return OK;
3855}
3856
Michael Wright3dd60e22019-03-27 22:06:44 +00003857status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
3858 int32_t displayId, bool isGestureMonitor) {
3859 { // acquire lock
3860 std::scoped_lock _l(mLock);
3861
3862 if (displayId < 0) {
3863 ALOGW("Attempted to register input monitor without a specified display.");
3864 return BAD_VALUE;
3865 }
3866
3867 if (inputChannel->getToken() == nullptr) {
3868 ALOGW("Attempted to register input monitor without an identifying token.");
3869 return BAD_VALUE;
3870 }
3871
3872 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3873
3874 const int fd = inputChannel->getFd();
3875 mConnectionsByFd.add(fd, connection);
3876 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
3877
3878 auto& monitorsByDisplay = isGestureMonitor
3879 ? mGestureMonitorsByDisplay
3880 : mGlobalMonitorsByDisplay;
3881 monitorsByDisplay[displayId].emplace_back(inputChannel);
3882
3883 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3884
3885 }
3886 // Wake the looper because some connections have changed.
3887 mLooper->wake();
3888 return OK;
3889}
3890
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3892#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003893 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894#endif
3895
3896 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003897 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898
3899 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3900 if (status) {
3901 return status;
3902 }
3903 } // release lock
3904
3905 // Wake the poll loop because removing the connection may have changed the current
3906 // synchronization state.
3907 mLooper->wake();
3908 return OK;
3909}
3910
3911status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3912 bool notify) {
3913 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3914 if (connectionIndex < 0) {
3915 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003916 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003917 return BAD_VALUE;
3918 }
3919
3920 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3921 mConnectionsByFd.removeItemsAt(connectionIndex);
3922
Robert Carr5c8a0262018-10-03 16:30:44 -07003923 mInputChannelsByToken.erase(inputChannel->getToken());
3924
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 if (connection->monitor) {
3926 removeMonitorChannelLocked(inputChannel);
3927 }
3928
3929 mLooper->removeFd(inputChannel->getFd());
3930
3931 nsecs_t currentTime = now();
3932 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3933
3934 connection->status = Connection::STATUS_ZOMBIE;
3935 return OK;
3936}
3937
3938void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003939 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
3940 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
3941}
3942
3943void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel,
3944 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3945 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end(); ) {
3946 std::vector<Monitor>& monitors = it->second;
3947 const size_t numMonitors = monitors.size();
3948 for (size_t i = 0; i < numMonitors; i++) {
3949 if (monitors[i].inputChannel == inputChannel) {
3950 monitors.erase(monitors.begin() + i);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003951 break;
3952 }
3953 }
Michael Wright3dd60e22019-03-27 22:06:44 +00003954 if (monitors.empty()) {
3955 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003956 } else {
3957 ++it;
3958 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959 }
3960}
3961
Michael Wright3dd60e22019-03-27 22:06:44 +00003962status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
3963 { // acquire lock
3964 std::scoped_lock _l(mLock);
3965 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
3966
3967 if (!foundDisplayId) {
3968 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
3969 return BAD_VALUE;
3970 }
3971 int32_t displayId = foundDisplayId.value();
3972
3973 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3974 if (stateIndex < 0) {
3975 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
3976 return BAD_VALUE;
3977 }
3978
3979 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
3980 std::optional<int32_t> foundDeviceId;
3981 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
3982 if (touchedMonitor.monitor.inputChannel->getToken() == token) {
3983 foundDeviceId = state.deviceId;
3984 }
3985 }
3986 if (!foundDeviceId || !state.down) {
3987 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
3988 " Ignoring.");
3989 return BAD_VALUE;
3990 }
3991 int32_t deviceId = foundDeviceId.value();
3992
3993 // Send cancel events to all the input channels we're stealing from.
3994 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3995 "gesture monitor stole pointer stream");
3996 options.deviceId = deviceId;
3997 options.displayId = displayId;
3998 for (const TouchedWindow& window : state.windows) {
3999 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
4000 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4001 }
4002 // Then clear the current touch state so we stop dispatching to them as well.
4003 state.filterNonMonitors();
4004 }
4005 return OK;
4006}
4007
4008
4009std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4010 const sp<IBinder>& token) {
4011 for (const auto& it : mGestureMonitorsByDisplay) {
4012 const std::vector<Monitor>& monitors = it.second;
4013 for (const Monitor& monitor : monitors) {
4014 if (monitor.inputChannel->getToken() == token) {
4015 return it.first;
4016 }
4017 }
4018 }
4019 return std::nullopt;
4020}
4021
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07004023 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08004024 return -1;
4025 }
4026
Robert Carr4e670e52018-08-15 13:26:12 -07004027 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
4028 sp<Connection> connection = mConnectionsByFd.valueAt(i);
4029 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
4030 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004031 }
4032 }
Robert Carr4e670e52018-08-15 13:26:12 -07004033
Michael Wrightd02c5b62014-02-10 15:10:22 -08004034 return -1;
4035}
4036
4037void InputDispatcher::onDispatchCycleFinishedLocked(
4038 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
4039 CommandEntry* commandEntry = postCommandLocked(
4040 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
4041 commandEntry->connection = connection;
4042 commandEntry->eventTime = currentTime;
4043 commandEntry->seq = seq;
4044 commandEntry->handled = handled;
4045}
4046
4047void InputDispatcher::onDispatchCycleBrokenLocked(
4048 nsecs_t currentTime, const sp<Connection>& connection) {
4049 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004050 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051
4052 CommandEntry* commandEntry = postCommandLocked(
4053 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
4054 commandEntry->connection = connection;
4055}
4056
chaviw0c06c6e2019-01-09 13:27:07 -08004057void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
4058 const sp<InputWindowHandle>& newFocus) {
4059 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4060 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08004061 CommandEntry* commandEntry = postCommandLocked(
4062 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004063 commandEntry->oldToken = oldToken;
4064 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004065}
4066
Michael Wrightd02c5b62014-02-10 15:10:22 -08004067void InputDispatcher::onANRLocked(
4068 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
4069 const sp<InputWindowHandle>& windowHandle,
4070 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
4071 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4072 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4073 ALOGI("Application is not responding: %s. "
4074 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004075 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004076 dispatchLatency, waitDuration, reason);
4077
4078 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004079 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080 struct tm tm;
4081 localtime_r(&t, &tm);
4082 char timestr[64];
4083 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4084 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004085 mLastANRState += INDENT "ANR:\n";
4086 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4087 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004088 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004089 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4090 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4091 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092 dumpDispatchStateLocked(mLastANRState);
4093
4094 CommandEntry* commandEntry = postCommandLocked(
4095 & InputDispatcher::doNotifyANRLockedInterruptible);
4096 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07004097 commandEntry->inputChannel = windowHandle != nullptr ?
4098 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099 commandEntry->reason = reason;
4100}
4101
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004102void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible (
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 CommandEntry* commandEntry) {
4104 mLock.unlock();
4105
4106 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4107
4108 mLock.lock();
4109}
4110
4111void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
4112 CommandEntry* commandEntry) {
4113 sp<Connection> connection = commandEntry->connection;
4114
4115 if (connection->status != Connection::STATUS_ZOMBIE) {
4116 mLock.unlock();
4117
Robert Carr803535b2018-08-02 16:38:15 -07004118 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119
4120 mLock.lock();
4121 }
4122}
4123
Robert Carrf759f162018-11-13 12:57:11 -08004124void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
4125 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004126 sp<IBinder> oldToken = commandEntry->oldToken;
4127 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004128 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004129 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004130 mLock.lock();
4131}
4132
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133void InputDispatcher::doNotifyANRLockedInterruptible(
4134 CommandEntry* commandEntry) {
4135 mLock.unlock();
4136
4137 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07004138 commandEntry->inputApplicationHandle,
4139 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004140 commandEntry->reason);
4141
4142 mLock.lock();
4143
4144 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07004145 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146}
4147
4148void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4149 CommandEntry* commandEntry) {
4150 KeyEntry* entry = commandEntry->keyEntry;
4151
4152 KeyEvent event;
4153 initializeKeyEvent(&event, entry);
4154
4155 mLock.unlock();
4156
Michael Wright2b3c3302018-03-02 17:19:13 +00004157 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07004158 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
4159 commandEntry->inputChannel->getToken() : nullptr;
4160 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004162 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4163 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
4164 std::to_string(t.duration().count()).c_str());
4165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166
4167 mLock.lock();
4168
4169 if (delay < 0) {
4170 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4171 } else if (!delay) {
4172 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4173 } else {
4174 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4175 entry->interceptKeyWakeupTime = now() + delay;
4176 }
4177 entry->release();
4178}
4179
chaviwfd6d3512019-03-25 13:23:49 -07004180void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4181 mLock.unlock();
4182 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4183 mLock.lock();
4184}
4185
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
4187 CommandEntry* commandEntry) {
4188 sp<Connection> connection = commandEntry->connection;
4189 nsecs_t finishTime = commandEntry->eventTime;
4190 uint32_t seq = commandEntry->seq;
4191 bool handled = commandEntry->handled;
4192
4193 // Handle post-event policy actions.
4194 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4195 if (dispatchEntry) {
4196 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4197 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004198 std::string msg =
4199 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004200 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004202 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 }
4204
4205 bool restartEvent;
4206 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4207 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4208 restartEvent = afterKeyEventLockedInterruptible(connection,
4209 dispatchEntry, keyEntry, handled);
4210 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4211 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4212 restartEvent = afterMotionEventLockedInterruptible(connection,
4213 dispatchEntry, motionEntry, handled);
4214 } else {
4215 restartEvent = false;
4216 }
4217
4218 // Dequeue the event and start the next cycle.
4219 // Note that because the lock might have been released, it is possible that the
4220 // contents of the wait queue to have been drained, so we need to double-check
4221 // a few things.
4222 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4223 connection->waitQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004224 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4226 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004227 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 } else {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08004229 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230 }
4231 }
4232
4233 // Start the next dispatch cycle for this connection.
4234 startDispatchCycleLocked(now(), connection);
4235 }
4236}
4237
4238bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4239 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004240 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004241 if (!handled) {
4242 // Report the key as unhandled, since the fallback was not handled.
4243 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4244 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004245 return false;
4246 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004248 // Get the fallback key state.
4249 // Clear it out after dispatching the UP.
4250 int32_t originalKeyCode = keyEntry->keyCode;
4251 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4252 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4253 connection->inputState.removeFallbackKey(originalKeyCode);
4254 }
4255
4256 if (handled || !dispatchEntry->hasForegroundTarget()) {
4257 // If the application handles the original key for which we previously
4258 // generated a fallback or if the window is not a foreground window,
4259 // then cancel the associated fallback key, if any.
4260 if (fallbackKeyCode != -1) {
4261 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004263 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4265 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4266 keyEntry->policyFlags);
4267#endif
4268 KeyEvent event;
4269 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004270 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271
4272 mLock.unlock();
4273
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004274 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4275 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004276
4277 mLock.lock();
4278
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004279 // Cancel the fallback key.
4280 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004282 "application handled the original non-fallback key "
4283 "or is no longer a foreground target, "
4284 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 options.keyCode = fallbackKeyCode;
4286 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004288 connection->inputState.removeFallbackKey(originalKeyCode);
4289 }
4290 } else {
4291 // If the application did not handle a non-fallback key, first check
4292 // that we are in a good state to perform unhandled key event processing
4293 // Then ask the policy what to do with it.
4294 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4295 && keyEntry->repeatCount == 0;
4296 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004298 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4299 "since this is not an initial down. "
4300 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4301 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4302 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004304 return false;
4305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004307 // Dispatch the unhandled key to the policy.
4308#if DEBUG_OUTBOUND_EVENT_DETAILS
4309 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4310 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4311 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4312 keyEntry->policyFlags);
4313#endif
4314 KeyEvent event;
4315 initializeKeyEvent(&event, keyEntry);
4316
4317 mLock.unlock();
4318
4319 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4320 &event, keyEntry->policyFlags, &event);
4321
4322 mLock.lock();
4323
4324 if (connection->status != Connection::STATUS_NORMAL) {
4325 connection->inputState.removeFallbackKey(originalKeyCode);
4326 return false;
4327 }
4328
4329 // Latch the fallback keycode for this key on an initial down.
4330 // The fallback keycode cannot change at any other point in the lifecycle.
4331 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004333 fallbackKeyCode = event.getKeyCode();
4334 } else {
4335 fallbackKeyCode = AKEYCODE_UNKNOWN;
4336 }
4337 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4338 }
4339
4340 ALOG_ASSERT(fallbackKeyCode != -1);
4341
4342 // Cancel the fallback key if the policy decides not to send it anymore.
4343 // We will continue to dispatch the key to the policy but we will no
4344 // longer dispatch a fallback key to the application.
4345 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4346 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4347#if DEBUG_OUTBOUND_EVENT_DETAILS
4348 if (fallback) {
4349 ALOGD("Unhandled key event: Policy requested to send key %d"
4350 "as a fallback for %d, but on the DOWN it had requested "
4351 "to send %d instead. Fallback canceled.",
4352 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4353 } else {
4354 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4355 "but on the DOWN it had requested to send %d. "
4356 "Fallback canceled.",
4357 originalKeyCode, fallbackKeyCode);
4358 }
4359#endif
4360
4361 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4362 "canceling fallback, policy no longer desires it");
4363 options.keyCode = fallbackKeyCode;
4364 synthesizeCancelationEventsForConnectionLocked(connection, options);
4365
4366 fallback = false;
4367 fallbackKeyCode = AKEYCODE_UNKNOWN;
4368 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4369 connection->inputState.setFallbackKey(originalKeyCode,
4370 fallbackKeyCode);
4371 }
4372 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373
4374#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004375 {
4376 std::string msg;
4377 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4378 connection->inputState.getFallbackKeys();
4379 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4380 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4381 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004383 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4384 fallbackKeys.size(), msg.c_str());
4385 }
4386#endif
4387
4388 if (fallback) {
4389 // Restart the dispatch cycle using the fallback key.
4390 keyEntry->eventTime = event.getEventTime();
4391 keyEntry->deviceId = event.getDeviceId();
4392 keyEntry->source = event.getSource();
4393 keyEntry->displayId = event.getDisplayId();
4394 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4395 keyEntry->keyCode = fallbackKeyCode;
4396 keyEntry->scanCode = event.getScanCode();
4397 keyEntry->metaState = event.getMetaState();
4398 keyEntry->repeatCount = event.getRepeatCount();
4399 keyEntry->downTime = event.getDownTime();
4400 keyEntry->syntheticRepeat = false;
4401
4402#if DEBUG_OUTBOUND_EVENT_DETAILS
4403 ALOGD("Unhandled key event: Dispatching fallback key. "
4404 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4405 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4406#endif
4407 return true; // restart the event
4408 } else {
4409#if DEBUG_OUTBOUND_EVENT_DETAILS
4410 ALOGD("Unhandled key event: No fallback key.");
4411#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004412
4413 // Report the key as unhandled, since there is no fallback key.
4414 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415 }
4416 }
4417 return false;
4418}
4419
4420bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4421 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4422 return false;
4423}
4424
4425void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4426 mLock.unlock();
4427
4428 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4429
4430 mLock.lock();
4431}
4432
4433void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004434 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004435 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4436 entry->downTime, entry->eventTime);
4437}
4438
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004439void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004440 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4441 // TODO Write some statistics about how long we spend waiting.
4442}
4443
4444void InputDispatcher::traceInboundQueueLengthLocked() {
4445 if (ATRACE_ENABLED()) {
4446 ATRACE_INT("iq", mInboundQueue.count());
4447 }
4448}
4449
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004450void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004451 if (ATRACE_ENABLED()) {
4452 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004453 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004454 ATRACE_INT(counterName, connection->outboundQueue.count());
4455 }
4456}
4457
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004458void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004459 if (ATRACE_ENABLED()) {
4460 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004461 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462 ATRACE_INT(counterName, connection->waitQueue.count());
4463 }
4464}
4465
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004466void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004467 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004469 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 dumpDispatchStateLocked(dump);
4471
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004472 if (!mLastANRState.empty()) {
4473 dump += "\nInput Dispatcher State at time of last ANR:\n";
4474 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 }
4476}
4477
4478void InputDispatcher::monitor() {
4479 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004480 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004482 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483}
4484
4485
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486// --- InputDispatcher::InjectionState ---
4487
4488InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4489 refCount(1),
4490 injectorPid(injectorPid), injectorUid(injectorUid),
4491 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4492 pendingForegroundDispatches(0) {
4493}
4494
4495InputDispatcher::InjectionState::~InjectionState() {
4496}
4497
4498void InputDispatcher::InjectionState::release() {
4499 refCount -= 1;
4500 if (refCount == 0) {
4501 delete this;
4502 } else {
4503 ALOG_ASSERT(refCount > 0);
4504 }
4505}
4506
4507
4508// --- InputDispatcher::EventEntry ---
4509
Prabir Pradhan42611e02018-11-27 14:04:02 -08004510InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4511 nsecs_t eventTime, uint32_t policyFlags) :
4512 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4513 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514}
4515
4516InputDispatcher::EventEntry::~EventEntry() {
4517 releaseInjectionState();
4518}
4519
4520void InputDispatcher::EventEntry::release() {
4521 refCount -= 1;
4522 if (refCount == 0) {
4523 delete this;
4524 } else {
4525 ALOG_ASSERT(refCount > 0);
4526 }
4527}
4528
4529void InputDispatcher::EventEntry::releaseInjectionState() {
4530 if (injectionState) {
4531 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004532 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004533 }
4534}
4535
4536
4537// --- InputDispatcher::ConfigurationChangedEntry ---
4538
Prabir Pradhan42611e02018-11-27 14:04:02 -08004539InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4540 uint32_t sequenceNum, nsecs_t eventTime) :
4541 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542}
4543
4544InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4545}
4546
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004547void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4548 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549}
4550
4551
4552// --- InputDispatcher::DeviceResetEntry ---
4553
Prabir Pradhan42611e02018-11-27 14:04:02 -08004554InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4555 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4556 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557 deviceId(deviceId) {
4558}
4559
4560InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4561}
4562
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004563void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4564 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565 deviceId, policyFlags);
4566}
4567
4568
4569// --- InputDispatcher::KeyEntry ---
4570
Prabir Pradhan42611e02018-11-27 14:04:02 -08004571InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004572 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004573 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4574 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004575 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004576 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4578 repeatCount(repeatCount), downTime(downTime),
4579 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4580 interceptKeyWakeupTime(0) {
4581}
4582
4583InputDispatcher::KeyEntry::~KeyEntry() {
4584}
4585
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004586void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Ashwini Orugantia70a3ff2019-12-04 17:05:19 -08004587 msg += StringPrintf("KeyEvent");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588}
4589
4590void InputDispatcher::KeyEntry::recycle() {
4591 releaseInjectionState();
4592
4593 dispatchInProgress = false;
4594 syntheticRepeat = false;
4595 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4596 interceptKeyWakeupTime = 0;
4597}
4598
4599
4600// --- InputDispatcher::MotionEntry ---
4601
Prabir Pradhan42611e02018-11-27 14:04:02 -08004602InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004603 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4604 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004605 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4606 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004607 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004608 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4609 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004610 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004612 deviceId(deviceId), source(source), displayId(displayId), action(action),
4613 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004614 classification(classification), edgeFlags(edgeFlags),
4615 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004616 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004617 for (uint32_t i = 0; i < pointerCount; i++) {
4618 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4619 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004620 if (xOffset || yOffset) {
4621 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004623 }
4624}
4625
4626InputDispatcher::MotionEntry::~MotionEntry() {
4627}
4628
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004629void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Ashwini Orugantia70a3ff2019-12-04 17:05:19 -08004630 msg += StringPrintf("MotionEvent");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004631}
4632
4633
4634// --- InputDispatcher::DispatchEntry ---
4635
4636volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4637
4638InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004639 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4640 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641 seq(nextSeq()),
4642 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004643 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4644 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4646 eventEntry->refCount += 1;
4647}
4648
4649InputDispatcher::DispatchEntry::~DispatchEntry() {
4650 eventEntry->release();
4651}
4652
4653uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4654 // Sequence number 0 is reserved and will never be returned.
4655 uint32_t seq;
4656 do {
4657 seq = android_atomic_inc(&sNextSeqAtomic);
4658 } while (!seq);
4659 return seq;
4660}
4661
4662
4663// --- InputDispatcher::InputState ---
4664
4665InputDispatcher::InputState::InputState() {
4666}
4667
4668InputDispatcher::InputState::~InputState() {
4669}
4670
4671bool InputDispatcher::InputState::isNeutral() const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004672 return mKeyMementos.empty() && mMotionMementos.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673}
4674
4675bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4676 int32_t displayId) const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004677 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004678 if (memento.deviceId == deviceId
4679 && memento.source == source
4680 && memento.displayId == displayId
4681 && memento.hovering) {
4682 return true;
4683 }
4684 }
4685 return false;
4686}
4687
4688bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4689 int32_t action, int32_t flags) {
4690 switch (action) {
4691 case AKEY_EVENT_ACTION_UP: {
4692 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4693 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4694 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4695 mFallbackKeys.removeItemsAt(i);
4696 } else {
4697 i += 1;
4698 }
4699 }
4700 }
4701 ssize_t index = findKeyMemento(entry);
4702 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004703 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704 return true;
4705 }
4706 /* FIXME: We can't just drop the key up event because that prevents creating
4707 * popup windows that are automatically shown when a key is held and then
4708 * dismissed when the key is released. The problem is that the popup will
4709 * not have received the original key down, so the key up will be considered
4710 * to be inconsistent with its observed state. We could perhaps handle this
4711 * by synthesizing a key down but that will cause other problems.
4712 *
4713 * So for now, allow inconsistent key up events to be dispatched.
4714 *
4715#if DEBUG_OUTBOUND_EVENT_DETAILS
4716 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4717 "keyCode=%d, scanCode=%d",
4718 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4719#endif
4720 return false;
4721 */
4722 return true;
4723 }
4724
4725 case AKEY_EVENT_ACTION_DOWN: {
4726 ssize_t index = findKeyMemento(entry);
4727 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004728 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729 }
4730 addKeyMemento(entry, flags);
4731 return true;
4732 }
4733
4734 default:
4735 return true;
4736 }
4737}
4738
4739bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4740 int32_t action, int32_t flags) {
4741 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4742 switch (actionMasked) {
4743 case AMOTION_EVENT_ACTION_UP:
4744 case AMOTION_EVENT_ACTION_CANCEL: {
4745 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4746 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004747 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 return true;
4749 }
4750#if DEBUG_OUTBOUND_EVENT_DETAILS
4751 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004752 "displayId=%" PRId32 ", actionMasked=%d",
4753 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004754#endif
4755 return false;
4756 }
4757
4758 case AMOTION_EVENT_ACTION_DOWN: {
4759 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4760 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004761 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762 }
4763 addMotionMemento(entry, flags, false /*hovering*/);
4764 return true;
4765 }
4766
4767 case AMOTION_EVENT_ACTION_POINTER_UP:
4768 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4769 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004770 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4771 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4772 // generate cancellation events for these since they're based in relative rather than
4773 // absolute units.
4774 return true;
4775 }
4776
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004778
4779 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4780 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4781 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4782 // other value and we need to track the motion so we can send cancellation events for
4783 // anything generating fallback events (e.g. DPad keys for joystick movements).
4784 if (index >= 0) {
4785 if (entry->pointerCoords[0].isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004786 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wright38dcdff2014-03-19 12:06:10 -07004787 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004788 MotionMemento& memento = mMotionMementos[index];
Michael Wright38dcdff2014-03-19 12:06:10 -07004789 memento.setPointers(entry);
4790 }
4791 } else if (!entry->pointerCoords[0].isEmpty()) {
4792 addMotionMemento(entry, flags, false /*hovering*/);
4793 }
4794
4795 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4796 return true;
4797 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004798 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004799 MotionMemento& memento = mMotionMementos[index];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800 memento.setPointers(entry);
4801 return true;
4802 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004803#if DEBUG_OUTBOUND_EVENT_DETAILS
4804 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004805 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4806 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807#endif
4808 return false;
4809 }
4810
4811 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4812 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4813 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004814 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 return true;
4816 }
4817#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004818 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4819 "displayId=%" PRId32,
4820 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821#endif
4822 return false;
4823 }
4824
4825 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4826 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4827 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4828 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004829 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 }
4831 addMotionMemento(entry, flags, true /*hovering*/);
4832 return true;
4833 }
4834
4835 default:
4836 return true;
4837 }
4838}
4839
4840ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4841 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004842 const KeyMemento& memento = mKeyMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843 if (memento.deviceId == entry->deviceId
4844 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004845 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846 && memento.keyCode == entry->keyCode
4847 && memento.scanCode == entry->scanCode) {
4848 return i;
4849 }
4850 }
4851 return -1;
4852}
4853
4854ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4855 bool hovering) const {
4856 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004857 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858 if (memento.deviceId == entry->deviceId
4859 && memento.source == entry->source
4860 && memento.displayId == entry->displayId
4861 && memento.hovering == hovering) {
4862 return i;
4863 }
4864 }
4865 return -1;
4866}
4867
4868void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004869 KeyMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 memento.deviceId = entry->deviceId;
4871 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004872 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 memento.keyCode = entry->keyCode;
4874 memento.scanCode = entry->scanCode;
4875 memento.metaState = entry->metaState;
4876 memento.flags = flags;
4877 memento.downTime = entry->downTime;
4878 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004879 mKeyMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880}
4881
4882void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4883 int32_t flags, bool hovering) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004884 MotionMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 memento.deviceId = entry->deviceId;
4886 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004887 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888 memento.flags = flags;
4889 memento.xPrecision = entry->xPrecision;
4890 memento.yPrecision = entry->yPrecision;
4891 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892 memento.setPointers(entry);
4893 memento.hovering = hovering;
4894 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004895 mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896}
4897
4898void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4899 pointerCount = entry->pointerCount;
4900 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4901 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4902 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4903 }
4904}
4905
4906void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004907 std::vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4908 for (KeyMemento& memento : mKeyMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909 if (shouldCancelKey(memento, options)) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004910 outEvents.push_back(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004911 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4913 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4914 }
4915 }
4916
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004917 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004919 const int32_t action = memento.hovering ?
4920 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004921 outEvents.push_back(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004922 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004923 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4924 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004926 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004927 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 }
4929 }
4930}
4931
4932void InputDispatcher::InputState::clear() {
4933 mKeyMementos.clear();
4934 mMotionMementos.clear();
4935 mFallbackKeys.clear();
4936}
4937
4938void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4939 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004940 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4942 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004943 const MotionMemento& otherMemento = other.mMotionMementos[j];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944 if (memento.deviceId == otherMemento.deviceId
4945 && memento.source == otherMemento.source
4946 && memento.displayId == otherMemento.displayId) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004947 other.mMotionMementos.erase(other.mMotionMementos.begin() + j);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004948 } else {
4949 j += 1;
4950 }
4951 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004952 other.mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953 }
4954 }
4955}
4956
4957int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4958 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4959 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4960}
4961
4962void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4963 int32_t fallbackKeyCode) {
4964 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4965 if (index >= 0) {
4966 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4967 } else {
4968 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4969 }
4970}
4971
4972void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4973 mFallbackKeys.removeItem(originalKeyCode);
4974}
4975
4976bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4977 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00004978 if (options.keyCode && memento.keyCode != options.keyCode.value()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004979 return false;
4980 }
4981
Michael Wright3dd60e22019-03-27 22:06:44 +00004982 if (options.deviceId && memento.deviceId != options.deviceId.value()) {
4983 return false;
4984 }
4985
4986 if (options.displayId && memento.displayId != options.displayId.value()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987 return false;
4988 }
4989
4990 switch (options.mode) {
4991 case CancelationOptions::CANCEL_ALL_EVENTS:
4992 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4993 return true;
4994 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4995 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
4996 default:
4997 return false;
4998 }
4999}
5000
5001bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
5002 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005003 if (options.deviceId && memento.deviceId != options.deviceId.value()) {
5004 return false;
5005 }
5006
5007 if (options.displayId && memento.displayId != options.displayId.value()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 return false;
5009 }
5010
5011 switch (options.mode) {
5012 case CancelationOptions::CANCEL_ALL_EVENTS:
5013 return true;
5014 case CancelationOptions::CANCEL_POINTER_EVENTS:
5015 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
5016 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
5017 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
5018 default:
5019 return false;
5020 }
5021}
5022
5023
5024// --- InputDispatcher::Connection ---
5025
Robert Carr803535b2018-08-02 16:38:15 -07005026InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
5027 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08005028 monitor(monitor),
5029 inputPublisher(inputChannel), inputPublisherBlocked(false) {
5030}
5031
5032InputDispatcher::Connection::~Connection() {
5033}
5034
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005035const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07005036 if (inputChannel != nullptr) {
5037 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005038 }
5039 if (monitor) {
5040 return "monitor";
5041 }
5042 return "?";
5043}
5044
5045const char* InputDispatcher::Connection::getStatusLabel() const {
5046 switch (status) {
5047 case STATUS_NORMAL:
5048 return "NORMAL";
5049
5050 case STATUS_BROKEN:
5051 return "BROKEN";
5052
5053 case STATUS_ZOMBIE:
5054 return "ZOMBIE";
5055
5056 default:
5057 return "UNKNOWN";
5058 }
5059}
5060
5061InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07005062 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005063 if (entry->seq == seq) {
5064 return entry;
5065 }
5066 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005067 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068}
5069
Michael Wright3dd60e22019-03-27 22:06:44 +00005070// --- InputDispatcher::Monitor
5071InputDispatcher::Monitor::Monitor(const sp<InputChannel>& inputChannel) :
5072 inputChannel(inputChannel) {
5073}
5074
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075
5076// --- InputDispatcher::CommandEntry ---
Michael Wright3dd60e22019-03-27 22:06:44 +00005077//
Michael Wrightd02c5b62014-02-10 15:10:22 -08005078InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07005079 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080 seq(0), handled(false) {
5081}
5082
5083InputDispatcher::CommandEntry::~CommandEntry() {
5084}
5085
Michael Wright3dd60e22019-03-27 22:06:44 +00005086// --- InputDispatcher::TouchedMonitor ---
5087InputDispatcher::TouchedMonitor::TouchedMonitor(const Monitor& monitor, float xOffset,
5088 float yOffset) : monitor(monitor), xOffset(xOffset), yOffset(yOffset) {
5089}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090
5091// --- InputDispatcher::TouchState ---
5092
5093InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01005094 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095}
5096
5097InputDispatcher::TouchState::~TouchState() {
5098}
5099
5100void InputDispatcher::TouchState::reset() {
5101 down = false;
5102 split = false;
5103 deviceId = -1;
5104 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01005105 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005107 portalWindows.clear();
Michael Wright3dd60e22019-03-27 22:06:44 +00005108 gestureMonitors.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005109}
5110
5111void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
5112 down = other.down;
5113 split = other.split;
5114 deviceId = other.deviceId;
5115 source = other.source;
5116 displayId = other.displayId;
5117 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005118 portalWindows = other.portalWindows;
Michael Wright3dd60e22019-03-27 22:06:44 +00005119 gestureMonitors = other.gestureMonitors;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120}
5121
5122void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
5123 int32_t targetFlags, BitSet32 pointerIds) {
5124 if (targetFlags & InputTarget::FLAG_SPLIT) {
5125 split = true;
5126 }
5127
5128 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005129 TouchedWindow& touchedWindow = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130 if (touchedWindow.windowHandle == windowHandle) {
5131 touchedWindow.targetFlags |= targetFlags;
5132 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
5133 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
5134 }
5135 touchedWindow.pointerIds.value |= pointerIds.value;
5136 return;
5137 }
5138 }
5139
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005140 TouchedWindow touchedWindow;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 touchedWindow.windowHandle = windowHandle;
5142 touchedWindow.targetFlags = targetFlags;
5143 touchedWindow.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005144 windows.push_back(touchedWindow);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145}
5146
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005147void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
5148 size_t numWindows = portalWindows.size();
5149 for (size_t i = 0; i < numWindows; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005150 if (portalWindows[i] == windowHandle) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005151 return;
5152 }
5153 }
5154 portalWindows.push_back(windowHandle);
5155}
5156
Michael Wright3dd60e22019-03-27 22:06:44 +00005157void InputDispatcher::TouchState::addGestureMonitors(
5158 const std::vector<TouchedMonitor>& newMonitors) {
5159 const size_t newSize = gestureMonitors.size() + newMonitors.size();
5160 gestureMonitors.reserve(newSize);
5161 gestureMonitors.insert(std::end(gestureMonitors),
5162 std::begin(newMonitors), std::end(newMonitors));
5163}
5164
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
5166 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005167 if (windows[i].windowHandle == windowHandle) {
5168 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169 return;
5170 }
5171 }
5172}
5173
Robert Carr803535b2018-08-02 16:38:15 -07005174void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
5175 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005176 if (windows[i].windowHandle->getToken() == token) {
5177 windows.erase(windows.begin() + i);
Robert Carr803535b2018-08-02 16:38:15 -07005178 return;
5179 }
5180 }
5181}
5182
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
5184 for (size_t i = 0 ; i < windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005185 TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005186 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
5187 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
5188 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
5189 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
5190 i += 1;
5191 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005192 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193 }
5194 }
5195}
5196
Michael Wright3dd60e22019-03-27 22:06:44 +00005197void InputDispatcher::TouchState::filterNonMonitors() {
5198 windows.clear();
5199 portalWindows.clear();
5200}
5201
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
5203 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005204 const TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5206 return window.windowHandle;
5207 }
5208 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005209 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005210}
5211
5212bool InputDispatcher::TouchState::isSlippery() const {
5213 // Must have exactly one foreground window.
5214 bool haveSlipperyForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005215 for (const TouchedWindow& window : windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005216 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5217 if (haveSlipperyForegroundWindow
5218 || !(window.windowHandle->getInfo()->layoutParamsFlags
5219 & InputWindowInfo::FLAG_SLIPPERY)) {
5220 return false;
5221 }
5222 haveSlipperyForegroundWindow = true;
5223 }
5224 }
5225 return haveSlipperyForegroundWindow;
5226}
5227
5228
5229// --- InputDispatcherThread ---
5230
5231InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5232 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5233}
5234
5235InputDispatcherThread::~InputDispatcherThread() {
5236}
5237
5238bool InputDispatcherThread::threadLoop() {
5239 mDispatcher->dispatchOnce();
5240 return true;
5241}
5242
5243} // namespace android