blob: abdecd965cbb1fd36a0affafdae3bf9abb43846f [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
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800112static std::string motionActionToString(int32_t action) {
113 // Convert MotionEvent action to string
114 switch(action & AMOTION_EVENT_ACTION_MASK) {
115 case AMOTION_EVENT_ACTION_DOWN:
116 return "DOWN";
117 case AMOTION_EVENT_ACTION_MOVE:
118 return "MOVE";
119 case AMOTION_EVENT_ACTION_UP:
120 return "UP";
121 case AMOTION_EVENT_ACTION_POINTER_DOWN:
122 return "POINTER_DOWN";
123 case AMOTION_EVENT_ACTION_POINTER_UP:
124 return "POINTER_UP";
125 }
126 return StringPrintf("%" PRId32, action);
127}
128
129static std::string keyActionToString(int32_t action) {
130 // Convert KeyEvent action to string
Michael Wright3dd60e22019-03-27 22:06:44 +0000131 switch (action) {
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800132 case AKEY_EVENT_ACTION_DOWN:
133 return "DOWN";
134 case AKEY_EVENT_ACTION_UP:
135 return "UP";
136 case AKEY_EVENT_ACTION_MULTIPLE:
137 return "MULTIPLE";
138 }
139 return StringPrintf("%" PRId32, action);
140}
141
Michael Wright3dd60e22019-03-27 22:06:44 +0000142static std::string dispatchModeToString(int32_t dispatchMode) {
143 switch (dispatchMode) {
144 case InputTarget::FLAG_DISPATCH_AS_IS:
145 return "DISPATCH_AS_IS";
146 case InputTarget::FLAG_DISPATCH_AS_OUTSIDE:
147 return "DISPATCH_AS_OUTSIDE";
148 case InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER:
149 return "DISPATCH_AS_HOVER_ENTER";
150 case InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT:
151 return "DISPATCH_AS_HOVER_EXIT";
152 case InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT:
153 return "DISPATCH_AS_SLIPPERY_EXIT";
154 case InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER:
155 return "DISPATCH_AS_SLIPPERY_ENTER";
156 }
157 return StringPrintf("%" PRId32, dispatchMode);
158}
159
Michael Wrightd02c5b62014-02-10 15:10:22 -0800160static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
161 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
162 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
163}
164
165static bool isValidKeyAction(int32_t action) {
166 switch (action) {
167 case AKEY_EVENT_ACTION_DOWN:
168 case AKEY_EVENT_ACTION_UP:
169 return true;
170 default:
171 return false;
172 }
173}
174
175static bool validateKeyEvent(int32_t action) {
176 if (! isValidKeyAction(action)) {
177 ALOGE("Key event has invalid action code 0x%x", action);
178 return false;
179 }
180 return true;
181}
182
Michael Wright7b159c92015-05-14 14:48:03 +0100183static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 switch (action & AMOTION_EVENT_ACTION_MASK) {
185 case AMOTION_EVENT_ACTION_DOWN:
186 case AMOTION_EVENT_ACTION_UP:
187 case AMOTION_EVENT_ACTION_CANCEL:
188 case AMOTION_EVENT_ACTION_MOVE:
189 case AMOTION_EVENT_ACTION_OUTSIDE:
190 case AMOTION_EVENT_ACTION_HOVER_ENTER:
191 case AMOTION_EVENT_ACTION_HOVER_MOVE:
192 case AMOTION_EVENT_ACTION_HOVER_EXIT:
193 case AMOTION_EVENT_ACTION_SCROLL:
194 return true;
195 case AMOTION_EVENT_ACTION_POINTER_DOWN:
196 case AMOTION_EVENT_ACTION_POINTER_UP: {
197 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800198 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 }
Michael Wright7b159c92015-05-14 14:48:03 +0100200 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
201 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
202 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203 default:
204 return false;
205 }
206}
207
Michael Wright7b159c92015-05-14 14:48:03 +0100208static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800209 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100210 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 ALOGE("Motion event has invalid action code 0x%x", action);
212 return false;
213 }
214 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000215 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800216 pointerCount, MAX_POINTERS);
217 return false;
218 }
219 BitSet32 pointerIdBits;
220 for (size_t i = 0; i < pointerCount; i++) {
221 int32_t id = pointerProperties[i].id;
222 if (id < 0 || id > MAX_POINTER_ID) {
223 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
224 id, MAX_POINTER_ID);
225 return false;
226 }
227 if (pointerIdBits.hasBit(id)) {
228 ALOGE("Motion event has duplicate pointer id %d", id);
229 return false;
230 }
231 pointerIdBits.markBit(id);
232 }
233 return true;
234}
235
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800236static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800238 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239 return;
240 }
241
242 bool first = true;
243 Region::const_iterator cur = region.begin();
244 Region::const_iterator const tail = region.end();
245 while (cur != tail) {
246 if (first) {
247 first = false;
248 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800249 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800251 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 cur++;
253 }
254}
255
Tiger Huang721e26f2018-07-24 22:26:19 +0800256template<typename T, typename U>
257static T getValueByKey(std::unordered_map<U, T>& map, U key) {
258 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
259 return it != map.end() ? it->second : T{};
260}
261
Michael Wrightd02c5b62014-02-10 15:10:22 -0800262
263// --- InputDispatcher ---
264
265InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
266 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700267 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100268 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700269 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800270 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800271 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800272 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
273 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800274 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800275
Yi Kong9b14ac62018-07-17 13:48:38 -0700276 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800277
278 policy->getDispatcherConfiguration(&mConfig);
279}
280
281InputDispatcher::~InputDispatcher() {
282 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800283 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800284
285 resetKeyRepeatLocked();
286 releasePendingEventLocked();
287 drainInboundQueueLocked();
288 }
289
290 while (mConnectionsByFd.size() != 0) {
291 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
292 }
293}
294
295void InputDispatcher::dispatchOnce() {
296 nsecs_t nextWakeupTime = LONG_LONG_MAX;
297 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800298 std::scoped_lock _l(mLock);
299 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800300
301 // Run a dispatch loop if there are no pending commands.
302 // The dispatch loop might enqueue commands to run afterwards.
303 if (!haveCommandsLocked()) {
304 dispatchOnceInnerLocked(&nextWakeupTime);
305 }
306
307 // Run all pending commands if there are any.
308 // If any commands were run then force the next poll to wake up immediately.
309 if (runCommandsLockedInterruptible()) {
310 nextWakeupTime = LONG_LONG_MIN;
311 }
312 } // release lock
313
314 // Wait for callback or timeout or wake. (make sure we round up, not down)
315 nsecs_t currentTime = now();
316 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
317 mLooper->pollOnce(timeoutMillis);
318}
319
320void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
321 nsecs_t currentTime = now();
322
Jeff Browndc5992e2014-04-11 01:27:26 -0700323 // Reset the key repeat timer whenever normal dispatch is suspended while the
324 // device is in a non-interactive state. This is to ensure that we abort a key
325 // repeat if the device is just coming out of sleep.
326 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800327 resetKeyRepeatLocked();
328 }
329
330 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
331 if (mDispatchFrozen) {
332#if DEBUG_FOCUS
333 ALOGD("Dispatch frozen. Waiting some more.");
334#endif
335 return;
336 }
337
338 // Optimize latency of app switches.
339 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
340 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
341 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
342 if (mAppSwitchDueTime < *nextWakeupTime) {
343 *nextWakeupTime = mAppSwitchDueTime;
344 }
345
346 // Ready to start a new event.
347 // If we don't already have a pending event, go grab one.
348 if (! mPendingEvent) {
349 if (mInboundQueue.isEmpty()) {
350 if (isAppSwitchDue) {
351 // The inbound queue is empty so the app switch key we were waiting
352 // for will never arrive. Stop waiting for it.
353 resetPendingAppSwitchLocked(false);
354 isAppSwitchDue = false;
355 }
356
357 // Synthesize a key repeat if appropriate.
358 if (mKeyRepeatState.lastKeyEntry) {
359 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
360 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
361 } else {
362 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
363 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
364 }
365 }
366 }
367
368 // Nothing to do if there is no pending event.
369 if (!mPendingEvent) {
370 return;
371 }
372 } else {
373 // Inbound queue has at least one entry.
374 mPendingEvent = mInboundQueue.dequeueAtHead();
375 traceInboundQueueLengthLocked();
376 }
377
378 // Poke user activity for this event.
379 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
380 pokeUserActivityLocked(mPendingEvent);
381 }
382
383 // Get ready to dispatch the event.
384 resetANRTimeoutsLocked();
385 }
386
387 // Now we have an event to dispatch.
388 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700389 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800390 bool done = false;
391 DropReason dropReason = DROP_REASON_NOT_DROPPED;
392 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
393 dropReason = DROP_REASON_POLICY;
394 } else if (!mDispatchEnabled) {
395 dropReason = DROP_REASON_DISABLED;
396 }
397
398 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700399 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800400 }
401
402 switch (mPendingEvent->type) {
403 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
404 ConfigurationChangedEntry* typedEntry =
405 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
406 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
407 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
408 break;
409 }
410
411 case EventEntry::TYPE_DEVICE_RESET: {
412 DeviceResetEntry* typedEntry =
413 static_cast<DeviceResetEntry*>(mPendingEvent);
414 done = dispatchDeviceResetLocked(currentTime, typedEntry);
415 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
416 break;
417 }
418
419 case EventEntry::TYPE_KEY: {
420 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
421 if (isAppSwitchDue) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800422 if (isAppSwitchKeyEvent(typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800423 resetPendingAppSwitchLocked(true);
424 isAppSwitchDue = false;
425 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
426 dropReason = DROP_REASON_APP_SWITCH;
427 }
428 }
429 if (dropReason == DROP_REASON_NOT_DROPPED
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800430 && isStaleEvent(currentTime, typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 dropReason = DROP_REASON_STALE;
432 }
433 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
434 dropReason = DROP_REASON_BLOCKED;
435 }
436 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
437 break;
438 }
439
440 case EventEntry::TYPE_MOTION: {
441 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
442 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
443 dropReason = DROP_REASON_APP_SWITCH;
444 }
445 if (dropReason == DROP_REASON_NOT_DROPPED
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800446 && isStaleEvent(currentTime, typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800447 dropReason = DROP_REASON_STALE;
448 }
449 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
450 dropReason = DROP_REASON_BLOCKED;
451 }
452 done = dispatchMotionLocked(currentTime, typedEntry,
453 &dropReason, nextWakeupTime);
454 break;
455 }
456
457 default:
458 ALOG_ASSERT(false);
459 break;
460 }
461
462 if (done) {
463 if (dropReason != DROP_REASON_NOT_DROPPED) {
464 dropInboundEventLocked(mPendingEvent, dropReason);
465 }
Michael Wright3a981722015-06-10 15:26:13 +0100466 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800467
468 releasePendingEventLocked();
469 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
470 }
471}
472
473bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
474 bool needWake = mInboundQueue.isEmpty();
475 mInboundQueue.enqueueAtTail(entry);
476 traceInboundQueueLengthLocked();
477
478 switch (entry->type) {
479 case EventEntry::TYPE_KEY: {
480 // Optimize app switch latency.
481 // If the application takes too long to catch up then we drop all events preceding
482 // the app switch key.
483 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800484 if (isAppSwitchKeyEvent(keyEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
486 mAppSwitchSawKeyDown = true;
487 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
488 if (mAppSwitchSawKeyDown) {
489#if DEBUG_APP_SWITCH
490 ALOGD("App switch is pending!");
491#endif
492 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
493 mAppSwitchSawKeyDown = false;
494 needWake = true;
495 }
496 }
497 }
498 break;
499 }
500
501 case EventEntry::TYPE_MOTION: {
502 // Optimize case where the current application is unresponsive and the user
503 // decides to touch a window in a different application.
504 // If the application takes too long to catch up then we drop all events preceding
505 // the touch into the other window.
506 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
507 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
508 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
509 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Robert Carr740167f2018-10-11 19:03:41 -0700510 && mInputTargetWaitApplicationToken != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 int32_t displayId = motionEntry->displayId;
512 int32_t x = int32_t(motionEntry->pointerCoords[0].
513 getAxisValue(AMOTION_EVENT_AXIS_X));
514 int32_t y = int32_t(motionEntry->pointerCoords[0].
515 getAxisValue(AMOTION_EVENT_AXIS_Y));
516 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700517 if (touchedWindowHandle != nullptr
Robert Carr740167f2018-10-11 19:03:41 -0700518 && touchedWindowHandle->getApplicationToken()
519 != mInputTargetWaitApplicationToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800520 // User touched a different application than the one we are waiting on.
521 // Flag the event, and start pruning the input queue.
522 mNextUnblockedEvent = motionEntry;
523 needWake = true;
524 }
525 }
526 break;
527 }
528 }
529
530 return needWake;
531}
532
533void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
534 entry->refCount += 1;
535 mRecentQueue.enqueueAtTail(entry);
536 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
537 mRecentQueue.dequeueAtHead()->release();
538 }
539}
540
541sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800542 int32_t x, int32_t y, bool addOutsideTargets, bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800544 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
545 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546 const InputWindowInfo* windowInfo = windowHandle->getInfo();
547 if (windowInfo->displayId == displayId) {
548 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549
550 if (windowInfo->visible) {
551 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
552 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
553 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
554 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800555 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
556 if (portalToDisplayId != ADISPLAY_ID_NONE
557 && portalToDisplayId != displayId) {
558 if (addPortalWindows) {
559 // For the monitoring channels of the display.
560 mTempTouchState.addPortalWindow(windowHandle);
561 }
562 return findTouchedWindowAtLocked(
563 portalToDisplayId, x, y, addOutsideTargets, addPortalWindows);
564 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565 // Found window.
566 return windowHandle;
567 }
568 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800569
570 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
571 mTempTouchState.addOrUpdateWindow(
572 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575 }
576 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700577 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800578}
579
Michael Wright3dd60e22019-03-27 22:06:44 +0000580std::vector<InputDispatcher::TouchedMonitor> InputDispatcher::findTouchedGestureMonitorsLocked(
581 int32_t displayId, const std::vector<sp<InputWindowHandle>>& portalWindows) {
582 std::vector<TouchedMonitor> touchedMonitors;
583
584 std::vector<Monitor> monitors = getValueByKey(mGestureMonitorsByDisplay, displayId);
585 addGestureMonitors(monitors, touchedMonitors);
586 for (const sp<InputWindowHandle>& portalWindow : portalWindows) {
587 const InputWindowInfo* windowInfo = portalWindow->getInfo();
588 monitors = getValueByKey(mGestureMonitorsByDisplay, windowInfo->portalToDisplayId);
589 addGestureMonitors(monitors, touchedMonitors,
590 -windowInfo->frameLeft, -windowInfo->frameTop);
591 }
592 return touchedMonitors;
593}
594
595void InputDispatcher::addGestureMonitors(const std::vector<Monitor>& monitors,
596 std::vector<TouchedMonitor>& outTouchedMonitors, float xOffset, float yOffset) {
597 if (monitors.empty()) {
598 return;
599 }
600 outTouchedMonitors.reserve(monitors.size() + outTouchedMonitors.size());
601 for (const Monitor& monitor : monitors) {
602 outTouchedMonitors.emplace_back(monitor, xOffset, yOffset);
603 }
604}
605
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
607 const char* reason;
608 switch (dropReason) {
609 case DROP_REASON_POLICY:
610#if DEBUG_INBOUND_EVENT_DETAILS
611 ALOGD("Dropped event because policy consumed it.");
612#endif
613 reason = "inbound event was dropped because the policy consumed it";
614 break;
615 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100616 if (mLastDropReason != DROP_REASON_DISABLED) {
617 ALOGI("Dropped event because input dispatch is disabled.");
618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800619 reason = "inbound event was dropped because input dispatch is disabled";
620 break;
621 case DROP_REASON_APP_SWITCH:
622 ALOGI("Dropped event because of pending overdue app switch.");
623 reason = "inbound event was dropped because of pending overdue app switch";
624 break;
625 case DROP_REASON_BLOCKED:
626 ALOGI("Dropped event because the current application is not responding and the user "
627 "has started interacting with a different application.");
628 reason = "inbound event was dropped because the current application is not responding "
629 "and the user has started interacting with a different application";
630 break;
631 case DROP_REASON_STALE:
632 ALOGI("Dropped event because it is stale.");
633 reason = "inbound event was dropped because it is stale";
634 break;
635 default:
636 ALOG_ASSERT(false);
637 return;
638 }
639
640 switch (entry->type) {
641 case EventEntry::TYPE_KEY: {
642 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
643 synthesizeCancelationEventsForAllConnectionsLocked(options);
644 break;
645 }
646 case EventEntry::TYPE_MOTION: {
647 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
648 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
649 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
650 synthesizeCancelationEventsForAllConnectionsLocked(options);
651 } else {
652 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
653 synthesizeCancelationEventsForAllConnectionsLocked(options);
654 }
655 break;
656 }
657 }
658}
659
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800660static bool isAppSwitchKeyCode(int32_t keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 return keyCode == AKEYCODE_HOME
662 || keyCode == AKEYCODE_ENDCALL
663 || keyCode == AKEYCODE_APP_SWITCH;
664}
665
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800666bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800667 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
668 && isAppSwitchKeyCode(keyEntry->keyCode)
669 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
670 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
671}
672
673bool InputDispatcher::isAppSwitchPendingLocked() {
674 return mAppSwitchDueTime != LONG_LONG_MAX;
675}
676
677void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
678 mAppSwitchDueTime = LONG_LONG_MAX;
679
680#if DEBUG_APP_SWITCH
681 if (handled) {
682 ALOGD("App switch has arrived.");
683 } else {
684 ALOGD("App switch was abandoned.");
685 }
686#endif
687}
688
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800689bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
691}
692
693bool InputDispatcher::haveCommandsLocked() const {
694 return !mCommandQueue.isEmpty();
695}
696
697bool InputDispatcher::runCommandsLockedInterruptible() {
698 if (mCommandQueue.isEmpty()) {
699 return false;
700 }
701
702 do {
703 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
704
705 Command command = commandEntry->command;
706 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
707
708 commandEntry->connection.clear();
709 delete commandEntry;
710 } while (! mCommandQueue.isEmpty());
711 return true;
712}
713
714InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
715 CommandEntry* commandEntry = new CommandEntry(command);
716 mCommandQueue.enqueueAtTail(commandEntry);
717 return commandEntry;
718}
719
720void InputDispatcher::drainInboundQueueLocked() {
721 while (! mInboundQueue.isEmpty()) {
722 EventEntry* entry = mInboundQueue.dequeueAtHead();
723 releaseInboundEventLocked(entry);
724 }
725 traceInboundQueueLengthLocked();
726}
727
728void InputDispatcher::releasePendingEventLocked() {
729 if (mPendingEvent) {
730 resetANRTimeoutsLocked();
731 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700732 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733 }
734}
735
736void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
737 InjectionState* injectionState = entry->injectionState;
738 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
739#if DEBUG_DISPATCH_CYCLE
740 ALOGD("Injected inbound event was dropped.");
741#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800742 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800743 }
744 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700745 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800746 }
747 addRecentEventLocked(entry);
748 entry->release();
749}
750
751void InputDispatcher::resetKeyRepeatLocked() {
752 if (mKeyRepeatState.lastKeyEntry) {
753 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700754 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800755 }
756}
757
758InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
759 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
760
761 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700762 uint32_t policyFlags = entry->policyFlags &
763 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764 if (entry->refCount == 1) {
765 entry->recycle();
766 entry->eventTime = currentTime;
767 entry->policyFlags = policyFlags;
768 entry->repeatCount += 1;
769 } else {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800770 KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100771 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800772 entry->action, entry->flags, entry->keyCode, entry->scanCode,
773 entry->metaState, entry->repeatCount + 1, entry->downTime);
774
775 mKeyRepeatState.lastKeyEntry = newEntry;
776 entry->release();
777
778 entry = newEntry;
779 }
780 entry->syntheticRepeat = true;
781
782 // Increment reference count since we keep a reference to the event in
783 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
784 entry->refCount += 1;
785
786 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
787 return entry;
788}
789
790bool InputDispatcher::dispatchConfigurationChangedLocked(
791 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
792#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700793 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794#endif
795
796 // Reset key repeating in case a keyboard device was added or removed or something.
797 resetKeyRepeatLocked();
798
799 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
800 CommandEntry* commandEntry = postCommandLocked(
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800801 & InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800802 commandEntry->eventTime = entry->eventTime;
803 return true;
804}
805
806bool InputDispatcher::dispatchDeviceResetLocked(
807 nsecs_t currentTime, DeviceResetEntry* entry) {
808#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700809 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
810 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811#endif
812
813 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
814 "device was reset");
815 options.deviceId = entry->deviceId;
816 synthesizeCancelationEventsForAllConnectionsLocked(options);
817 return true;
818}
819
820bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
821 DropReason* dropReason, nsecs_t* nextWakeupTime) {
822 // Preprocessing.
823 if (! entry->dispatchInProgress) {
824 if (entry->repeatCount == 0
825 && entry->action == AKEY_EVENT_ACTION_DOWN
826 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
827 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
828 if (mKeyRepeatState.lastKeyEntry
829 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
830 // We have seen two identical key downs in a row which indicates that the device
831 // driver is automatically generating key repeats itself. We take note of the
832 // repeat here, but we disable our own next key repeat timer since it is clear that
833 // we will not need to synthesize key repeats ourselves.
834 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
835 resetKeyRepeatLocked();
836 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
837 } else {
838 // Not a repeat. Save key down state in case we do see a repeat later.
839 resetKeyRepeatLocked();
840 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
841 }
842 mKeyRepeatState.lastKeyEntry = entry;
843 entry->refCount += 1;
844 } else if (! entry->syntheticRepeat) {
845 resetKeyRepeatLocked();
846 }
847
848 if (entry->repeatCount == 1) {
849 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
850 } else {
851 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
852 }
853
854 entry->dispatchInProgress = true;
855
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800856 logOutboundKeyDetails("dispatchKey - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 }
858
859 // Handle case where the policy asked us to try again later last time.
860 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
861 if (currentTime < entry->interceptKeyWakeupTime) {
862 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
863 *nextWakeupTime = entry->interceptKeyWakeupTime;
864 }
865 return false; // wait until next wakeup
866 }
867 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
868 entry->interceptKeyWakeupTime = 0;
869 }
870
871 // Give the policy a chance to intercept the key.
872 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
873 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
874 CommandEntry* commandEntry = postCommandLocked(
875 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800876 sp<InputWindowHandle> focusedWindowHandle =
877 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
878 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700879 commandEntry->inputChannel =
880 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 }
882 commandEntry->keyEntry = entry;
883 entry->refCount += 1;
884 return false; // wait for the command to run
885 } else {
886 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
887 }
888 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
889 if (*dropReason == DROP_REASON_NOT_DROPPED) {
890 *dropReason = DROP_REASON_POLICY;
891 }
892 }
893
894 // Clean up if dropping the event.
895 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800896 setInjectionResult(entry, *dropReason == DROP_REASON_POLICY
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800898 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 return true;
900 }
901
902 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800903 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
905 entry, inputTargets, nextWakeupTime);
906 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
907 return false;
908 }
909
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800910 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
912 return true;
913 }
914
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800915 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000916 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917
918 // Dispatch the key.
919 dispatchEventLocked(currentTime, entry, inputTargets);
920 return true;
921}
922
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800923void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100925 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
926 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800927 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100929 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800931 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932#endif
933}
934
935bool InputDispatcher::dispatchMotionLocked(
936 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000937 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 // Preprocessing.
939 if (! entry->dispatchInProgress) {
940 entry->dispatchInProgress = true;
941
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800942 logOutboundMotionDetails("dispatchMotion - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800943 }
944
945 // Clean up if dropping the event.
946 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800947 setInjectionResult(entry, *dropReason == DROP_REASON_POLICY
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
949 return true;
950 }
951
952 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
953
954 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800955 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956
957 bool conflictingPointerActions = false;
958 int32_t injectionResult;
959 if (isPointerEvent) {
960 // Pointer event. (eg. touchscreen)
961 injectionResult = findTouchedWindowTargetsLocked(currentTime,
962 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
963 } else {
964 // Non touch event. (eg. trackball)
965 injectionResult = findFocusedWindowTargetsLocked(currentTime,
966 entry, inputTargets, nextWakeupTime);
967 }
968 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
969 return false;
970 }
971
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800972 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100974 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
975 CancelationOptions::Mode mode(isPointerEvent ?
976 CancelationOptions::CANCEL_POINTER_EVENTS :
977 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
978 CancelationOptions options(mode, "input event injection failed");
979 synthesizeCancelationEventsForMonitorsLocked(options);
980 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 return true;
982 }
983
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800984 // Add monitor channels from event's or focused display.
Michael Wright3dd60e22019-03-27 22:06:44 +0000985 addGlobalMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800987 if (isPointerEvent) {
988 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
989 if (stateIndex >= 0) {
990 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800991 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800992 // The event has gone through these portal windows, so we add monitoring targets of
993 // the corresponding displays as well.
994 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800995 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Michael Wright3dd60e22019-03-27 22:06:44 +0000996 addGlobalMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800997 -windowInfo->frameLeft, -windowInfo->frameTop);
998 }
999 }
1000 }
1001 }
1002
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003 // Dispatch the motion.
1004 if (conflictingPointerActions) {
1005 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
1006 "conflicting pointer actions");
1007 synthesizeCancelationEventsForAllConnectionsLocked(options);
1008 }
1009 dispatchEventLocked(currentTime, entry, inputTargets);
1010 return true;
1011}
1012
1013
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001014void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001016 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
1017 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01001018 "action=0x%x, actionButton=0x%x, flags=0x%x, "
1019 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08001020 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001022 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +01001023 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 entry->metaState, entry->buttonState,
1025 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +08001026 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027
1028 for (uint32_t i = 0; i < entry->pointerCount; i++) {
1029 ALOGD(" Pointer %d: id=%d, toolType=%d, "
1030 "x=%f, y=%f, pressure=%f, size=%f, "
1031 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08001032 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 i, entry->pointerProperties[i].id,
1034 entry->pointerProperties[i].toolType,
1035 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
1036 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
1037 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
1038 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
1039 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
1040 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
1041 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
1042 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08001043 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 }
1045#endif
1046}
1047
1048void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001049 EventEntry* eventEntry, const std::vector<InputTarget>& inputTargets) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001050 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051#if DEBUG_DISPATCH_CYCLE
1052 ALOGD("dispatchEventToCurrentInputTargets");
1053#endif
1054
1055 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1056
1057 pokeUserActivityLocked(eventEntry);
1058
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001059 for (const InputTarget& inputTarget : inputTargets) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
1061 if (connectionIndex >= 0) {
1062 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1063 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1064 } else {
1065#if DEBUG_FOCUS
1066 ALOGD("Dropping event delivery to target with channel '%s' because it "
1067 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001068 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001069#endif
1070 }
1071 }
1072}
1073
1074int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1075 const EventEntry* entry,
1076 const sp<InputApplicationHandle>& applicationHandle,
1077 const sp<InputWindowHandle>& windowHandle,
1078 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001079 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1081#if DEBUG_FOCUS
1082 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1083#endif
1084 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1085 mInputTargetWaitStartTime = currentTime;
1086 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1087 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001088 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 }
1090 } else {
1091 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1092#if DEBUG_FOCUS
1093 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001094 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001095 reason);
1096#endif
1097 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001098 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001100 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101 timeout = applicationHandle->getDispatchingTimeout(
1102 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1103 } else {
1104 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1105 }
1106
1107 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1108 mInputTargetWaitStartTime = currentTime;
1109 mInputTargetWaitTimeoutTime = currentTime + timeout;
1110 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001111 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112
Yi Kong9b14ac62018-07-17 13:48:38 -07001113 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001114 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115 }
Robert Carr740167f2018-10-11 19:03:41 -07001116 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1117 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 }
1119 }
1120 }
1121
1122 if (mInputTargetWaitTimeoutExpired) {
1123 return INPUT_EVENT_INJECTION_TIMED_OUT;
1124 }
1125
1126 if (currentTime >= mInputTargetWaitTimeoutTime) {
1127 onANRLocked(currentTime, applicationHandle, windowHandle,
1128 entry->eventTime, mInputTargetWaitStartTime, reason);
1129
1130 // Force poll loop to wake up immediately on next iteration once we get the
1131 // ANR response back from the policy.
1132 *nextWakeupTime = LONG_LONG_MIN;
1133 return INPUT_EVENT_INJECTION_PENDING;
1134 } else {
1135 // Force poll loop to wake up when timeout is due.
1136 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1137 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1138 }
1139 return INPUT_EVENT_INJECTION_PENDING;
1140 }
1141}
1142
Robert Carr803535b2018-08-02 16:38:15 -07001143void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1144 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1145 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1146 state.removeWindowByToken(token);
1147 }
1148}
1149
Michael Wrightd02c5b62014-02-10 15:10:22 -08001150void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1151 const sp<InputChannel>& inputChannel) {
1152 if (newTimeout > 0) {
1153 // Extend the timeout.
1154 mInputTargetWaitTimeoutTime = now() + newTimeout;
1155 } else {
1156 // Give up.
1157 mInputTargetWaitTimeoutExpired = true;
1158
1159 // Input state will not be realistic. Mark it out of sync.
1160 if (inputChannel.get()) {
1161 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1162 if (connectionIndex >= 0) {
1163 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001164 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165
Robert Carr803535b2018-08-02 16:38:15 -07001166 if (token != nullptr) {
1167 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 }
1169
1170 if (connection->status == Connection::STATUS_NORMAL) {
1171 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1172 "application not responding");
1173 synthesizeCancelationEventsForConnectionLocked(connection, options);
1174 }
1175 }
1176 }
1177 }
1178}
1179
1180nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1181 nsecs_t currentTime) {
1182 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1183 return currentTime - mInputTargetWaitStartTime;
1184 }
1185 return 0;
1186}
1187
1188void InputDispatcher::resetANRTimeoutsLocked() {
1189#if DEBUG_FOCUS
1190 ALOGD("Resetting ANR timeouts.");
1191#endif
1192
1193 // Reset input target wait timeout.
1194 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001195 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196}
1197
Tiger Huang721e26f2018-07-24 22:26:19 +08001198/**
1199 * Get the display id that the given event should go to. If this event specifies a valid display id,
1200 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1201 * Focused display is the display that the user most recently interacted with.
1202 */
1203int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1204 int32_t displayId;
1205 switch (entry->type) {
1206 case EventEntry::TYPE_KEY: {
1207 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1208 displayId = typedEntry->displayId;
1209 break;
1210 }
1211 case EventEntry::TYPE_MOTION: {
1212 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1213 displayId = typedEntry->displayId;
1214 break;
1215 }
1216 default: {
1217 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1218 return ADISPLAY_ID_NONE;
1219 }
1220 }
1221 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1222}
1223
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001225 const EventEntry* entry, std::vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001227 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228
Tiger Huang721e26f2018-07-24 22:26:19 +08001229 int32_t displayId = getTargetDisplayId(entry);
1230 sp<InputWindowHandle> focusedWindowHandle =
1231 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1232 sp<InputApplicationHandle> focusedApplicationHandle =
1233 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1234
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235 // If there is no currently focused window and no focused application
1236 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001237 if (focusedWindowHandle == nullptr) {
1238 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001240 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 "Waiting because no window has focus but there is a "
1242 "focused application that may eventually add a window "
1243 "when it finishes starting up.");
1244 goto Unresponsive;
1245 }
1246
Arthur Hung3b413f22018-10-26 18:05:34 +08001247 ALOGI("Dropping event because there is no focused window or focused application in display "
1248 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1250 goto Failed;
1251 }
1252
1253 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001254 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1256 goto Failed;
1257 }
1258
Jeff Brownffb49772014-10-10 19:01:34 -07001259 // Check whether the window is ready for more input.
1260 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001261 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001262 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001264 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 goto Unresponsive;
1266 }
1267
1268 // Success! Output targets.
1269 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001270 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1272 inputTargets);
1273
1274 // Done.
1275Failed:
1276Unresponsive:
1277 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001278 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001279#if DEBUG_FOCUS
1280 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1281 "timeSpentWaitingForApplication=%0.1fms",
1282 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1283#endif
1284 return injectionResult;
1285}
1286
1287int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001288 const MotionEntry* entry, std::vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289 bool* outConflictingPointerActions) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001290 ATRACE_CALL();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291 enum InjectionPermission {
1292 INJECTION_PERMISSION_UNKNOWN,
1293 INJECTION_PERMISSION_GRANTED,
1294 INJECTION_PERMISSION_DENIED
1295 };
1296
Michael Wrightd02c5b62014-02-10 15:10:22 -08001297 // For security reasons, we defer updating the touch state until we are sure that
1298 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 int32_t displayId = entry->displayId;
1300 int32_t action = entry->action;
1301 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1302
1303 // Update the touch state as needed based on the properties of the touch event.
1304 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1305 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1306 sp<InputWindowHandle> newHoverWindowHandle;
1307
Jeff Brownf086ddb2014-02-11 14:28:48 -08001308 // Copy current touch state into mTempTouchState.
1309 // This state is always reset at the end of this function, so if we don't find state
1310 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001311 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001312 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1313 if (oldStateIndex >= 0) {
1314 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1315 mTempTouchState.copyFrom(*oldState);
1316 }
1317
1318 bool isSplit = mTempTouchState.split;
1319 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1320 && (mTempTouchState.deviceId != entry->deviceId
1321 || mTempTouchState.source != entry->source
1322 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1324 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1325 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1326 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1327 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1328 || isHoverAction);
1329 bool wrongDevice = false;
1330 if (newGesture) {
1331 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001332 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001334 ALOGD("Dropping event because a pointer for a different device is already down "
1335 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001336#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001337 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001338 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1339 switchedDevice = false;
1340 wrongDevice = true;
1341 goto Failed;
1342 }
1343 mTempTouchState.reset();
1344 mTempTouchState.down = down;
1345 mTempTouchState.deviceId = entry->deviceId;
1346 mTempTouchState.source = entry->source;
1347 mTempTouchState.displayId = displayId;
1348 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001349 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1350#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001351 ALOGI("Dropping move event because a pointer for a different device is already active "
1352 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001353#endif
1354 // TODO: test multiple simultaneous input streams.
1355 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1356 switchedDevice = false;
1357 wrongDevice = true;
1358 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 }
1360
1361 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1362 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1363
1364 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1365 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1366 getAxisValue(AMOTION_EVENT_AXIS_X));
1367 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1368 getAxisValue(AMOTION_EVENT_AXIS_Y));
Michael Wright3dd60e22019-03-27 22:06:44 +00001369 bool isDown = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001370 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(
Michael Wright3dd60e22019-03-27 22:06:44 +00001371 displayId, x, y, isDown /*addOutsideTargets*/, true /*addPortalWindows*/);
1372
1373 std::vector<TouchedMonitor> newGestureMonitors = isDown
1374 ? findTouchedGestureMonitorsLocked(displayId, mTempTouchState.portalWindows)
1375 : std::vector<TouchedMonitor>{};
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001378 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1380 // New window supports splitting.
1381 isSplit = true;
1382 } else if (isSplit) {
1383 // New window does not support splitting but we have already split events.
1384 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001385 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001386 }
1387
1388 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001389 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 // Try to assign the pointer to the first foreground window we find, if there is one.
1391 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001392 }
1393
1394 if (newTouchedWindowHandle == nullptr && newGestureMonitors.empty()) {
1395 ALOGI("Dropping event because there is no touchable window or gesture monitor at "
1396 "(%d, %d) in display %" PRId32 ".", x, y, displayId);
1397 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1398 goto Failed;
1399 }
1400
1401 if (newTouchedWindowHandle != nullptr) {
1402 // Set target flags.
1403 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1404 if (isSplit) {
1405 targetFlags |= InputTarget::FLAG_SPLIT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001407 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1408 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1409 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1410 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1411 }
1412
1413 // Update hover state.
1414 if (isHoverAction) {
1415 newHoverWindowHandle = newTouchedWindowHandle;
1416 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1417 newHoverWindowHandle = mLastHoverWindowHandle;
1418 }
1419
1420 // Update the temporary touch state.
1421 BitSet32 pointerIds;
1422 if (isSplit) {
1423 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1424 pointerIds.markBit(pointerId);
1425 }
1426 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 }
1428
Michael Wright3dd60e22019-03-27 22:06:44 +00001429 mTempTouchState.addGestureMonitors(newGestureMonitors);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430 } else {
1431 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1432
1433 // If the pointer is not currently down, then ignore the event.
1434 if (! mTempTouchState.down) {
1435#if DEBUG_FOCUS
1436 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001437 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438#endif
1439 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1440 goto Failed;
1441 }
1442
1443 // Check whether touches should slip outside of the current foreground window.
1444 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1445 && entry->pointerCount == 1
1446 && mTempTouchState.isSlippery()) {
1447 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1448 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1449
1450 sp<InputWindowHandle> oldTouchedWindowHandle =
1451 mTempTouchState.getFirstForegroundWindowHandle();
1452 sp<InputWindowHandle> newTouchedWindowHandle =
1453 findTouchedWindowAtLocked(displayId, x, y);
1454 if (oldTouchedWindowHandle != newTouchedWindowHandle
Michael Wright3dd60e22019-03-27 22:06:44 +00001455 && oldTouchedWindowHandle != nullptr
Yi Kong9b14ac62018-07-17 13:48:38 -07001456 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001457#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001458 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001459 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001460 newTouchedWindowHandle->getName().c_str(),
1461 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462#endif
1463 // Make a slippery exit from the old window.
1464 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1465 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1466
1467 // Make a slippery entrance into the new window.
1468 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1469 isSplit = true;
1470 }
1471
1472 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1473 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1474 if (isSplit) {
1475 targetFlags |= InputTarget::FLAG_SPLIT;
1476 }
1477 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1478 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1479 }
1480
1481 BitSet32 pointerIds;
1482 if (isSplit) {
1483 pointerIds.markBit(entry->pointerProperties[0].id);
1484 }
1485 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1486 }
1487 }
1488 }
1489
1490 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1491 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001492 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493#if DEBUG_HOVER
1494 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001495 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496#endif
1497 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1498 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1499 }
1500
1501 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001502 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503#if DEBUG_HOVER
1504 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001505 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001506#endif
1507 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1508 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1509 }
1510 }
1511
1512 // Check permission to inject into all touched foreground windows and ensure there
1513 // is at least one touched foreground window.
1514 {
1515 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001516 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001517 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1518 haveForegroundWindow = true;
1519 if (! checkInjectionPermission(touchedWindow.windowHandle,
1520 entry->injectionState)) {
1521 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1522 injectionPermission = INJECTION_PERMISSION_DENIED;
1523 goto Failed;
1524 }
1525 }
1526 }
Michael Wright3dd60e22019-03-27 22:06:44 +00001527 bool hasGestureMonitor = !mTempTouchState.gestureMonitors.empty();
1528 if (!haveForegroundWindow && !hasGestureMonitor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001529#if DEBUG_FOCUS
Michael Wright3dd60e22019-03-27 22:06:44 +00001530 ALOGD("Dropping event because there is no touched foreground window in display %"
1531 PRId32 " or gesture monitor to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001532#endif
1533 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1534 goto Failed;
1535 }
1536
1537 // Permission granted to injection into all touched foreground windows.
1538 injectionPermission = INJECTION_PERMISSION_GRANTED;
1539 }
1540
1541 // Check whether windows listening for outside touches are owned by the same UID. If it is
1542 // set the policy flag that we will not reveal coordinate information to this window.
1543 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1544 sp<InputWindowHandle> foregroundWindowHandle =
1545 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001546 if (foregroundWindowHandle) {
1547 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
1548 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
1549 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1550 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1551 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1552 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1553 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1554 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 }
1556 }
1557 }
1558 }
1559
1560 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001561 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001563 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001564 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001565 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001566 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001567 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001568 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001569 goto Unresponsive;
1570 }
1571 }
1572 }
1573
1574 // If this is the first pointer going down and the touched window has a wallpaper
1575 // then also add the touched wallpaper windows so they are locked in for the duration
1576 // of the touch gesture.
1577 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1578 // engine only supports touch events. We would need to add a mechanism similar
1579 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1580 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1581 sp<InputWindowHandle> foregroundWindowHandle =
1582 mTempTouchState.getFirstForegroundWindowHandle();
Michael Wright3dd60e22019-03-27 22:06:44 +00001583 if (foregroundWindowHandle && foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001584 const std::vector<sp<InputWindowHandle>> windowHandles =
1585 getWindowHandlesLocked(displayId);
1586 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 const InputWindowInfo* info = windowHandle->getInfo();
1588 if (info->displayId == displayId
1589 && windowHandle->getInfo()->layoutParamsType
1590 == InputWindowInfo::TYPE_WALLPAPER) {
1591 mTempTouchState.addOrUpdateWindow(windowHandle,
1592 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001593 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001594 | InputTarget::FLAG_DISPATCH_AS_IS,
1595 BitSet32(0));
1596 }
1597 }
1598 }
1599 }
1600
1601 // Success! Output targets.
1602 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1603
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001604 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001605 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1606 touchedWindow.pointerIds, inputTargets);
1607 }
1608
Michael Wright3dd60e22019-03-27 22:06:44 +00001609 for (const TouchedMonitor& touchedMonitor : mTempTouchState.gestureMonitors) {
1610 addMonitoringTargetLocked(touchedMonitor.monitor, touchedMonitor.xOffset,
1611 touchedMonitor.yOffset, inputTargets);
1612 }
1613
Michael Wrightd02c5b62014-02-10 15:10:22 -08001614 // Drop the outside or hover touch windows since we will not care about them
1615 // in the next iteration.
1616 mTempTouchState.filterNonAsIsTouchWindows();
1617
1618Failed:
1619 // Check injection permission once and for all.
1620 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001621 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622 injectionPermission = INJECTION_PERMISSION_GRANTED;
1623 } else {
1624 injectionPermission = INJECTION_PERMISSION_DENIED;
1625 }
1626 }
1627
1628 // Update final pieces of touch state if the injector had permission.
1629 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1630 if (!wrongDevice) {
1631 if (switchedDevice) {
1632#if DEBUG_FOCUS
1633 ALOGD("Conflicting pointer actions: Switched to a different device.");
1634#endif
1635 *outConflictingPointerActions = true;
1636 }
1637
1638 if (isHoverAction) {
1639 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001640 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641#if DEBUG_FOCUS
1642 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1643#endif
1644 *outConflictingPointerActions = true;
1645 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001646 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1648 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001649 mTempTouchState.deviceId = entry->deviceId;
1650 mTempTouchState.source = entry->source;
1651 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001652 }
1653 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1654 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1655 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001656 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1658 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001659 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660#if DEBUG_FOCUS
1661 ALOGD("Conflicting pointer actions: Down received while already down.");
1662#endif
1663 *outConflictingPointerActions = true;
1664 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1666 // One pointer went up.
1667 if (isSplit) {
1668 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1669 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1670
1671 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001672 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1674 touchedWindow.pointerIds.clearBit(pointerId);
1675 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001676 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001677 continue;
1678 }
1679 }
1680 i += 1;
1681 }
1682 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001683 }
1684
1685 // Save changes unless the action was scroll in which case the temporary touch
1686 // state was only valid for this one action.
1687 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1688 if (mTempTouchState.displayId >= 0) {
1689 if (oldStateIndex >= 0) {
1690 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1691 } else {
1692 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1693 }
1694 } else if (oldStateIndex >= 0) {
1695 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001697 }
1698
1699 // Update hover state.
1700 mLastHoverWindowHandle = newHoverWindowHandle;
1701 }
1702 } else {
1703#if DEBUG_FOCUS
1704 ALOGD("Not updating touch focus because injection was denied.");
1705#endif
1706 }
1707
1708Unresponsive:
1709 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1710 mTempTouchState.reset();
1711
1712 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001713 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714#if DEBUG_FOCUS
1715 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1716 "timeSpentWaitingForApplication=%0.1fms",
1717 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1718#endif
1719 return injectionResult;
1720}
1721
1722void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001723 int32_t targetFlags, BitSet32 pointerIds, std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001724 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1725 if (inputChannel == nullptr) {
1726 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1727 return;
1728 }
1729
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001731 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001732 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001733 target.flags = targetFlags;
1734 target.xOffset = - windowInfo->frameLeft;
1735 target.yOffset = - windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001736 target.globalScaleFactor = windowInfo->globalScaleFactor;
1737 target.windowXScale = windowInfo->windowXScale;
1738 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001740 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741}
1742
Michael Wright3dd60e22019-03-27 22:06:44 +00001743void InputDispatcher::addGlobalMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
1744 int32_t displayId, float xOffset, float yOffset) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745
Michael Wright3dd60e22019-03-27 22:06:44 +00001746 std::unordered_map<int32_t, std::vector<Monitor>>::const_iterator it =
1747 mGlobalMonitorsByDisplay.find(displayId);
1748
1749 if (it != mGlobalMonitorsByDisplay.end()) {
1750 const std::vector<Monitor>& monitors = it->second;
1751 for (const Monitor& monitor : monitors) {
1752 addMonitoringTargetLocked(monitor, xOffset, yOffset, inputTargets);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001753 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001754 }
1755}
1756
Michael Wright3dd60e22019-03-27 22:06:44 +00001757void InputDispatcher::addMonitoringTargetLocked(const Monitor& monitor,
1758 float xOffset, float yOffset, std::vector<InputTarget>& inputTargets) {
1759 InputTarget target;
1760 target.inputChannel = monitor.inputChannel;
1761 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
1762 target.xOffset = xOffset;
1763 target.yOffset = yOffset;
1764 target.pointerIds.clear();
1765 target.globalScaleFactor = 1.0f;
1766 inputTargets.push_back(target);
1767}
1768
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1770 const InjectionState* injectionState) {
1771 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001772 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1774 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001775 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001776 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1777 "owned by uid %d",
1778 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001779 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 windowHandle->getInfo()->ownerUid);
1781 } else {
1782 ALOGW("Permission denied: injecting event from pid %d uid %d",
1783 injectionState->injectorPid, injectionState->injectorUid);
1784 }
1785 return false;
1786 }
1787 return true;
1788}
1789
1790bool InputDispatcher::isWindowObscuredAtPointLocked(
1791 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1792 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001793 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1794 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001795 if (otherHandle == windowHandle) {
1796 break;
1797 }
1798
1799 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1800 if (otherInfo->displayId == displayId
1801 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1802 && otherInfo->frameContainsPoint(x, y)) {
1803 return true;
1804 }
1805 }
1806 return false;
1807}
1808
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001809
1810bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1811 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001812 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001813 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001814 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001815 if (otherHandle == windowHandle) {
1816 break;
1817 }
1818
1819 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1820 if (otherInfo->displayId == displayId
1821 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1822 && otherInfo->overlaps(windowInfo)) {
1823 return true;
1824 }
1825 }
1826 return false;
1827}
1828
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001829std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001830 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1831 const char* targetType) {
1832 // If the window is paused then keep waiting.
1833 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001834 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001835 }
1836
1837 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001838 ssize_t connectionIndex = getConnectionIndexLocked(
1839 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001840 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001841 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001842 "registered with the input dispatcher. The window may be in the process "
1843 "of being removed.", targetType);
1844 }
1845
1846 // If the connection is dead then keep waiting.
1847 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1848 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001849 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001850 "The window may be in the process of being removed.", targetType,
1851 connection->getStatusLabel());
1852 }
1853
1854 // If the connection is backed up then keep waiting.
1855 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001856 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001857 "Outbound queue length: %d. Wait queue length: %d.",
1858 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1859 }
1860
1861 // Ensure that the dispatch queues aren't too far backed up for this event.
1862 if (eventEntry->type == EventEntry::TYPE_KEY) {
1863 // If the event is a key event, then we must wait for all previous events to
1864 // complete before delivering it because previous events may have the
1865 // side-effect of transferring focus to a different window and we want to
1866 // ensure that the following keys are sent to the new window.
1867 //
1868 // Suppose the user touches a button in a window then immediately presses "A".
1869 // If the button causes a pop-up window to appear then we want to ensure that
1870 // the "A" key is delivered to the new pop-up window. This is because users
1871 // often anticipate pending UI changes when typing on a keyboard.
1872 // To obtain this behavior, we must serialize key events with respect to all
1873 // prior input events.
1874 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001875 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001876 "finished processing all of the input events that were previously "
1877 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1878 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879 }
Jeff Brownffb49772014-10-10 19:01:34 -07001880 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 // Touch events can always be sent to a window immediately because the user intended
1882 // to touch whatever was visible at the time. Even if focus changes or a new
1883 // window appears moments later, the touch event was meant to be delivered to
1884 // whatever window happened to be on screen at the time.
1885 //
1886 // Generic motion events, such as trackball or joystick events are a little trickier.
1887 // Like key events, generic motion events are delivered to the focused window.
1888 // Unlike key events, generic motion events don't tend to transfer focus to other
1889 // windows and it is not important for them to be serialized. So we prefer to deliver
1890 // generic motion events as soon as possible to improve efficiency and reduce lag
1891 // through batching.
1892 //
1893 // The one case where we pause input event delivery is when the wait queue is piling
1894 // up with lots of events because the application is not responding.
1895 // This condition ensures that ANRs are detected reliably.
1896 if (!connection->waitQueue.isEmpty()
1897 && currentTime >= connection->waitQueue.head->deliveryTime
1898 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001899 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001900 "finished processing certain input events that were delivered to it over "
1901 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1902 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1903 connection->waitQueue.count(),
1904 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 }
1906 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001907 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908}
1909
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001910std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 const sp<InputApplicationHandle>& applicationHandle,
1912 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001913 if (applicationHandle != nullptr) {
1914 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001915 std::string label(applicationHandle->getName());
1916 label += " - ";
1917 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918 return label;
1919 } else {
1920 return applicationHandle->getName();
1921 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001922 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923 return windowHandle->getName();
1924 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001925 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 }
1927}
1928
1929void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001930 int32_t displayId = getTargetDisplayId(eventEntry);
1931 sp<InputWindowHandle> focusedWindowHandle =
1932 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1933 if (focusedWindowHandle != nullptr) {
1934 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1936#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001937 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938#endif
1939 return;
1940 }
1941 }
1942
1943 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1944 switch (eventEntry->type) {
1945 case EventEntry::TYPE_MOTION: {
1946 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1947 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1948 return;
1949 }
1950
1951 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1952 eventType = USER_ACTIVITY_EVENT_TOUCH;
1953 }
1954 break;
1955 }
1956 case EventEntry::TYPE_KEY: {
1957 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1958 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1959 return;
1960 }
1961 eventType = USER_ACTIVITY_EVENT_BUTTON;
1962 break;
1963 }
1964 }
1965
1966 CommandEntry* commandEntry = postCommandLocked(
1967 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1968 commandEntry->eventTime = eventEntry->eventTime;
1969 commandEntry->userActivityEventType = eventType;
1970}
1971
1972void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1973 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00001974 if (ATRACE_ENABLED()) {
1975 std::string message = StringPrintf(
1976 "prepareDispatchCycleLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
1977 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
1978 ATRACE_NAME(message.c_str());
1979 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980#if DEBUG_DISPATCH_CYCLE
1981 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Robert Carre07e1032018-11-26 12:55:53 -08001982 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1983 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001984 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001986 inputTarget->globalScaleFactor,
1987 inputTarget->windowXScale, inputTarget->windowYScale,
1988 inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989#endif
1990
1991 // Skip this event if the connection status is not normal.
1992 // We don't want to enqueue additional outbound events if the connection is broken.
1993 if (connection->status != Connection::STATUS_NORMAL) {
1994#if DEBUG_DISPATCH_CYCLE
1995 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001996 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997#endif
1998 return;
1999 }
2000
2001 // Split a motion event if needed.
2002 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
2003 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
2004
2005 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
2006 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
2007 MotionEntry* splitMotionEntry = splitMotionEvent(
2008 originalMotionEntry, inputTarget->pointerIds);
2009 if (!splitMotionEntry) {
2010 return; // split event was dropped
2011 }
2012#if DEBUG_FOCUS
2013 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002014 connection->getInputChannelName().c_str());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002015 logOutboundMotionDetails(" ", splitMotionEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016#endif
2017 enqueueDispatchEntriesLocked(currentTime, connection,
2018 splitMotionEntry, inputTarget);
2019 splitMotionEntry->release();
2020 return;
2021 }
2022 }
2023
2024 // Not splitting. Enqueue dispatch entries for the event as is.
2025 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
2026}
2027
2028void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
2029 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002030 if (ATRACE_ENABLED()) {
2031 std::string message = StringPrintf(
2032 "enqueueDispatchEntriesLocked(inputChannel=%s, sequenceNum=%" PRIu32 ")",
2033 connection->getInputChannelName().c_str(), eventEntry->sequenceNum);
2034 ATRACE_NAME(message.c_str());
2035 }
2036
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 bool wasEmpty = connection->outboundQueue.isEmpty();
2038
2039 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07002040 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002041 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002042 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07002044 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07002046 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07002048 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07002050 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
2052
2053 // If the outbound queue was previously empty, start the dispatch cycle going.
2054 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
2055 startDispatchCycleLocked(currentTime, connection);
2056 }
2057}
2058
chaviw8c9cf542019-03-25 13:02:48 -07002059void InputDispatcher::enqueueDispatchEntryLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
2061 int32_t dispatchMode) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002062 if (ATRACE_ENABLED()) {
2063 std::string message = StringPrintf(
2064 "enqueueDispatchEntry(inputChannel=%s, dispatchMode=%s)",
2065 connection->getInputChannelName().c_str(),
2066 dispatchModeToString(dispatchMode).c_str());
2067 ATRACE_NAME(message.c_str());
2068 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 int32_t inputTargetFlags = inputTarget->flags;
2070 if (!(inputTargetFlags & dispatchMode)) {
2071 return;
2072 }
2073 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
2074
2075 // This is a new event.
2076 // Enqueue a new dispatch entry onto the outbound queue for this connection.
2077 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
2078 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08002079 inputTarget->globalScaleFactor, inputTarget->windowXScale,
2080 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002081
2082 // Apply target flags and update the connection's input state.
2083 switch (eventEntry->type) {
2084 case EventEntry::TYPE_KEY: {
2085 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2086 dispatchEntry->resolvedAction = keyEntry->action;
2087 dispatchEntry->resolvedFlags = keyEntry->flags;
2088
2089 if (!connection->inputState.trackKey(keyEntry,
2090 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2091#if DEBUG_DISPATCH_CYCLE
2092 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002093 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094#endif
2095 delete dispatchEntry;
2096 return; // skip the inconsistent event
2097 }
2098 break;
2099 }
2100
2101 case EventEntry::TYPE_MOTION: {
2102 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2103 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2104 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2105 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2106 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2107 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2108 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2109 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2110 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2111 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2112 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2113 } else {
2114 dispatchEntry->resolvedAction = motionEntry->action;
2115 }
2116 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2117 && !connection->inputState.isHovering(
2118 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2119#if DEBUG_DISPATCH_CYCLE
2120 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002121 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122#endif
2123 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2124 }
2125
2126 dispatchEntry->resolvedFlags = motionEntry->flags;
2127 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2128 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2129 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002130 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2131 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2132 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002133
2134 if (!connection->inputState.trackMotion(motionEntry,
2135 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2136#if DEBUG_DISPATCH_CYCLE
2137 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002138 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002139#endif
2140 delete dispatchEntry;
2141 return; // skip the inconsistent event
2142 }
chaviw8c9cf542019-03-25 13:02:48 -07002143
2144 dispatchPointerDownOutsideFocusIfNecessary(motionEntry->source,
2145 dispatchEntry->resolvedAction, inputTarget->inputChannel->getToken());
2146
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 break;
2148 }
2149 }
2150
2151 // Remember that we are waiting for this dispatch to complete.
2152 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002153 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 }
2155
2156 // Enqueue the dispatch entry.
2157 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002158 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002159
2160}
2161
2162void InputDispatcher::dispatchPointerDownOutsideFocusIfNecessary(uint32_t source, int32_t action,
2163 const sp<IBinder>& newToken) {
2164 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2165 if (source != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
2166 return;
2167 }
2168
2169 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2170 if (inputWindowHandle == nullptr) {
2171 return;
2172 }
2173
2174 int32_t displayId = inputWindowHandle->getInfo()->displayId;
2175 sp<InputWindowHandle> focusedWindowHandle =
2176 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2177
2178 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2179
2180 if (!hasFocusChanged) {
2181 return;
2182 }
2183
2184 // Dispatch onPointerDownOutsideFocus to the policy.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002185}
2186
2187void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2188 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002189 if (ATRACE_ENABLED()) {
2190 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
2191 connection->getInputChannelName().c_str());
2192 ATRACE_NAME(message.c_str());
2193 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194#if DEBUG_DISPATCH_CYCLE
2195 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002196 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197#endif
2198
2199 while (connection->status == Connection::STATUS_NORMAL
2200 && !connection->outboundQueue.isEmpty()) {
2201 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2202 dispatchEntry->deliveryTime = currentTime;
2203
2204 // Publish the event.
2205 status_t status;
2206 EventEntry* eventEntry = dispatchEntry->eventEntry;
2207 switch (eventEntry->type) {
2208 case EventEntry::TYPE_KEY: {
2209 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2210
2211 // Publish the key event.
2212 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002213 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2215 keyEntry->keyCode, keyEntry->scanCode,
2216 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2217 keyEntry->eventTime);
2218 break;
2219 }
2220
2221 case EventEntry::TYPE_MOTION: {
2222 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2223
2224 PointerCoords scaledCoords[MAX_POINTERS];
2225 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2226
2227 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002228 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2230 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002231 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2232 float wxs = dispatchEntry->windowXScale;
2233 float wys = dispatchEntry->windowYScale;
2234 xOffset = dispatchEntry->xOffset * wxs;
2235 yOffset = dispatchEntry->yOffset * wys;
2236 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002237 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002238 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002239 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 }
2241 usingCoords = scaledCoords;
2242 }
2243 } else {
2244 xOffset = 0.0f;
2245 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246
2247 // We don't want the dispatch target to know.
2248 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002249 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 scaledCoords[i].clear();
2251 }
2252 usingCoords = scaledCoords;
2253 }
2254 }
2255
2256 // Publish the motion event.
2257 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002258 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002259 dispatchEntry->resolvedAction, motionEntry->actionButton,
2260 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002261 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification,
Michael Wright7b159c92015-05-14 14:48:03 +01002262 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 motionEntry->downTime, motionEntry->eventTime,
2264 motionEntry->pointerCount, motionEntry->pointerProperties,
2265 usingCoords);
2266 break;
2267 }
2268
2269 default:
2270 ALOG_ASSERT(false);
2271 return;
2272 }
2273
2274 // Check the result.
2275 if (status) {
2276 if (status == WOULD_BLOCK) {
2277 if (connection->waitQueue.isEmpty()) {
2278 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2279 "This is unexpected because the wait queue is empty, so the pipe "
2280 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002281 "event to it, status=%d", connection->getInputChannelName().c_str(),
2282 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2284 } else {
2285 // Pipe is full and we are waiting for the app to finish process some events
2286 // before sending more events to it.
2287#if DEBUG_DISPATCH_CYCLE
2288 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2289 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002290 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291#endif
2292 connection->inputPublisherBlocked = true;
2293 }
2294 } else {
2295 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002296 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2298 }
2299 return;
2300 }
2301
2302 // Re-enqueue the event on the wait queue.
2303 connection->outboundQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002304 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 connection->waitQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002306 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 }
2308}
2309
2310void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2311 const sp<Connection>& connection, uint32_t seq, bool handled) {
2312#if DEBUG_DISPATCH_CYCLE
2313 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002314 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315#endif
2316
2317 connection->inputPublisherBlocked = false;
2318
2319 if (connection->status == Connection::STATUS_BROKEN
2320 || connection->status == Connection::STATUS_ZOMBIE) {
2321 return;
2322 }
2323
2324 // Notify other system components and prepare to start the next dispatch cycle.
2325 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2326}
2327
2328void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2329 const sp<Connection>& connection, bool notify) {
2330#if DEBUG_DISPATCH_CYCLE
2331 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002332 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333#endif
2334
2335 // Clear the dispatch queues.
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002336 drainDispatchQueue(&connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002337 traceOutboundQueueLength(connection);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002338 drainDispatchQueue(&connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002339 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340
2341 // The connection appears to be unrecoverably broken.
2342 // Ignore already broken or zombie connections.
2343 if (connection->status == Connection::STATUS_NORMAL) {
2344 connection->status = Connection::STATUS_BROKEN;
2345
2346 if (notify) {
2347 // Notify other system components.
2348 onDispatchCycleBrokenLocked(currentTime, connection);
2349 }
2350 }
2351}
2352
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002353void InputDispatcher::drainDispatchQueue(Queue<DispatchEntry>* queue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354 while (!queue->isEmpty()) {
2355 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002356 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357 }
2358}
2359
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002360void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002362 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363 }
2364 delete dispatchEntry;
2365}
2366
2367int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2368 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2369
2370 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002371 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372
2373 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2374 if (connectionIndex < 0) {
2375 ALOGE("Received spurious receive callback for unknown input channel. "
2376 "fd=%d, events=0x%x", fd, events);
2377 return 0; // remove the callback
2378 }
2379
2380 bool notify;
2381 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2382 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2383 if (!(events & ALOOPER_EVENT_INPUT)) {
2384 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002385 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 return 1;
2387 }
2388
2389 nsecs_t currentTime = now();
2390 bool gotOne = false;
2391 status_t status;
2392 for (;;) {
2393 uint32_t seq;
2394 bool handled;
2395 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2396 if (status) {
2397 break;
2398 }
2399 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2400 gotOne = true;
2401 }
2402 if (gotOne) {
2403 d->runCommandsLockedInterruptible();
2404 if (status == WOULD_BLOCK) {
2405 return 1;
2406 }
2407 }
2408
2409 notify = status != DEAD_OBJECT || !connection->monitor;
2410 if (notify) {
2411 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002412 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 }
2414 } else {
2415 // Monitor channels are never explicitly unregistered.
2416 // We do it automatically when the remote endpoint is closed so don't warn
2417 // about them.
2418 notify = !connection->monitor;
2419 if (notify) {
2420 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002421 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
2423 }
2424
2425 // Unregister the channel.
2426 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2427 return 0; // remove the callback
2428 } // release lock
2429}
2430
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002431void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked (
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432 const CancelationOptions& options) {
2433 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2434 synthesizeCancelationEventsForConnectionLocked(
2435 mConnectionsByFd.valueAt(i), options);
2436 }
2437}
2438
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002439void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked (
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002440 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002441 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2442 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2443}
2444
2445void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2446 const CancelationOptions& options,
2447 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2448 for (const auto& it : monitorsByDisplay) {
2449 const std::vector<Monitor>& monitors = it.second;
2450 for (const Monitor& monitor : monitors) {
2451 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002452 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002453 }
2454}
2455
Michael Wrightd02c5b62014-02-10 15:10:22 -08002456void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2457 const sp<InputChannel>& channel, const CancelationOptions& options) {
2458 ssize_t index = getConnectionIndexLocked(channel);
2459 if (index >= 0) {
2460 synthesizeCancelationEventsForConnectionLocked(
2461 mConnectionsByFd.valueAt(index), options);
2462 }
2463}
2464
2465void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2466 const sp<Connection>& connection, const CancelationOptions& options) {
2467 if (connection->status == Connection::STATUS_BROKEN) {
2468 return;
2469 }
2470
2471 nsecs_t currentTime = now();
2472
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002473 std::vector<EventEntry*> cancelationEvents;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474 connection->inputState.synthesizeCancelationEvents(currentTime,
2475 cancelationEvents, options);
2476
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002477 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002479 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002481 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 options.reason, options.mode);
2483#endif
2484 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002485 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 switch (cancelationEventEntry->type) {
2487 case EventEntry::TYPE_KEY:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002488 logOutboundKeyDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 static_cast<KeyEntry*>(cancelationEventEntry));
2490 break;
2491 case EventEntry::TYPE_MOTION:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002492 logOutboundMotionDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 static_cast<MotionEntry*>(cancelationEventEntry));
2494 break;
2495 }
2496
2497 InputTarget target;
chaviwfbe5d9c2018-12-26 12:23:37 -08002498 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(
2499 connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002500 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2502 target.xOffset = -windowInfo->frameLeft;
2503 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002504 target.globalScaleFactor = windowInfo->globalScaleFactor;
2505 target.windowXScale = windowInfo->windowXScale;
2506 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507 } else {
2508 target.xOffset = 0;
2509 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002510 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002511 }
2512 target.inputChannel = connection->inputChannel;
2513 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2514
chaviw8c9cf542019-03-25 13:02:48 -07002515 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2517
2518 cancelationEventEntry->release();
2519 }
2520
2521 startDispatchCycleLocked(currentTime, connection);
2522 }
2523}
2524
2525InputDispatcher::MotionEntry*
2526InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2527 ALOG_ASSERT(pointerIds.value != 0);
2528
2529 uint32_t splitPointerIndexMap[MAX_POINTERS];
2530 PointerProperties splitPointerProperties[MAX_POINTERS];
2531 PointerCoords splitPointerCoords[MAX_POINTERS];
2532
2533 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2534 uint32_t splitPointerCount = 0;
2535
2536 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2537 originalPointerIndex++) {
2538 const PointerProperties& pointerProperties =
2539 originalMotionEntry->pointerProperties[originalPointerIndex];
2540 uint32_t pointerId = uint32_t(pointerProperties.id);
2541 if (pointerIds.hasBit(pointerId)) {
2542 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2543 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2544 splitPointerCoords[splitPointerCount].copyFrom(
2545 originalMotionEntry->pointerCoords[originalPointerIndex]);
2546 splitPointerCount += 1;
2547 }
2548 }
2549
2550 if (splitPointerCount != pointerIds.count()) {
2551 // This is bad. We are missing some of the pointers that we expected to deliver.
2552 // Most likely this indicates that we received an ACTION_MOVE events that has
2553 // different pointer ids than we expected based on the previous ACTION_DOWN
2554 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2555 // in this way.
2556 ALOGW("Dropping split motion event because the pointer count is %d but "
2557 "we expected there to be %d pointers. This probably means we received "
2558 "a broken sequence of pointer ids from the input device.",
2559 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002560 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 }
2562
2563 int32_t action = originalMotionEntry->action;
2564 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2565 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2566 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2567 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2568 const PointerProperties& pointerProperties =
2569 originalMotionEntry->pointerProperties[originalPointerIndex];
2570 uint32_t pointerId = uint32_t(pointerProperties.id);
2571 if (pointerIds.hasBit(pointerId)) {
2572 if (pointerIds.count() == 1) {
2573 // The first/last pointer went down/up.
2574 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2575 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2576 } else {
2577 // A secondary pointer went down/up.
2578 uint32_t splitPointerIndex = 0;
2579 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2580 splitPointerIndex += 1;
2581 }
2582 action = maskedAction | (splitPointerIndex
2583 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2584 }
2585 } else {
2586 // An unrelated pointer changed.
2587 action = AMOTION_EVENT_ACTION_MOVE;
2588 }
2589 }
2590
2591 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002592 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002593 originalMotionEntry->eventTime,
2594 originalMotionEntry->deviceId,
2595 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002596 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 originalMotionEntry->policyFlags,
2598 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002599 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 originalMotionEntry->flags,
2601 originalMotionEntry->metaState,
2602 originalMotionEntry->buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002603 originalMotionEntry->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604 originalMotionEntry->edgeFlags,
2605 originalMotionEntry->xPrecision,
2606 originalMotionEntry->yPrecision,
2607 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002608 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609
2610 if (originalMotionEntry->injectionState) {
2611 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2612 splitMotionEntry->injectionState->refCount += 1;
2613 }
2614
2615 return splitMotionEntry;
2616}
2617
2618void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2619#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002620 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621#endif
2622
2623 bool needWake;
2624 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002625 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626
Prabir Pradhan42611e02018-11-27 14:04:02 -08002627 ConfigurationChangedEntry* newEntry =
2628 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629 needWake = enqueueInboundEventLocked(newEntry);
2630 } // release lock
2631
2632 if (needWake) {
2633 mLooper->wake();
2634 }
2635}
2636
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002637/**
2638 * If one of the meta shortcuts is detected, process them here:
2639 * Meta + Backspace -> generate BACK
2640 * Meta + Enter -> generate HOME
2641 * This will potentially overwrite keyCode and metaState.
2642 */
2643void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2644 int32_t& keyCode, int32_t& metaState) {
2645 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2646 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2647 if (keyCode == AKEYCODE_DEL) {
2648 newKeyCode = AKEYCODE_BACK;
2649 } else if (keyCode == AKEYCODE_ENTER) {
2650 newKeyCode = AKEYCODE_HOME;
2651 }
2652 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002653 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002654 struct KeyReplacement replacement = {keyCode, deviceId};
2655 mReplacedKeys.add(replacement, newKeyCode);
2656 keyCode = newKeyCode;
2657 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2658 }
2659 } else if (action == AKEY_EVENT_ACTION_UP) {
2660 // In order to maintain a consistent stream of up and down events, check to see if the key
2661 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2662 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002663 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002664 struct KeyReplacement replacement = {keyCode, deviceId};
2665 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2666 if (index >= 0) {
2667 keyCode = mReplacedKeys.valueAt(index);
2668 mReplacedKeys.removeItemsAt(index);
2669 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2670 }
2671 }
2672}
2673
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2675#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002676 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002677 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002678 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002679 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002681 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682#endif
2683 if (!validateKeyEvent(args->action)) {
2684 return;
2685 }
2686
2687 uint32_t policyFlags = args->policyFlags;
2688 int32_t flags = args->flags;
2689 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002690 // InputDispatcher tracks and generates key repeats on behalf of
2691 // whatever notifies it, so repeatCount should always be set to 0
2692 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2694 policyFlags |= POLICY_FLAG_VIRTUAL;
2695 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 if (policyFlags & POLICY_FLAG_FUNCTION) {
2698 metaState |= AMETA_FUNCTION_ON;
2699 }
2700
2701 policyFlags |= POLICY_FLAG_TRUSTED;
2702
Michael Wright78f24442014-08-06 15:55:28 -07002703 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002704 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002705
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002707 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002708 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 args->downTime, args->eventTime);
2710
Michael Wright2b3c3302018-03-02 17:19:13 +00002711 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002713 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2714 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2715 std::to_string(t.duration().count()).c_str());
2716 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718 bool needWake;
2719 { // acquire lock
2720 mLock.lock();
2721
2722 if (shouldSendKeyToInputFilterLocked(args)) {
2723 mLock.unlock();
2724
2725 policyFlags |= POLICY_FLAG_FILTERED;
2726 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2727 return; // event was consumed by the filter
2728 }
2729
2730 mLock.lock();
2731 }
2732
Prabir Pradhan42611e02018-11-27 14:04:02 -08002733 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002734 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002735 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002736 metaState, repeatCount, args->downTime);
2737
2738 needWake = enqueueInboundEventLocked(newEntry);
2739 mLock.unlock();
2740 } // release lock
2741
2742 if (needWake) {
2743 mLooper->wake();
2744 }
2745}
2746
2747bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2748 return mInputFilterEnabled;
2749}
2750
2751void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2752#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002753 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2754 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002755 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002756 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2757 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002758 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002759 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760 for (uint32_t i = 0; i < args->pointerCount; i++) {
2761 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2762 "x=%f, y=%f, pressure=%f, size=%f, "
2763 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2764 "orientation=%f",
2765 i, args->pointerProperties[i].id,
2766 args->pointerProperties[i].toolType,
2767 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2768 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2769 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2770 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2771 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2772 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2773 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2774 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2775 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2776 }
2777#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002778 if (!validateMotionEvent(args->action, args->actionButton,
2779 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 return;
2781 }
2782
2783 uint32_t policyFlags = args->policyFlags;
2784 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002785
2786 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002787 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002788 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2789 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2790 std::to_string(t.duration().count()).c_str());
2791 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792
2793 bool needWake;
2794 { // acquire lock
2795 mLock.lock();
2796
2797 if (shouldSendMotionToInputFilterLocked(args)) {
2798 mLock.unlock();
2799
2800 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002801 event.initialize(args->deviceId, args->source, args->displayId,
2802 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002803 args->flags, args->edgeFlags, args->metaState, args->buttonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002804 args->classification, 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 args->downTime, args->eventTime,
2806 args->pointerCount, args->pointerProperties, args->pointerCoords);
2807
2808 policyFlags |= POLICY_FLAG_FILTERED;
2809 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2810 return; // event was consumed by the filter
2811 }
2812
2813 mLock.lock();
2814 }
2815
2816 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002817 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002818 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002819 args->action, args->actionButton, args->flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002820 args->metaState, args->buttonState, args->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002822 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823
2824 needWake = enqueueInboundEventLocked(newEntry);
2825 mLock.unlock();
2826 } // release lock
2827
2828 if (needWake) {
2829 mLooper->wake();
2830 }
2831}
2832
2833bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002834 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835}
2836
2837void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2838#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002839 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2840 "switchMask=0x%08x",
2841 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842#endif
2843
2844 uint32_t policyFlags = args->policyFlags;
2845 policyFlags |= POLICY_FLAG_TRUSTED;
2846 mPolicy->notifySwitch(args->eventTime,
2847 args->switchValues, args->switchMask, policyFlags);
2848}
2849
2850void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2851#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002852 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002853 args->eventTime, args->deviceId);
2854#endif
2855
2856 bool needWake;
2857 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002858 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859
Prabir Pradhan42611e02018-11-27 14:04:02 -08002860 DeviceResetEntry* newEntry =
2861 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862 needWake = enqueueInboundEventLocked(newEntry);
2863 } // release lock
2864
2865 if (needWake) {
2866 mLooper->wake();
2867 }
2868}
2869
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002870int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2872 uint32_t policyFlags) {
2873#if DEBUG_INBOUND_EVENT_DETAILS
2874 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002875 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2876 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877#endif
2878
2879 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2880
2881 policyFlags |= POLICY_FLAG_INJECTED;
2882 if (hasInjectionPermission(injectorPid, injectorUid)) {
2883 policyFlags |= POLICY_FLAG_TRUSTED;
2884 }
2885
2886 EventEntry* firstInjectedEntry;
2887 EventEntry* lastInjectedEntry;
2888 switch (event->getType()) {
2889 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002890 KeyEvent keyEvent;
2891 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2892 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893 if (! validateKeyEvent(action)) {
2894 return INPUT_EVENT_INJECTION_FAILED;
2895 }
2896
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002897 int32_t flags = keyEvent.getFlags();
2898 int32_t keyCode = keyEvent.getKeyCode();
2899 int32_t metaState = keyEvent.getMetaState();
2900 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2901 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002902 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002903 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002904 keyEvent.getDownTime(), keyEvent.getEventTime());
2905
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2907 policyFlags |= POLICY_FLAG_VIRTUAL;
2908 }
2909
2910 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002911 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002912 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002913 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2914 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2915 std::to_string(t.duration().count()).c_str());
2916 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917 }
2918
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002920 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002921 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002922 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002923 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2924 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925 lastInjectedEntry = firstInjectedEntry;
2926 break;
2927 }
2928
2929 case AINPUT_EVENT_TYPE_MOTION: {
2930 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 int32_t action = motionEvent->getAction();
2932 size_t pointerCount = motionEvent->getPointerCount();
2933 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002934 int32_t actionButton = motionEvent->getActionButton();
Charles Chen3611f1f2019-01-29 17:26:18 +08002935 int32_t displayId = motionEvent->getDisplayId();
Michael Wright7b159c92015-05-14 14:48:03 +01002936 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 return INPUT_EVENT_INJECTION_FAILED;
2938 }
2939
2940 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2941 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002942 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002943 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002944 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2945 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2946 std::to_string(t.duration().count()).c_str());
2947 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002948 }
2949
2950 mLock.lock();
2951 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2952 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002953 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002954 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2955 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002956 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002958 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002959 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002960 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002961 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2962 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002963 lastInjectedEntry = firstInjectedEntry;
2964 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2965 sampleEventTimes += 1;
2966 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002967 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2968 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002969 motionEvent->getDeviceId(), motionEvent->getSource(),
2970 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002971 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002973 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002975 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002976 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2977 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002978 lastInjectedEntry->next = nextInjectedEntry;
2979 lastInjectedEntry = nextInjectedEntry;
2980 }
2981 break;
2982 }
2983
2984 default:
2985 ALOGW("Cannot inject event of type %d", event->getType());
2986 return INPUT_EVENT_INJECTION_FAILED;
2987 }
2988
2989 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2990 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2991 injectionState->injectionIsAsync = true;
2992 }
2993
2994 injectionState->refCount += 1;
2995 lastInjectedEntry->injectionState = injectionState;
2996
2997 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002998 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002999 EventEntry* nextEntry = entry->next;
3000 needWake |= enqueueInboundEventLocked(entry);
3001 entry = nextEntry;
3002 }
3003
3004 mLock.unlock();
3005
3006 if (needWake) {
3007 mLooper->wake();
3008 }
3009
3010 int32_t injectionResult;
3011 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003012 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003013
3014 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3015 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3016 } else {
3017 for (;;) {
3018 injectionResult = injectionState->injectionResult;
3019 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3020 break;
3021 }
3022
3023 nsecs_t remainingTimeout = endTime - now();
3024 if (remainingTimeout <= 0) {
3025#if DEBUG_INJECTION
3026 ALOGD("injectInputEvent - Timed out waiting for injection result "
3027 "to become available.");
3028#endif
3029 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3030 break;
3031 }
3032
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003033 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003034 }
3035
3036 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
3037 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
3038 while (injectionState->pendingForegroundDispatches != 0) {
3039#if DEBUG_INJECTION
3040 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
3041 injectionState->pendingForegroundDispatches);
3042#endif
3043 nsecs_t remainingTimeout = endTime - now();
3044 if (remainingTimeout <= 0) {
3045#if DEBUG_INJECTION
3046 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3047 "dispatches to finish.");
3048#endif
3049 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3050 break;
3051 }
3052
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003053 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003054 }
3055 }
3056 }
3057
3058 injectionState->release();
3059 } // release lock
3060
3061#if DEBUG_INJECTION
3062 ALOGD("injectInputEvent - Finished with result %d. "
3063 "injectorPid=%d, injectorUid=%d",
3064 injectionResult, injectorPid, injectorUid);
3065#endif
3066
3067 return injectionResult;
3068}
3069
3070bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3071 return injectorUid == 0
3072 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3073}
3074
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003075void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003076 InjectionState* injectionState = entry->injectionState;
3077 if (injectionState) {
3078#if DEBUG_INJECTION
3079 ALOGD("Setting input event injection result to %d. "
3080 "injectorPid=%d, injectorUid=%d",
3081 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
3082#endif
3083
3084 if (injectionState->injectionIsAsync
3085 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
3086 // Log the outcome since the injector did not wait for the injection result.
3087 switch (injectionResult) {
3088 case INPUT_EVENT_INJECTION_SUCCEEDED:
3089 ALOGV("Asynchronous input event injection succeeded.");
3090 break;
3091 case INPUT_EVENT_INJECTION_FAILED:
3092 ALOGW("Asynchronous input event injection failed.");
3093 break;
3094 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3095 ALOGW("Asynchronous input event injection permission denied.");
3096 break;
3097 case INPUT_EVENT_INJECTION_TIMED_OUT:
3098 ALOGW("Asynchronous input event injection timed out.");
3099 break;
3100 }
3101 }
3102
3103 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003104 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003105 }
3106}
3107
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003108void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003109 InjectionState* injectionState = entry->injectionState;
3110 if (injectionState) {
3111 injectionState->pendingForegroundDispatches += 1;
3112 }
3113}
3114
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003115void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116 InjectionState* injectionState = entry->injectionState;
3117 if (injectionState) {
3118 injectionState->pendingForegroundDispatches -= 1;
3119
3120 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003121 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 }
3123 }
3124}
3125
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003126std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3127 int32_t displayId) const {
3128 std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>::const_iterator it =
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003129 mWindowHandlesByDisplay.find(displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003130 if(it != mWindowHandlesByDisplay.end()) {
3131 return it->second;
3132 }
3133
3134 // Return an empty one if nothing found.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003135 return std::vector<sp<InputWindowHandle>>();
Arthur Hungb92218b2018-08-14 12:00:21 +08003136}
3137
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003139 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003140 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003141 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3142 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003143 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003144 return windowHandle;
3145 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 }
3147 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003148 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149}
3150
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003151bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003152 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003153 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3154 for (const sp<InputWindowHandle>& handle : windowHandles) {
3155 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003156 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003157 ALOGE("Found window %s in display %" PRId32
3158 ", but it should belong to display %" PRId32,
3159 windowHandle->getName().c_str(), it.first,
3160 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003161 }
3162 return true;
3163 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 }
3165 }
3166 return false;
3167}
3168
Robert Carr5c8a0262018-10-03 16:30:44 -07003169sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3170 size_t count = mInputChannelsByToken.count(token);
3171 if (count == 0) {
3172 return nullptr;
3173 }
3174 return mInputChannelsByToken.at(token);
3175}
3176
Arthur Hungb92218b2018-08-14 12:00:21 +08003177/**
3178 * Called from InputManagerService, update window handle list by displayId that can receive input.
3179 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3180 * If set an empty list, remove all handles from the specific display.
3181 * For focused handle, check if need to change and send a cancel event to previous one.
3182 * For removed handle, check if need to send a cancel event if already in touch.
3183 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003184void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
chaviw291d88a2019-02-14 10:33:58 -08003185 int32_t displayId, const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003187 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188#endif
3189 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003190 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191
Arthur Hungb92218b2018-08-14 12:00:21 +08003192 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003193 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3194 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195
Tiger Huang721e26f2018-07-24 22:26:19 +08003196 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003198
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003199 if (inputWindowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003200 // Remove all handles on a display if there are no windows left.
3201 mWindowHandlesByDisplay.erase(displayId);
3202 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003203 // Since we compare the pointer of input window handles across window updates, we need
3204 // to make sure the handle object for the same window stays unchanged across updates.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003205 const std::vector<sp<InputWindowHandle>>& oldHandles =
3206 mWindowHandlesByDisplay[displayId];
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003207 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003208 for (const sp<InputWindowHandle>& handle : oldHandles) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003209 oldHandlesByTokens[handle->getToken()] = handle;
3210 }
3211
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003212 std::vector<sp<InputWindowHandle>> newHandles;
3213 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003214 if (!handle->updateInfo() || (getInputChannelLocked(handle->getToken()) == nullptr
3215 && handle->getInfo()->portalToDisplayId == ADISPLAY_ID_NONE)) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003216 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003217 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003218 continue;
3219 }
3220
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003221 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003222 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003223 handle->getName().c_str(), displayId,
3224 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003225 continue;
3226 }
3227
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003228 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3229 const sp<InputWindowHandle> oldHandle =
3230 oldHandlesByTokens.at(handle->getToken());
3231 oldHandle->updateFrom(handle);
3232 newHandles.push_back(oldHandle);
3233 } else {
3234 newHandles.push_back(handle);
3235 }
3236 }
3237
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003238 for (const sp<InputWindowHandle>& windowHandle : newHandles) {
Arthur Hung7ab76b12019-01-09 19:17:20 +08003239 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3240 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3241 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003242 newFocusedWindowHandle = windowHandle;
3243 }
3244 if (windowHandle == mLastHoverWindowHandle) {
3245 foundHoveredWindow = true;
3246 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003247 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003248
3249 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003250 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251 }
3252
3253 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003254 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 }
3256
Tiger Huang721e26f2018-07-24 22:26:19 +08003257 sp<InputWindowHandle> oldFocusedWindowHandle =
3258 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3259
3260 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3261 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003263 ALOGD("Focus left window: %s in display %" PRId32,
3264 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003266 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3267 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003268 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3270 "focus left window");
3271 synthesizeCancelationEventsForInputChannelLocked(
3272 focusedInputChannel, options);
3273 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003274 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003276 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003278 ALOGD("Focus entered window: %s in display %" PRId32,
3279 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003280#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003281 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003282 }
Robert Carrf759f162018-11-13 12:57:11 -08003283
3284 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003285 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003286 }
3287
Michael Wrightd02c5b62014-02-10 15:10:22 -08003288 }
3289
Arthur Hungb92218b2018-08-14 12:00:21 +08003290 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3291 if (stateIndex >= 0) {
3292 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003293 for (size_t i = 0; i < state.windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003294 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003295 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003297 ALOGD("Touched window was removed: %s in display %" PRId32,
3298 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003299#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003300 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003301 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003302 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003303 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3304 "touched window was removed");
3305 synthesizeCancelationEventsForInputChannelLocked(
3306 touchedInputChannel, options);
3307 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003308 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003309 } else {
3310 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 }
3313 }
3314
3315 // Release information for windows that are no longer present.
3316 // This ensures that unused input channels are released promptly.
3317 // Otherwise, they might stick around until the window handle is destroyed
3318 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003319 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003320 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003322 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003323#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003324 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 }
3326 }
3327 } // release lock
3328
3329 // Wake up poll loop since it may need to make new input dispatching choices.
3330 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003331
3332 if (setInputWindowsListener) {
3333 setInputWindowsListener->onSetInputWindowsFinished();
3334 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335}
3336
3337void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003338 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003340 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341#endif
3342 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003343 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344
Tiger Huang721e26f2018-07-24 22:26:19 +08003345 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3346 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003347 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003348 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3349 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003352 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003354 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003356 oldFocusedApplicationHandle.clear();
3357 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358 }
3359
3360#if DEBUG_FOCUS
3361 //logDispatchStateLocked();
3362#endif
3363 } // release lock
3364
3365 // Wake up poll loop since it may need to make new input dispatching choices.
3366 mLooper->wake();
3367}
3368
Tiger Huang721e26f2018-07-24 22:26:19 +08003369/**
3370 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3371 * the display not specified.
3372 *
3373 * We track any unreleased events for each window. If a window loses the ability to receive the
3374 * released event, we will send a cancel event to it. So when the focused display is changed, we
3375 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3376 * display. The display-specified events won't be affected.
3377 */
3378void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3379#if DEBUG_FOCUS
3380 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3381#endif
3382 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003383 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003384
3385 if (mFocusedDisplayId != displayId) {
3386 sp<InputWindowHandle> oldFocusedWindowHandle =
3387 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3388 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003389 sp<InputChannel> inputChannel =
3390 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003391 if (inputChannel != nullptr) {
3392 CancelationOptions options(
Michael Wright3dd60e22019-03-27 22:06:44 +00003393 CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Tiger Huang721e26f2018-07-24 22:26:19 +08003394 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003395 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003396 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3397 }
3398 }
3399 mFocusedDisplayId = displayId;
3400
3401 // Sanity check
3402 sp<InputWindowHandle> newFocusedWindowHandle =
3403 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003404 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003405
Tiger Huang721e26f2018-07-24 22:26:19 +08003406 if (newFocusedWindowHandle == nullptr) {
3407 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3408 if (!mFocusedWindowHandlesByDisplay.empty()) {
3409 ALOGE("But another display has a focused window:");
3410 for (auto& it : mFocusedWindowHandlesByDisplay) {
3411 const int32_t displayId = it.first;
3412 const sp<InputWindowHandle>& windowHandle = it.second;
3413 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3414 displayId, windowHandle->getName().c_str());
3415 }
3416 }
3417 }
3418 }
3419
3420#if DEBUG_FOCUS
3421 logDispatchStateLocked();
3422#endif
3423 } // release lock
3424
3425 // Wake up poll loop since it may need to make new input dispatching choices.
3426 mLooper->wake();
3427}
3428
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3430#if DEBUG_FOCUS
3431 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3432#endif
3433
3434 bool changed;
3435 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003436 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437
3438 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3439 if (mDispatchFrozen && !frozen) {
3440 resetANRTimeoutsLocked();
3441 }
3442
3443 if (mDispatchEnabled && !enabled) {
3444 resetAndDropEverythingLocked("dispatcher is being disabled");
3445 }
3446
3447 mDispatchEnabled = enabled;
3448 mDispatchFrozen = frozen;
3449 changed = true;
3450 } else {
3451 changed = false;
3452 }
3453
3454#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003455 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456#endif
3457 } // release lock
3458
3459 if (changed) {
3460 // Wake up poll loop since it may need to make new input dispatching choices.
3461 mLooper->wake();
3462 }
3463}
3464
3465void InputDispatcher::setInputFilterEnabled(bool enabled) {
3466#if DEBUG_FOCUS
3467 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3468#endif
3469
3470 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003471 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472
3473 if (mInputFilterEnabled == enabled) {
3474 return;
3475 }
3476
3477 mInputFilterEnabled = enabled;
3478 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3479 } // release lock
3480
3481 // Wake up poll loop since there might be work to do to drop everything.
3482 mLooper->wake();
3483}
3484
chaviwfbe5d9c2018-12-26 12:23:37 -08003485bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3486 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003488 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003490 return true;
3491 }
3492
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003494 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495
chaviwfbe5d9c2018-12-26 12:23:37 -08003496 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3497 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003498 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003499 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 return false;
3501 }
chaviw4f2dd402018-12-26 15:30:27 -08003502#if DEBUG_FOCUS
3503 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3504 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3505#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3507#if DEBUG_FOCUS
3508 ALOGD("Cannot transfer focus because windows are on different displays.");
3509#endif
3510 return false;
3511 }
3512
3513 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003514 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3515 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3516 for (size_t i = 0; i < state.windows.size(); i++) {
3517 const TouchedWindow& touchedWindow = state.windows[i];
3518 if (touchedWindow.windowHandle == fromWindowHandle) {
3519 int32_t oldTargetFlags = touchedWindow.targetFlags;
3520 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003522 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003523
Jeff Brownf086ddb2014-02-11 14:28:48 -08003524 int32_t newTargetFlags = oldTargetFlags
3525 & (InputTarget::FLAG_FOREGROUND
3526 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3527 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528
Jeff Brownf086ddb2014-02-11 14:28:48 -08003529 found = true;
3530 goto Found;
3531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 }
3533 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003534Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535
3536 if (! found) {
3537#if DEBUG_FOCUS
3538 ALOGD("Focus transfer failed because from window did not have focus.");
3539#endif
3540 return false;
3541 }
3542
chaviwfbe5d9c2018-12-26 12:23:37 -08003543
3544 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3545 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3547 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3548 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3549 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3550 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3551
3552 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3553 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3554 "transferring touch focus from this window to another window");
3555 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3556 }
3557
3558#if DEBUG_FOCUS
3559 logDispatchStateLocked();
3560#endif
3561 } // release lock
3562
3563 // Wake up poll loop since it may need to make new input dispatching choices.
3564 mLooper->wake();
3565 return true;
3566}
3567
3568void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3569#if DEBUG_FOCUS
3570 ALOGD("Resetting and dropping all events (%s).", reason);
3571#endif
3572
3573 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3574 synthesizeCancelationEventsForAllConnectionsLocked(options);
3575
3576 resetKeyRepeatLocked();
3577 releasePendingEventLocked();
3578 drainInboundQueueLocked();
3579 resetANRTimeoutsLocked();
3580
Jeff Brownf086ddb2014-02-11 14:28:48 -08003581 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003582 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003583 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003584}
3585
3586void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003587 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 dumpDispatchStateLocked(dump);
3589
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003590 std::istringstream stream(dump);
3591 std::string line;
3592
3593 while (std::getline(stream, line, '\n')) {
3594 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003595 }
3596}
3597
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003598void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3599 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3600 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003601 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602
Tiger Huang721e26f2018-07-24 22:26:19 +08003603 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3604 dump += StringPrintf(INDENT "FocusedApplications:\n");
3605 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3606 const int32_t displayId = it.first;
3607 const sp<InputApplicationHandle>& applicationHandle = it.second;
3608 dump += StringPrintf(
3609 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3610 displayId,
3611 applicationHandle->getName().c_str(),
3612 applicationHandle->getDispatchingTimeout(
3613 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3614 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003616 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003618
3619 if (!mFocusedWindowHandlesByDisplay.empty()) {
3620 dump += StringPrintf(INDENT "FocusedWindows:\n");
3621 for (auto& it : mFocusedWindowHandlesByDisplay) {
3622 const int32_t displayId = it.first;
3623 const sp<InputWindowHandle>& windowHandle = it.second;
3624 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3625 displayId, windowHandle->getName().c_str());
3626 }
3627 } else {
3628 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630
Jeff Brownf086ddb2014-02-11 14:28:48 -08003631 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003632 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003633 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3634 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003635 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003636 state.displayId, toString(state.down), toString(state.split),
3637 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003638 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003639 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003640 for (size_t i = 0; i < state.windows.size(); i++) {
3641 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003642 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3643 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003644 touchedWindow.pointerIds.value,
3645 touchedWindow.targetFlags);
3646 }
3647 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003648 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003649 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003650 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003651 dump += INDENT3 "Portal windows:\n";
3652 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003653 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003654 dump += StringPrintf(INDENT4 "%zu: name='%s'\n",
3655 i, portalWindowHandle->getName().c_str());
3656 }
3657 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 }
3659 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003660 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 }
3662
Arthur Hungb92218b2018-08-14 12:00:21 +08003663 if (!mWindowHandlesByDisplay.empty()) {
3664 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003665 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003666 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003667 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003668 dump += INDENT2 "Windows:\n";
3669 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003670 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003671 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003672
Arthur Hungb92218b2018-08-14 12:00:21 +08003673 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003674 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, "
Arthur Hungb92218b2018-08-14 12:00:21 +08003675 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003676 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003677 "touchableRegion=",
3678 i, windowInfo->name.c_str(), windowInfo->displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003679 windowInfo->portalToDisplayId,
Arthur Hungb92218b2018-08-14 12:00:21 +08003680 toString(windowInfo->paused),
3681 toString(windowInfo->hasFocus),
3682 toString(windowInfo->hasWallpaper),
3683 toString(windowInfo->visible),
3684 toString(windowInfo->canReceiveKeys),
3685 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3686 windowInfo->layer,
3687 windowInfo->frameLeft, windowInfo->frameTop,
3688 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003689 windowInfo->globalScaleFactor,
3690 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003691 dumpRegion(dump, windowInfo->touchableRegion);
3692 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3693 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3694 windowInfo->ownerPid, windowInfo->ownerUid,
3695 windowInfo->dispatchingTimeout / 1000000.0);
3696 }
3697 } else {
3698 dump += INDENT2 "Windows: <none>\n";
3699 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 }
3701 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003702 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 }
3704
Michael Wright3dd60e22019-03-27 22:06:44 +00003705 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
3706 for (auto& it : mGlobalMonitorsByDisplay) {
3707 const std::vector<Monitor>& monitors = it.second;
3708 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3709 dumpMonitors(dump, monitors);
3710 }
3711 for (auto& it : mGestureMonitorsByDisplay) {
3712 const std::vector<Monitor>& monitors = it.second;
3713 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3714 dumpMonitors(dump, monitors);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003715 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003717 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 }
3719
3720 nsecs_t currentTime = now();
3721
3722 // Dump recently dispatched or dropped events from oldest to newest.
3723 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003724 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003725 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003726 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003728 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 (currentTime - entry->eventTime) * 0.000001f);
3730 }
3731 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003732 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 }
3734
3735 // Dump event currently being dispatched.
3736 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003737 dump += INDENT "PendingEvent:\n";
3738 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003740 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003741 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3742 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003743 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 }
3745
3746 // Dump inbound events from oldest to newest.
3747 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003748 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003750 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003752 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 (currentTime - entry->eventTime) * 0.000001f);
3754 }
3755 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003756 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757 }
3758
Michael Wright78f24442014-08-06 15:55:28 -07003759 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003760 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003761 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3762 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3763 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003764 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003765 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3766 }
3767 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003768 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003769 }
3770
Michael Wrightd02c5b62014-02-10 15:10:22 -08003771 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003772 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3774 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003775 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003776 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003777 i, connection->getInputChannelName().c_str(),
3778 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779 connection->getStatusLabel(), toString(connection->monitor),
3780 toString(connection->inputPublisherBlocked));
3781
3782 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003783 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003784 connection->outboundQueue.count());
3785 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3786 entry = entry->next) {
3787 dump.append(INDENT4);
3788 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003789 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003790 entry->targetFlags, entry->resolvedAction,
3791 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3792 }
3793 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003794 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795 }
3796
3797 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003798 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 connection->waitQueue.count());
3800 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3801 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003802 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003803 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003804 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 "age=%0.1fms, wait=%0.1fms\n",
3806 entry->targetFlags, entry->resolvedAction,
3807 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3808 (currentTime - entry->deliveryTime) * 0.000001f);
3809 }
3810 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003811 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 }
3813 }
3814 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003815 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003816 }
3817
3818 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003819 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 (mAppSwitchDueTime - now()) / 1000000.0);
3821 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003822 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003823 }
3824
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003825 dump += INDENT "Configuration:\n";
3826 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003828 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003829 mConfig.keyRepeatTimeout * 0.000001f);
3830}
3831
Michael Wright3dd60e22019-03-27 22:06:44 +00003832void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3833 const size_t numMonitors = monitors.size();
3834 for (size_t i = 0; i < numMonitors; i++) {
3835 const Monitor& monitor = monitors[i];
3836 const sp<InputChannel>& channel = monitor.inputChannel;
3837 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3838 dump += "\n";
3839 }
3840}
3841
3842status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3843 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003845 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3846 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003847#endif
3848
3849 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003850 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851
3852 if (getConnectionIndexLocked(inputChannel) >= 0) {
3853 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003854 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003855 return BAD_VALUE;
3856 }
3857
Michael Wright3dd60e22019-03-27 22:06:44 +00003858 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859
3860 int fd = inputChannel->getFd();
3861 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003862 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863
Michael Wrightd02c5b62014-02-10 15:10:22 -08003864 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3865 } // release lock
3866
3867 // Wake the looper because some connections have changed.
3868 mLooper->wake();
3869 return OK;
3870}
3871
Michael Wright3dd60e22019-03-27 22:06:44 +00003872status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
3873 int32_t displayId, bool isGestureMonitor) {
3874 { // acquire lock
3875 std::scoped_lock _l(mLock);
3876
3877 if (displayId < 0) {
3878 ALOGW("Attempted to register input monitor without a specified display.");
3879 return BAD_VALUE;
3880 }
3881
3882 if (inputChannel->getToken() == nullptr) {
3883 ALOGW("Attempted to register input monitor without an identifying token.");
3884 return BAD_VALUE;
3885 }
3886
3887 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3888
3889 const int fd = inputChannel->getFd();
3890 mConnectionsByFd.add(fd, connection);
3891 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
3892
3893 auto& monitorsByDisplay = isGestureMonitor
3894 ? mGestureMonitorsByDisplay
3895 : mGlobalMonitorsByDisplay;
3896 monitorsByDisplay[displayId].emplace_back(inputChannel);
3897
3898 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3899
3900 }
3901 // Wake the looper because some connections have changed.
3902 mLooper->wake();
3903 return OK;
3904}
3905
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3907#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003908 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003909#endif
3910
3911 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003912 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003913
3914 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3915 if (status) {
3916 return status;
3917 }
3918 } // release lock
3919
3920 // Wake the poll loop because removing the connection may have changed the current
3921 // synchronization state.
3922 mLooper->wake();
3923 return OK;
3924}
3925
3926status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3927 bool notify) {
3928 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3929 if (connectionIndex < 0) {
3930 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003931 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932 return BAD_VALUE;
3933 }
3934
3935 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3936 mConnectionsByFd.removeItemsAt(connectionIndex);
3937
Robert Carr5c8a0262018-10-03 16:30:44 -07003938 mInputChannelsByToken.erase(inputChannel->getToken());
3939
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 if (connection->monitor) {
3941 removeMonitorChannelLocked(inputChannel);
3942 }
3943
3944 mLooper->removeFd(inputChannel->getFd());
3945
3946 nsecs_t currentTime = now();
3947 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3948
3949 connection->status = Connection::STATUS_ZOMBIE;
3950 return OK;
3951}
3952
3953void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003954 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
3955 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
3956}
3957
3958void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel,
3959 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3960 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end(); ) {
3961 std::vector<Monitor>& monitors = it->second;
3962 const size_t numMonitors = monitors.size();
3963 for (size_t i = 0; i < numMonitors; i++) {
3964 if (monitors[i].inputChannel == inputChannel) {
3965 monitors.erase(monitors.begin() + i);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003966 break;
3967 }
3968 }
Michael Wright3dd60e22019-03-27 22:06:44 +00003969 if (monitors.empty()) {
3970 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003971 } else {
3972 ++it;
3973 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 }
3975}
3976
Michael Wright3dd60e22019-03-27 22:06:44 +00003977status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
3978 { // acquire lock
3979 std::scoped_lock _l(mLock);
3980 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
3981
3982 if (!foundDisplayId) {
3983 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
3984 return BAD_VALUE;
3985 }
3986 int32_t displayId = foundDisplayId.value();
3987
3988 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3989 if (stateIndex < 0) {
3990 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
3991 return BAD_VALUE;
3992 }
3993
3994 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
3995 std::optional<int32_t> foundDeviceId;
3996 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
3997 if (touchedMonitor.monitor.inputChannel->getToken() == token) {
3998 foundDeviceId = state.deviceId;
3999 }
4000 }
4001 if (!foundDeviceId || !state.down) {
4002 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
4003 " Ignoring.");
4004 return BAD_VALUE;
4005 }
4006 int32_t deviceId = foundDeviceId.value();
4007
4008 // Send cancel events to all the input channels we're stealing from.
4009 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4010 "gesture monitor stole pointer stream");
4011 options.deviceId = deviceId;
4012 options.displayId = displayId;
4013 for (const TouchedWindow& window : state.windows) {
4014 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
4015 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4016 }
4017 // Then clear the current touch state so we stop dispatching to them as well.
4018 state.filterNonMonitors();
4019 }
4020 return OK;
4021}
4022
4023
4024std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4025 const sp<IBinder>& token) {
4026 for (const auto& it : mGestureMonitorsByDisplay) {
4027 const std::vector<Monitor>& monitors = it.second;
4028 for (const Monitor& monitor : monitors) {
4029 if (monitor.inputChannel->getToken() == token) {
4030 return it.first;
4031 }
4032 }
4033 }
4034 return std::nullopt;
4035}
4036
Michael Wrightd02c5b62014-02-10 15:10:22 -08004037ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07004038 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08004039 return -1;
4040 }
4041
Robert Carr4e670e52018-08-15 13:26:12 -07004042 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
4043 sp<Connection> connection = mConnectionsByFd.valueAt(i);
4044 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
4045 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046 }
4047 }
Robert Carr4e670e52018-08-15 13:26:12 -07004048
Michael Wrightd02c5b62014-02-10 15:10:22 -08004049 return -1;
4050}
4051
4052void InputDispatcher::onDispatchCycleFinishedLocked(
4053 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
4054 CommandEntry* commandEntry = postCommandLocked(
4055 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
4056 commandEntry->connection = connection;
4057 commandEntry->eventTime = currentTime;
4058 commandEntry->seq = seq;
4059 commandEntry->handled = handled;
4060}
4061
4062void InputDispatcher::onDispatchCycleBrokenLocked(
4063 nsecs_t currentTime, const sp<Connection>& connection) {
4064 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004065 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004066
4067 CommandEntry* commandEntry = postCommandLocked(
4068 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
4069 commandEntry->connection = connection;
4070}
4071
chaviw0c06c6e2019-01-09 13:27:07 -08004072void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
4073 const sp<InputWindowHandle>& newFocus) {
4074 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4075 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08004076 CommandEntry* commandEntry = postCommandLocked(
4077 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004078 commandEntry->oldToken = oldToken;
4079 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004080}
4081
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082void InputDispatcher::onANRLocked(
4083 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
4084 const sp<InputWindowHandle>& windowHandle,
4085 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
4086 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4087 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4088 ALOGI("Application is not responding: %s. "
4089 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004090 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 dispatchLatency, waitDuration, reason);
4092
4093 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004094 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004095 struct tm tm;
4096 localtime_r(&t, &tm);
4097 char timestr[64];
4098 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4099 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004100 mLastANRState += INDENT "ANR:\n";
4101 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4102 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004103 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004104 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4105 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4106 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 dumpDispatchStateLocked(mLastANRState);
4108
4109 CommandEntry* commandEntry = postCommandLocked(
4110 & InputDispatcher::doNotifyANRLockedInterruptible);
4111 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07004112 commandEntry->inputChannel = windowHandle != nullptr ?
4113 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 commandEntry->reason = reason;
4115}
4116
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004117void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible (
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 CommandEntry* commandEntry) {
4119 mLock.unlock();
4120
4121 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4122
4123 mLock.lock();
4124}
4125
4126void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
4127 CommandEntry* commandEntry) {
4128 sp<Connection> connection = commandEntry->connection;
4129
4130 if (connection->status != Connection::STATUS_ZOMBIE) {
4131 mLock.unlock();
4132
Robert Carr803535b2018-08-02 16:38:15 -07004133 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004134
4135 mLock.lock();
4136 }
4137}
4138
Robert Carrf759f162018-11-13 12:57:11 -08004139void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
4140 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004141 sp<IBinder> oldToken = commandEntry->oldToken;
4142 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004143 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004144 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004145 mLock.lock();
4146}
4147
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148void InputDispatcher::doNotifyANRLockedInterruptible(
4149 CommandEntry* commandEntry) {
4150 mLock.unlock();
4151
4152 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07004153 commandEntry->inputApplicationHandle,
4154 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 commandEntry->reason);
4156
4157 mLock.lock();
4158
4159 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07004160 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161}
4162
4163void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4164 CommandEntry* commandEntry) {
4165 KeyEntry* entry = commandEntry->keyEntry;
4166
4167 KeyEvent event;
4168 initializeKeyEvent(&event, entry);
4169
4170 mLock.unlock();
4171
Michael Wright2b3c3302018-03-02 17:19:13 +00004172 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07004173 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
4174 commandEntry->inputChannel->getToken() : nullptr;
4175 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004177 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4178 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
4179 std::to_string(t.duration().count()).c_str());
4180 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181
4182 mLock.lock();
4183
4184 if (delay < 0) {
4185 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4186 } else if (!delay) {
4187 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4188 } else {
4189 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4190 entry->interceptKeyWakeupTime = now() + delay;
4191 }
4192 entry->release();
4193}
4194
4195void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
4196 CommandEntry* commandEntry) {
4197 sp<Connection> connection = commandEntry->connection;
4198 nsecs_t finishTime = commandEntry->eventTime;
4199 uint32_t seq = commandEntry->seq;
4200 bool handled = commandEntry->handled;
4201
4202 // Handle post-event policy actions.
4203 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4204 if (dispatchEntry) {
4205 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4206 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004207 std::string msg =
4208 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004209 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004211 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 }
4213
4214 bool restartEvent;
4215 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4216 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4217 restartEvent = afterKeyEventLockedInterruptible(connection,
4218 dispatchEntry, keyEntry, handled);
4219 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4220 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4221 restartEvent = afterMotionEventLockedInterruptible(connection,
4222 dispatchEntry, motionEntry, handled);
4223 } else {
4224 restartEvent = false;
4225 }
4226
4227 // Dequeue the event and start the next cycle.
4228 // Note that because the lock might have been released, it is possible that the
4229 // contents of the wait queue to have been drained, so we need to double-check
4230 // a few things.
4231 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4232 connection->waitQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004233 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4235 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004236 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 } else {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08004238 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239 }
4240 }
4241
4242 // Start the next dispatch cycle for this connection.
4243 startDispatchCycleLocked(now(), connection);
4244 }
4245}
4246
4247bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4248 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004249 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004250 if (!handled) {
4251 // Report the key as unhandled, since the fallback was not handled.
4252 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4253 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004254 return false;
4255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004257 // Get the fallback key state.
4258 // Clear it out after dispatching the UP.
4259 int32_t originalKeyCode = keyEntry->keyCode;
4260 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4261 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4262 connection->inputState.removeFallbackKey(originalKeyCode);
4263 }
4264
4265 if (handled || !dispatchEntry->hasForegroundTarget()) {
4266 // If the application handles the original key for which we previously
4267 // generated a fallback or if the window is not a foreground window,
4268 // then cancel the associated fallback key, if any.
4269 if (fallbackKeyCode != -1) {
4270 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004272 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4274 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4275 keyEntry->policyFlags);
4276#endif
4277 KeyEvent event;
4278 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004279 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280
4281 mLock.unlock();
4282
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004283 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4284 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285
4286 mLock.lock();
4287
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004288 // Cancel the fallback key.
4289 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004291 "application handled the original non-fallback key "
4292 "or is no longer a foreground target, "
4293 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 options.keyCode = fallbackKeyCode;
4295 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004297 connection->inputState.removeFallbackKey(originalKeyCode);
4298 }
4299 } else {
4300 // If the application did not handle a non-fallback key, first check
4301 // that we are in a good state to perform unhandled key event processing
4302 // Then ask the policy what to do with it.
4303 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4304 && keyEntry->repeatCount == 0;
4305 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004307 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4308 "since this is not an initial down. "
4309 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4310 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4311 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004313 return false;
4314 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004316 // Dispatch the unhandled key to the policy.
4317#if DEBUG_OUTBOUND_EVENT_DETAILS
4318 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4319 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4320 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4321 keyEntry->policyFlags);
4322#endif
4323 KeyEvent event;
4324 initializeKeyEvent(&event, keyEntry);
4325
4326 mLock.unlock();
4327
4328 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4329 &event, keyEntry->policyFlags, &event);
4330
4331 mLock.lock();
4332
4333 if (connection->status != Connection::STATUS_NORMAL) {
4334 connection->inputState.removeFallbackKey(originalKeyCode);
4335 return false;
4336 }
4337
4338 // Latch the fallback keycode for this key on an initial down.
4339 // The fallback keycode cannot change at any other point in the lifecycle.
4340 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004342 fallbackKeyCode = event.getKeyCode();
4343 } else {
4344 fallbackKeyCode = AKEYCODE_UNKNOWN;
4345 }
4346 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4347 }
4348
4349 ALOG_ASSERT(fallbackKeyCode != -1);
4350
4351 // Cancel the fallback key if the policy decides not to send it anymore.
4352 // We will continue to dispatch the key to the policy but we will no
4353 // longer dispatch a fallback key to the application.
4354 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4355 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4356#if DEBUG_OUTBOUND_EVENT_DETAILS
4357 if (fallback) {
4358 ALOGD("Unhandled key event: Policy requested to send key %d"
4359 "as a fallback for %d, but on the DOWN it had requested "
4360 "to send %d instead. Fallback canceled.",
4361 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4362 } else {
4363 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4364 "but on the DOWN it had requested to send %d. "
4365 "Fallback canceled.",
4366 originalKeyCode, fallbackKeyCode);
4367 }
4368#endif
4369
4370 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4371 "canceling fallback, policy no longer desires it");
4372 options.keyCode = fallbackKeyCode;
4373 synthesizeCancelationEventsForConnectionLocked(connection, options);
4374
4375 fallback = false;
4376 fallbackKeyCode = AKEYCODE_UNKNOWN;
4377 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4378 connection->inputState.setFallbackKey(originalKeyCode,
4379 fallbackKeyCode);
4380 }
4381 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382
4383#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004384 {
4385 std::string msg;
4386 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4387 connection->inputState.getFallbackKeys();
4388 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4389 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4390 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004392 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4393 fallbackKeys.size(), msg.c_str());
4394 }
4395#endif
4396
4397 if (fallback) {
4398 // Restart the dispatch cycle using the fallback key.
4399 keyEntry->eventTime = event.getEventTime();
4400 keyEntry->deviceId = event.getDeviceId();
4401 keyEntry->source = event.getSource();
4402 keyEntry->displayId = event.getDisplayId();
4403 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4404 keyEntry->keyCode = fallbackKeyCode;
4405 keyEntry->scanCode = event.getScanCode();
4406 keyEntry->metaState = event.getMetaState();
4407 keyEntry->repeatCount = event.getRepeatCount();
4408 keyEntry->downTime = event.getDownTime();
4409 keyEntry->syntheticRepeat = false;
4410
4411#if DEBUG_OUTBOUND_EVENT_DETAILS
4412 ALOGD("Unhandled key event: Dispatching fallback key. "
4413 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4414 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4415#endif
4416 return true; // restart the event
4417 } else {
4418#if DEBUG_OUTBOUND_EVENT_DETAILS
4419 ALOGD("Unhandled key event: No fallback key.");
4420#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004421
4422 // Report the key as unhandled, since there is no fallback key.
4423 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004424 }
4425 }
4426 return false;
4427}
4428
4429bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4430 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4431 return false;
4432}
4433
4434void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4435 mLock.unlock();
4436
4437 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4438
4439 mLock.lock();
4440}
4441
4442void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004443 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4445 entry->downTime, entry->eventTime);
4446}
4447
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004448void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004449 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4450 // TODO Write some statistics about how long we spend waiting.
4451}
4452
4453void InputDispatcher::traceInboundQueueLengthLocked() {
4454 if (ATRACE_ENABLED()) {
4455 ATRACE_INT("iq", mInboundQueue.count());
4456 }
4457}
4458
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004459void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460 if (ATRACE_ENABLED()) {
4461 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004462 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004463 ATRACE_INT(counterName, connection->outboundQueue.count());
4464 }
4465}
4466
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004467void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004468 if (ATRACE_ENABLED()) {
4469 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004470 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004471 ATRACE_INT(counterName, connection->waitQueue.count());
4472 }
4473}
4474
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004475void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004476 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004477
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004478 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 dumpDispatchStateLocked(dump);
4480
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004481 if (!mLastANRState.empty()) {
4482 dump += "\nInput Dispatcher State at time of last ANR:\n";
4483 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 }
4485}
4486
4487void InputDispatcher::monitor() {
4488 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004489 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004490 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004491 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492}
4493
4494
Michael Wrightd02c5b62014-02-10 15:10:22 -08004495// --- InputDispatcher::InjectionState ---
4496
4497InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4498 refCount(1),
4499 injectorPid(injectorPid), injectorUid(injectorUid),
4500 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4501 pendingForegroundDispatches(0) {
4502}
4503
4504InputDispatcher::InjectionState::~InjectionState() {
4505}
4506
4507void InputDispatcher::InjectionState::release() {
4508 refCount -= 1;
4509 if (refCount == 0) {
4510 delete this;
4511 } else {
4512 ALOG_ASSERT(refCount > 0);
4513 }
4514}
4515
4516
4517// --- InputDispatcher::EventEntry ---
4518
Prabir Pradhan42611e02018-11-27 14:04:02 -08004519InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4520 nsecs_t eventTime, uint32_t policyFlags) :
4521 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4522 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004523}
4524
4525InputDispatcher::EventEntry::~EventEntry() {
4526 releaseInjectionState();
4527}
4528
4529void InputDispatcher::EventEntry::release() {
4530 refCount -= 1;
4531 if (refCount == 0) {
4532 delete this;
4533 } else {
4534 ALOG_ASSERT(refCount > 0);
4535 }
4536}
4537
4538void InputDispatcher::EventEntry::releaseInjectionState() {
4539 if (injectionState) {
4540 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004541 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542 }
4543}
4544
4545
4546// --- InputDispatcher::ConfigurationChangedEntry ---
4547
Prabir Pradhan42611e02018-11-27 14:04:02 -08004548InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4549 uint32_t sequenceNum, nsecs_t eventTime) :
4550 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004551}
4552
4553InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4554}
4555
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004556void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4557 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004558}
4559
4560
4561// --- InputDispatcher::DeviceResetEntry ---
4562
Prabir Pradhan42611e02018-11-27 14:04:02 -08004563InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4564 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4565 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004566 deviceId(deviceId) {
4567}
4568
4569InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4570}
4571
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004572void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4573 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574 deviceId, policyFlags);
4575}
4576
4577
4578// --- InputDispatcher::KeyEntry ---
4579
Prabir Pradhan42611e02018-11-27 14:04:02 -08004580InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004581 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004582 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4583 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004584 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004585 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004586 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4587 repeatCount(repeatCount), downTime(downTime),
4588 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4589 interceptKeyWakeupTime(0) {
4590}
4591
4592InputDispatcher::KeyEntry::~KeyEntry() {
4593}
4594
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004595void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004596 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4598 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004599 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004600 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601}
4602
4603void InputDispatcher::KeyEntry::recycle() {
4604 releaseInjectionState();
4605
4606 dispatchInProgress = false;
4607 syntheticRepeat = false;
4608 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4609 interceptKeyWakeupTime = 0;
4610}
4611
4612
4613// --- InputDispatcher::MotionEntry ---
4614
Prabir Pradhan42611e02018-11-27 14:04:02 -08004615InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004616 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4617 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004618 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4619 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004620 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004621 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4622 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004623 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004624 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004625 deviceId(deviceId), source(source), displayId(displayId), action(action),
4626 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004627 classification(classification), edgeFlags(edgeFlags),
4628 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004629 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 for (uint32_t i = 0; i < pointerCount; i++) {
4631 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4632 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004633 if (xOffset || yOffset) {
4634 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4635 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636 }
4637}
4638
4639InputDispatcher::MotionEntry::~MotionEntry() {
4640}
4641
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004642void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004643 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004644 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004645 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004646 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004647 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4648 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004649
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 for (uint32_t i = 0; i < pointerCount; i++) {
4651 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004652 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004654 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655 pointerCoords[i].getX(), pointerCoords[i].getY());
4656 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004657 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658}
4659
4660
4661// --- InputDispatcher::DispatchEntry ---
4662
4663volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4664
4665InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004666 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4667 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004668 seq(nextSeq()),
4669 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004670 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4671 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004672 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4673 eventEntry->refCount += 1;
4674}
4675
4676InputDispatcher::DispatchEntry::~DispatchEntry() {
4677 eventEntry->release();
4678}
4679
4680uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4681 // Sequence number 0 is reserved and will never be returned.
4682 uint32_t seq;
4683 do {
4684 seq = android_atomic_inc(&sNextSeqAtomic);
4685 } while (!seq);
4686 return seq;
4687}
4688
4689
4690// --- InputDispatcher::InputState ---
4691
4692InputDispatcher::InputState::InputState() {
4693}
4694
4695InputDispatcher::InputState::~InputState() {
4696}
4697
4698bool InputDispatcher::InputState::isNeutral() const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004699 return mKeyMementos.empty() && mMotionMementos.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700}
4701
4702bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4703 int32_t displayId) const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004704 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705 if (memento.deviceId == deviceId
4706 && memento.source == source
4707 && memento.displayId == displayId
4708 && memento.hovering) {
4709 return true;
4710 }
4711 }
4712 return false;
4713}
4714
4715bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4716 int32_t action, int32_t flags) {
4717 switch (action) {
4718 case AKEY_EVENT_ACTION_UP: {
4719 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4720 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4721 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4722 mFallbackKeys.removeItemsAt(i);
4723 } else {
4724 i += 1;
4725 }
4726 }
4727 }
4728 ssize_t index = findKeyMemento(entry);
4729 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004730 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 return true;
4732 }
4733 /* FIXME: We can't just drop the key up event because that prevents creating
4734 * popup windows that are automatically shown when a key is held and then
4735 * dismissed when the key is released. The problem is that the popup will
4736 * not have received the original key down, so the key up will be considered
4737 * to be inconsistent with its observed state. We could perhaps handle this
4738 * by synthesizing a key down but that will cause other problems.
4739 *
4740 * So for now, allow inconsistent key up events to be dispatched.
4741 *
4742#if DEBUG_OUTBOUND_EVENT_DETAILS
4743 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4744 "keyCode=%d, scanCode=%d",
4745 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4746#endif
4747 return false;
4748 */
4749 return true;
4750 }
4751
4752 case AKEY_EVENT_ACTION_DOWN: {
4753 ssize_t index = findKeyMemento(entry);
4754 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004755 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 }
4757 addKeyMemento(entry, flags);
4758 return true;
4759 }
4760
4761 default:
4762 return true;
4763 }
4764}
4765
4766bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4767 int32_t action, int32_t flags) {
4768 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4769 switch (actionMasked) {
4770 case AMOTION_EVENT_ACTION_UP:
4771 case AMOTION_EVENT_ACTION_CANCEL: {
4772 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4773 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004774 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 return true;
4776 }
4777#if DEBUG_OUTBOUND_EVENT_DETAILS
4778 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004779 "displayId=%" PRId32 ", actionMasked=%d",
4780 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004781#endif
4782 return false;
4783 }
4784
4785 case AMOTION_EVENT_ACTION_DOWN: {
4786 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4787 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004788 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789 }
4790 addMotionMemento(entry, flags, false /*hovering*/);
4791 return true;
4792 }
4793
4794 case AMOTION_EVENT_ACTION_POINTER_UP:
4795 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4796 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004797 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4798 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4799 // generate cancellation events for these since they're based in relative rather than
4800 // absolute units.
4801 return true;
4802 }
4803
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004805
4806 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4807 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4808 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4809 // other value and we need to track the motion so we can send cancellation events for
4810 // anything generating fallback events (e.g. DPad keys for joystick movements).
4811 if (index >= 0) {
4812 if (entry->pointerCoords[0].isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004813 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wright38dcdff2014-03-19 12:06:10 -07004814 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004815 MotionMemento& memento = mMotionMementos[index];
Michael Wright38dcdff2014-03-19 12:06:10 -07004816 memento.setPointers(entry);
4817 }
4818 } else if (!entry->pointerCoords[0].isEmpty()) {
4819 addMotionMemento(entry, flags, false /*hovering*/);
4820 }
4821
4822 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4823 return true;
4824 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004826 MotionMemento& memento = mMotionMementos[index];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 memento.setPointers(entry);
4828 return true;
4829 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830#if DEBUG_OUTBOUND_EVENT_DETAILS
4831 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004832 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4833 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834#endif
4835 return false;
4836 }
4837
4838 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4839 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4840 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004841 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 return true;
4843 }
4844#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004845 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4846 "displayId=%" PRId32,
4847 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848#endif
4849 return false;
4850 }
4851
4852 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4853 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4854 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4855 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004856 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 }
4858 addMotionMemento(entry, flags, true /*hovering*/);
4859 return true;
4860 }
4861
4862 default:
4863 return true;
4864 }
4865}
4866
4867ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4868 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004869 const KeyMemento& memento = mKeyMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 if (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 return i;
4876 }
4877 }
4878 return -1;
4879}
4880
4881ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4882 bool hovering) const {
4883 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004884 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004885 if (memento.deviceId == entry->deviceId
4886 && memento.source == entry->source
4887 && memento.displayId == entry->displayId
4888 && memento.hovering == hovering) {
4889 return i;
4890 }
4891 }
4892 return -1;
4893}
4894
4895void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004896 KeyMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 memento.deviceId = entry->deviceId;
4898 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004899 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 memento.keyCode = entry->keyCode;
4901 memento.scanCode = entry->scanCode;
4902 memento.metaState = entry->metaState;
4903 memento.flags = flags;
4904 memento.downTime = entry->downTime;
4905 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004906 mKeyMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907}
4908
4909void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4910 int32_t flags, bool hovering) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004911 MotionMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912 memento.deviceId = entry->deviceId;
4913 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004914 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915 memento.flags = flags;
4916 memento.xPrecision = entry->xPrecision;
4917 memento.yPrecision = entry->yPrecision;
4918 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919 memento.setPointers(entry);
4920 memento.hovering = hovering;
4921 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004922 mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923}
4924
4925void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4926 pointerCount = entry->pointerCount;
4927 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4928 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4929 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4930 }
4931}
4932
4933void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004934 std::vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4935 for (KeyMemento& memento : mKeyMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936 if (shouldCancelKey(memento, options)) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004937 outEvents.push_back(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004938 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4940 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4941 }
4942 }
4943
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004944 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004946 const int32_t action = memento.hovering ?
4947 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004948 outEvents.push_back(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004949 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004950 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4951 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004953 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004954 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955 }
4956 }
4957}
4958
4959void InputDispatcher::InputState::clear() {
4960 mKeyMementos.clear();
4961 mMotionMementos.clear();
4962 mFallbackKeys.clear();
4963}
4964
4965void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4966 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004967 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4969 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004970 const MotionMemento& otherMemento = other.mMotionMementos[j];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971 if (memento.deviceId == otherMemento.deviceId
4972 && memento.source == otherMemento.source
4973 && memento.displayId == otherMemento.displayId) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004974 other.mMotionMementos.erase(other.mMotionMementos.begin() + j);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004975 } else {
4976 j += 1;
4977 }
4978 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004979 other.mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980 }
4981 }
4982}
4983
4984int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4985 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4986 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4987}
4988
4989void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4990 int32_t fallbackKeyCode) {
4991 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4992 if (index >= 0) {
4993 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4994 } else {
4995 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4996 }
4997}
4998
4999void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
5000 mFallbackKeys.removeItem(originalKeyCode);
5001}
5002
5003bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
5004 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005005 if (options.keyCode && memento.keyCode != options.keyCode.value()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005006 return false;
5007 }
5008
Michael Wright3dd60e22019-03-27 22:06:44 +00005009 if (options.deviceId && memento.deviceId != options.deviceId.value()) {
5010 return false;
5011 }
5012
5013 if (options.displayId && memento.displayId != options.displayId.value()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 return false;
5015 }
5016
5017 switch (options.mode) {
5018 case CancelationOptions::CANCEL_ALL_EVENTS:
5019 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
5020 return true;
5021 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
5022 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
5023 default:
5024 return false;
5025 }
5026}
5027
5028bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
5029 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005030 if (options.deviceId && memento.deviceId != options.deviceId.value()) {
5031 return false;
5032 }
5033
5034 if (options.displayId && memento.displayId != options.displayId.value()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005035 return false;
5036 }
5037
5038 switch (options.mode) {
5039 case CancelationOptions::CANCEL_ALL_EVENTS:
5040 return true;
5041 case CancelationOptions::CANCEL_POINTER_EVENTS:
5042 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
5043 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
5044 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
5045 default:
5046 return false;
5047 }
5048}
5049
5050
5051// --- InputDispatcher::Connection ---
5052
Robert Carr803535b2018-08-02 16:38:15 -07005053InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
5054 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 monitor(monitor),
5056 inputPublisher(inputChannel), inputPublisherBlocked(false) {
5057}
5058
5059InputDispatcher::Connection::~Connection() {
5060}
5061
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005062const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07005063 if (inputChannel != nullptr) {
5064 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065 }
5066 if (monitor) {
5067 return "monitor";
5068 }
5069 return "?";
5070}
5071
5072const char* InputDispatcher::Connection::getStatusLabel() const {
5073 switch (status) {
5074 case STATUS_NORMAL:
5075 return "NORMAL";
5076
5077 case STATUS_BROKEN:
5078 return "BROKEN";
5079
5080 case STATUS_ZOMBIE:
5081 return "ZOMBIE";
5082
5083 default:
5084 return "UNKNOWN";
5085 }
5086}
5087
5088InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07005089 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005090 if (entry->seq == seq) {
5091 return entry;
5092 }
5093 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005094 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095}
5096
Michael Wright3dd60e22019-03-27 22:06:44 +00005097// --- InputDispatcher::Monitor
5098InputDispatcher::Monitor::Monitor(const sp<InputChannel>& inputChannel) :
5099 inputChannel(inputChannel) {
5100}
5101
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102
5103// --- InputDispatcher::CommandEntry ---
Michael Wright3dd60e22019-03-27 22:06:44 +00005104//
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07005106 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107 seq(0), handled(false) {
5108}
5109
5110InputDispatcher::CommandEntry::~CommandEntry() {
5111}
5112
Michael Wright3dd60e22019-03-27 22:06:44 +00005113// --- InputDispatcher::TouchedMonitor ---
5114InputDispatcher::TouchedMonitor::TouchedMonitor(const Monitor& monitor, float xOffset,
5115 float yOffset) : monitor(monitor), xOffset(xOffset), yOffset(yOffset) {
5116}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117
5118// --- InputDispatcher::TouchState ---
5119
5120InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01005121 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122}
5123
5124InputDispatcher::TouchState::~TouchState() {
5125}
5126
5127void InputDispatcher::TouchState::reset() {
5128 down = false;
5129 split = false;
5130 deviceId = -1;
5131 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01005132 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005133 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005134 portalWindows.clear();
Michael Wright3dd60e22019-03-27 22:06:44 +00005135 gestureMonitors.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136}
5137
5138void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
5139 down = other.down;
5140 split = other.split;
5141 deviceId = other.deviceId;
5142 source = other.source;
5143 displayId = other.displayId;
5144 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005145 portalWindows = other.portalWindows;
Michael Wright3dd60e22019-03-27 22:06:44 +00005146 gestureMonitors = other.gestureMonitors;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005147}
5148
5149void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
5150 int32_t targetFlags, BitSet32 pointerIds) {
5151 if (targetFlags & InputTarget::FLAG_SPLIT) {
5152 split = true;
5153 }
5154
5155 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005156 TouchedWindow& touchedWindow = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 if (touchedWindow.windowHandle == windowHandle) {
5158 touchedWindow.targetFlags |= targetFlags;
5159 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
5160 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
5161 }
5162 touchedWindow.pointerIds.value |= pointerIds.value;
5163 return;
5164 }
5165 }
5166
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005167 TouchedWindow touchedWindow;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168 touchedWindow.windowHandle = windowHandle;
5169 touchedWindow.targetFlags = targetFlags;
5170 touchedWindow.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005171 windows.push_back(touchedWindow);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172}
5173
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005174void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
5175 size_t numWindows = portalWindows.size();
5176 for (size_t i = 0; i < numWindows; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005177 if (portalWindows[i] == windowHandle) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005178 return;
5179 }
5180 }
5181 portalWindows.push_back(windowHandle);
5182}
5183
Michael Wright3dd60e22019-03-27 22:06:44 +00005184void InputDispatcher::TouchState::addGestureMonitors(
5185 const std::vector<TouchedMonitor>& newMonitors) {
5186 const size_t newSize = gestureMonitors.size() + newMonitors.size();
5187 gestureMonitors.reserve(newSize);
5188 gestureMonitors.insert(std::end(gestureMonitors),
5189 std::begin(newMonitors), std::end(newMonitors));
5190}
5191
Michael Wrightd02c5b62014-02-10 15:10:22 -08005192void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
5193 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005194 if (windows[i].windowHandle == windowHandle) {
5195 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196 return;
5197 }
5198 }
5199}
5200
Robert Carr803535b2018-08-02 16:38:15 -07005201void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
5202 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005203 if (windows[i].windowHandle->getToken() == token) {
5204 windows.erase(windows.begin() + i);
Robert Carr803535b2018-08-02 16:38:15 -07005205 return;
5206 }
5207 }
5208}
5209
Michael Wrightd02c5b62014-02-10 15:10:22 -08005210void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
5211 for (size_t i = 0 ; i < windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005212 TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005213 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
5214 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
5215 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
5216 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
5217 i += 1;
5218 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005219 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220 }
5221 }
5222}
5223
Michael Wright3dd60e22019-03-27 22:06:44 +00005224void InputDispatcher::TouchState::filterNonMonitors() {
5225 windows.clear();
5226 portalWindows.clear();
5227}
5228
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
5230 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005231 const TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005232 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5233 return window.windowHandle;
5234 }
5235 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005236 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005237}
5238
5239bool InputDispatcher::TouchState::isSlippery() const {
5240 // Must have exactly one foreground window.
5241 bool haveSlipperyForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005242 for (const TouchedWindow& window : windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005243 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5244 if (haveSlipperyForegroundWindow
5245 || !(window.windowHandle->getInfo()->layoutParamsFlags
5246 & InputWindowInfo::FLAG_SLIPPERY)) {
5247 return false;
5248 }
5249 haveSlipperyForegroundWindow = true;
5250 }
5251 }
5252 return haveSlipperyForegroundWindow;
5253}
5254
5255
5256// --- InputDispatcherThread ---
5257
5258InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5259 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5260}
5261
5262InputDispatcherThread::~InputDispatcherThread() {
5263}
5264
5265bool InputDispatcherThread::threadLoop() {
5266 mDispatcher->dispatchOnce();
5267 return true;
5268}
5269
5270} // namespace android