blob: c2ff4c9629747a8ee00cda9cc29fd47ccb1e2b13 [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
chaviwfd6d3512019-03-25 13:23:49 -07002144 dispatchPointerDownOutsideFocus(motionEntry->source,
chaviw8c9cf542019-03-25 13:02:48 -07002145 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
chaviwfd6d3512019-03-25 13:23:49 -07002162void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
chaviw8c9cf542019-03-25 13:02:48 -07002163 const sp<IBinder>& newToken) {
2164 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002165 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2166 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002167 return;
2168 }
2169
2170 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2171 if (inputWindowHandle == nullptr) {
2172 return;
2173 }
2174
chaviw8c9cf542019-03-25 13:02:48 -07002175 sp<InputWindowHandle> focusedWindowHandle =
Tiger Huang0683fe72019-06-03 21:50:55 +08002176 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
chaviw8c9cf542019-03-25 13:02:48 -07002177
2178 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2179
2180 if (!hasFocusChanged) {
2181 return;
2182 }
2183
chaviwfd6d3512019-03-25 13:23:49 -07002184 CommandEntry* commandEntry = postCommandLocked(
2185 & InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
2186 commandEntry->newToken = newToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187}
2188
2189void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2190 const sp<Connection>& connection) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002191 if (ATRACE_ENABLED()) {
2192 std::string message = StringPrintf("startDispatchCycleLocked(inputChannel=%s)",
2193 connection->getInputChannelName().c_str());
2194 ATRACE_NAME(message.c_str());
2195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196#if DEBUG_DISPATCH_CYCLE
2197 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002198 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199#endif
2200
2201 while (connection->status == Connection::STATUS_NORMAL
2202 && !connection->outboundQueue.isEmpty()) {
2203 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2204 dispatchEntry->deliveryTime = currentTime;
2205
2206 // Publish the event.
2207 status_t status;
2208 EventEntry* eventEntry = dispatchEntry->eventEntry;
2209 switch (eventEntry->type) {
2210 case EventEntry::TYPE_KEY: {
2211 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2212
2213 // Publish the key event.
2214 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002215 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2217 keyEntry->keyCode, keyEntry->scanCode,
2218 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2219 keyEntry->eventTime);
2220 break;
2221 }
2222
2223 case EventEntry::TYPE_MOTION: {
2224 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2225
2226 PointerCoords scaledCoords[MAX_POINTERS];
2227 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2228
2229 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002230 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2232 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002233 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2234 float wxs = dispatchEntry->windowXScale;
2235 float wys = dispatchEntry->windowYScale;
2236 xOffset = dispatchEntry->xOffset * wxs;
2237 yOffset = dispatchEntry->yOffset * wys;
2238 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002239 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002241 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 }
2243 usingCoords = scaledCoords;
2244 }
2245 } else {
2246 xOffset = 0.0f;
2247 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248
2249 // We don't want the dispatch target to know.
2250 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002251 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 scaledCoords[i].clear();
2253 }
2254 usingCoords = scaledCoords;
2255 }
2256 }
2257
2258 // Publish the motion event.
2259 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002260 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002261 dispatchEntry->resolvedAction, motionEntry->actionButton,
2262 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002263 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification,
Michael Wright7b159c92015-05-14 14:48:03 +01002264 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 motionEntry->downTime, motionEntry->eventTime,
2266 motionEntry->pointerCount, motionEntry->pointerProperties,
2267 usingCoords);
2268 break;
2269 }
2270
2271 default:
2272 ALOG_ASSERT(false);
2273 return;
2274 }
2275
2276 // Check the result.
2277 if (status) {
2278 if (status == WOULD_BLOCK) {
2279 if (connection->waitQueue.isEmpty()) {
2280 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2281 "This is unexpected because the wait queue is empty, so the pipe "
2282 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002283 "event to it, status=%d", connection->getInputChannelName().c_str(),
2284 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2286 } else {
2287 // Pipe is full and we are waiting for the app to finish process some events
2288 // before sending more events to it.
2289#if DEBUG_DISPATCH_CYCLE
2290 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2291 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002292 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293#endif
2294 connection->inputPublisherBlocked = true;
2295 }
2296 } else {
2297 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002298 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2300 }
2301 return;
2302 }
2303
2304 // Re-enqueue the event on the wait queue.
2305 connection->outboundQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002306 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 connection->waitQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002308 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 }
2310}
2311
2312void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2313 const sp<Connection>& connection, uint32_t seq, bool handled) {
2314#if DEBUG_DISPATCH_CYCLE
2315 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002316 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317#endif
2318
2319 connection->inputPublisherBlocked = false;
2320
2321 if (connection->status == Connection::STATUS_BROKEN
2322 || connection->status == Connection::STATUS_ZOMBIE) {
2323 return;
2324 }
2325
2326 // Notify other system components and prepare to start the next dispatch cycle.
2327 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2328}
2329
2330void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2331 const sp<Connection>& connection, bool notify) {
2332#if DEBUG_DISPATCH_CYCLE
2333 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002334 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335#endif
2336
2337 // Clear the dispatch queues.
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002338 drainDispatchQueue(&connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002339 traceOutboundQueueLength(connection);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002340 drainDispatchQueue(&connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002341 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342
2343 // The connection appears to be unrecoverably broken.
2344 // Ignore already broken or zombie connections.
2345 if (connection->status == Connection::STATUS_NORMAL) {
2346 connection->status = Connection::STATUS_BROKEN;
2347
2348 if (notify) {
2349 // Notify other system components.
2350 onDispatchCycleBrokenLocked(currentTime, connection);
2351 }
2352 }
2353}
2354
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002355void InputDispatcher::drainDispatchQueue(Queue<DispatchEntry>* queue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 while (!queue->isEmpty()) {
2357 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002358 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 }
2360}
2361
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002362void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002364 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 }
2366 delete dispatchEntry;
2367}
2368
2369int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2370 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2371
2372 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002373 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374
2375 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2376 if (connectionIndex < 0) {
2377 ALOGE("Received spurious receive callback for unknown input channel. "
2378 "fd=%d, events=0x%x", fd, events);
2379 return 0; // remove the callback
2380 }
2381
2382 bool notify;
2383 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2384 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2385 if (!(events & ALOOPER_EVENT_INPUT)) {
2386 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002387 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388 return 1;
2389 }
2390
2391 nsecs_t currentTime = now();
2392 bool gotOne = false;
2393 status_t status;
2394 for (;;) {
2395 uint32_t seq;
2396 bool handled;
2397 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2398 if (status) {
2399 break;
2400 }
2401 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2402 gotOne = true;
2403 }
2404 if (gotOne) {
2405 d->runCommandsLockedInterruptible();
2406 if (status == WOULD_BLOCK) {
2407 return 1;
2408 }
2409 }
2410
2411 notify = status != DEAD_OBJECT || !connection->monitor;
2412 if (notify) {
2413 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002414 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002415 }
2416 } else {
2417 // Monitor channels are never explicitly unregistered.
2418 // We do it automatically when the remote endpoint is closed so don't warn
2419 // about them.
2420 notify = !connection->monitor;
2421 if (notify) {
2422 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002423 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 }
2425 }
2426
2427 // Unregister the channel.
2428 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2429 return 0; // remove the callback
2430 } // release lock
2431}
2432
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002433void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked (
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 const CancelationOptions& options) {
2435 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2436 synthesizeCancelationEventsForConnectionLocked(
2437 mConnectionsByFd.valueAt(i), options);
2438 }
2439}
2440
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002441void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked (
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002442 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00002443 synthesizeCancelationEventsForMonitorsLocked(options, mGlobalMonitorsByDisplay);
2444 synthesizeCancelationEventsForMonitorsLocked(options, mGestureMonitorsByDisplay);
2445}
2446
2447void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked(
2448 const CancelationOptions& options,
2449 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
2450 for (const auto& it : monitorsByDisplay) {
2451 const std::vector<Monitor>& monitors = it.second;
2452 for (const Monitor& monitor : monitors) {
2453 synthesizeCancelationEventsForInputChannelLocked(monitor.inputChannel, options);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002454 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002455 }
2456}
2457
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2459 const sp<InputChannel>& channel, const CancelationOptions& options) {
2460 ssize_t index = getConnectionIndexLocked(channel);
2461 if (index >= 0) {
2462 synthesizeCancelationEventsForConnectionLocked(
2463 mConnectionsByFd.valueAt(index), options);
2464 }
2465}
2466
2467void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2468 const sp<Connection>& connection, const CancelationOptions& options) {
2469 if (connection->status == Connection::STATUS_BROKEN) {
2470 return;
2471 }
2472
2473 nsecs_t currentTime = now();
2474
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002475 std::vector<EventEntry*> cancelationEvents;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 connection->inputState.synthesizeCancelationEvents(currentTime,
2477 cancelationEvents, options);
2478
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002479 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002481 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002483 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 options.reason, options.mode);
2485#endif
2486 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002487 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 switch (cancelationEventEntry->type) {
2489 case EventEntry::TYPE_KEY:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002490 logOutboundKeyDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491 static_cast<KeyEntry*>(cancelationEventEntry));
2492 break;
2493 case EventEntry::TYPE_MOTION:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002494 logOutboundMotionDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 static_cast<MotionEntry*>(cancelationEventEntry));
2496 break;
2497 }
2498
2499 InputTarget target;
chaviwfbe5d9c2018-12-26 12:23:37 -08002500 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(
2501 connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002502 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2504 target.xOffset = -windowInfo->frameLeft;
2505 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002506 target.globalScaleFactor = windowInfo->globalScaleFactor;
2507 target.windowXScale = windowInfo->windowXScale;
2508 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002509 } else {
2510 target.xOffset = 0;
2511 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002512 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513 }
2514 target.inputChannel = connection->inputChannel;
2515 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2516
chaviw8c9cf542019-03-25 13:02:48 -07002517 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Michael Wrightd02c5b62014-02-10 15:10:22 -08002518 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2519
2520 cancelationEventEntry->release();
2521 }
2522
2523 startDispatchCycleLocked(currentTime, connection);
2524 }
2525}
2526
2527InputDispatcher::MotionEntry*
2528InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2529 ALOG_ASSERT(pointerIds.value != 0);
2530
2531 uint32_t splitPointerIndexMap[MAX_POINTERS];
2532 PointerProperties splitPointerProperties[MAX_POINTERS];
2533 PointerCoords splitPointerCoords[MAX_POINTERS];
2534
2535 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2536 uint32_t splitPointerCount = 0;
2537
2538 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2539 originalPointerIndex++) {
2540 const PointerProperties& pointerProperties =
2541 originalMotionEntry->pointerProperties[originalPointerIndex];
2542 uint32_t pointerId = uint32_t(pointerProperties.id);
2543 if (pointerIds.hasBit(pointerId)) {
2544 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2545 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2546 splitPointerCoords[splitPointerCount].copyFrom(
2547 originalMotionEntry->pointerCoords[originalPointerIndex]);
2548 splitPointerCount += 1;
2549 }
2550 }
2551
2552 if (splitPointerCount != pointerIds.count()) {
2553 // This is bad. We are missing some of the pointers that we expected to deliver.
2554 // Most likely this indicates that we received an ACTION_MOVE events that has
2555 // different pointer ids than we expected based on the previous ACTION_DOWN
2556 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2557 // in this way.
2558 ALOGW("Dropping split motion event because the pointer count is %d but "
2559 "we expected there to be %d pointers. This probably means we received "
2560 "a broken sequence of pointer ids from the input device.",
2561 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002562 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 }
2564
2565 int32_t action = originalMotionEntry->action;
2566 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2567 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2568 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2569 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2570 const PointerProperties& pointerProperties =
2571 originalMotionEntry->pointerProperties[originalPointerIndex];
2572 uint32_t pointerId = uint32_t(pointerProperties.id);
2573 if (pointerIds.hasBit(pointerId)) {
2574 if (pointerIds.count() == 1) {
2575 // The first/last pointer went down/up.
2576 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2577 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2578 } else {
2579 // A secondary pointer went down/up.
2580 uint32_t splitPointerIndex = 0;
2581 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2582 splitPointerIndex += 1;
2583 }
2584 action = maskedAction | (splitPointerIndex
2585 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2586 }
2587 } else {
2588 // An unrelated pointer changed.
2589 action = AMOTION_EVENT_ACTION_MOVE;
2590 }
2591 }
2592
2593 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002594 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595 originalMotionEntry->eventTime,
2596 originalMotionEntry->deviceId,
2597 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002598 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 originalMotionEntry->policyFlags,
2600 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002601 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002602 originalMotionEntry->flags,
2603 originalMotionEntry->metaState,
2604 originalMotionEntry->buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002605 originalMotionEntry->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606 originalMotionEntry->edgeFlags,
2607 originalMotionEntry->xPrecision,
2608 originalMotionEntry->yPrecision,
2609 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002610 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002611
2612 if (originalMotionEntry->injectionState) {
2613 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2614 splitMotionEntry->injectionState->refCount += 1;
2615 }
2616
2617 return splitMotionEntry;
2618}
2619
2620void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2621#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002622 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623#endif
2624
2625 bool needWake;
2626 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002627 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628
Prabir Pradhan42611e02018-11-27 14:04:02 -08002629 ConfigurationChangedEntry* newEntry =
2630 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631 needWake = enqueueInboundEventLocked(newEntry);
2632 } // release lock
2633
2634 if (needWake) {
2635 mLooper->wake();
2636 }
2637}
2638
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002639/**
2640 * If one of the meta shortcuts is detected, process them here:
2641 * Meta + Backspace -> generate BACK
2642 * Meta + Enter -> generate HOME
2643 * This will potentially overwrite keyCode and metaState.
2644 */
2645void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2646 int32_t& keyCode, int32_t& metaState) {
2647 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2648 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2649 if (keyCode == AKEYCODE_DEL) {
2650 newKeyCode = AKEYCODE_BACK;
2651 } else if (keyCode == AKEYCODE_ENTER) {
2652 newKeyCode = AKEYCODE_HOME;
2653 }
2654 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002655 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002656 struct KeyReplacement replacement = {keyCode, deviceId};
2657 mReplacedKeys.add(replacement, newKeyCode);
2658 keyCode = newKeyCode;
2659 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2660 }
2661 } else if (action == AKEY_EVENT_ACTION_UP) {
2662 // In order to maintain a consistent stream of up and down events, check to see if the key
2663 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2664 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002665 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002666 struct KeyReplacement replacement = {keyCode, deviceId};
2667 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2668 if (index >= 0) {
2669 keyCode = mReplacedKeys.valueAt(index);
2670 mReplacedKeys.removeItemsAt(index);
2671 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2672 }
2673 }
2674}
2675
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2677#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002678 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002679 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002680 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002681 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002683 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684#endif
2685 if (!validateKeyEvent(args->action)) {
2686 return;
2687 }
2688
2689 uint32_t policyFlags = args->policyFlags;
2690 int32_t flags = args->flags;
2691 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002692 // InputDispatcher tracks and generates key repeats on behalf of
2693 // whatever notifies it, so repeatCount should always be set to 0
2694 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2696 policyFlags |= POLICY_FLAG_VIRTUAL;
2697 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2698 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 if (policyFlags & POLICY_FLAG_FUNCTION) {
2700 metaState |= AMETA_FUNCTION_ON;
2701 }
2702
2703 policyFlags |= POLICY_FLAG_TRUSTED;
2704
Michael Wright78f24442014-08-06 15:55:28 -07002705 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002706 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002707
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002709 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002710 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 args->downTime, args->eventTime);
2712
Michael Wright2b3c3302018-03-02 17:19:13 +00002713 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002715 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2716 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2717 std::to_string(t.duration().count()).c_str());
2718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719
Michael Wrightd02c5b62014-02-10 15:10:22 -08002720 bool needWake;
2721 { // acquire lock
2722 mLock.lock();
2723
2724 if (shouldSendKeyToInputFilterLocked(args)) {
2725 mLock.unlock();
2726
2727 policyFlags |= POLICY_FLAG_FILTERED;
2728 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2729 return; // event was consumed by the filter
2730 }
2731
2732 mLock.lock();
2733 }
2734
Prabir Pradhan42611e02018-11-27 14:04:02 -08002735 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002736 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002737 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738 metaState, repeatCount, args->downTime);
2739
2740 needWake = enqueueInboundEventLocked(newEntry);
2741 mLock.unlock();
2742 } // release lock
2743
2744 if (needWake) {
2745 mLooper->wake();
2746 }
2747}
2748
2749bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2750 return mInputFilterEnabled;
2751}
2752
2753void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2754#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002755 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2756 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002757 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002758 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2759 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002760 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002761 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762 for (uint32_t i = 0; i < args->pointerCount; i++) {
2763 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2764 "x=%f, y=%f, pressure=%f, size=%f, "
2765 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2766 "orientation=%f",
2767 i, args->pointerProperties[i].id,
2768 args->pointerProperties[i].toolType,
2769 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2770 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2771 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2772 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2773 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2774 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2775 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2776 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2777 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2778 }
2779#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002780 if (!validateMotionEvent(args->action, args->actionButton,
2781 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 return;
2783 }
2784
2785 uint32_t policyFlags = args->policyFlags;
2786 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002787
2788 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002789 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002790 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2791 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2792 std::to_string(t.duration().count()).c_str());
2793 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002794
2795 bool needWake;
2796 { // acquire lock
2797 mLock.lock();
2798
2799 if (shouldSendMotionToInputFilterLocked(args)) {
2800 mLock.unlock();
2801
2802 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002803 event.initialize(args->deviceId, args->source, args->displayId,
2804 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002805 args->flags, args->edgeFlags, args->metaState, args->buttonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002806 args->classification, 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 args->downTime, args->eventTime,
2808 args->pointerCount, args->pointerProperties, args->pointerCoords);
2809
2810 policyFlags |= POLICY_FLAG_FILTERED;
2811 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2812 return; // event was consumed by the filter
2813 }
2814
2815 mLock.lock();
2816 }
2817
2818 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002819 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002820 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002821 args->action, args->actionButton, args->flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002822 args->metaState, args->buttonState, args->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002824 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825
2826 needWake = enqueueInboundEventLocked(newEntry);
2827 mLock.unlock();
2828 } // release lock
2829
2830 if (needWake) {
2831 mLooper->wake();
2832 }
2833}
2834
2835bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002836 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837}
2838
2839void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2840#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002841 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2842 "switchMask=0x%08x",
2843 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844#endif
2845
2846 uint32_t policyFlags = args->policyFlags;
2847 policyFlags |= POLICY_FLAG_TRUSTED;
2848 mPolicy->notifySwitch(args->eventTime,
2849 args->switchValues, args->switchMask, policyFlags);
2850}
2851
2852void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2853#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002854 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855 args->eventTime, args->deviceId);
2856#endif
2857
2858 bool needWake;
2859 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002860 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002861
Prabir Pradhan42611e02018-11-27 14:04:02 -08002862 DeviceResetEntry* newEntry =
2863 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 needWake = enqueueInboundEventLocked(newEntry);
2865 } // release lock
2866
2867 if (needWake) {
2868 mLooper->wake();
2869 }
2870}
2871
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002872int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2874 uint32_t policyFlags) {
2875#if DEBUG_INBOUND_EVENT_DETAILS
2876 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002877 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2878 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002879#endif
2880
2881 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2882
2883 policyFlags |= POLICY_FLAG_INJECTED;
2884 if (hasInjectionPermission(injectorPid, injectorUid)) {
2885 policyFlags |= POLICY_FLAG_TRUSTED;
2886 }
2887
2888 EventEntry* firstInjectedEntry;
2889 EventEntry* lastInjectedEntry;
2890 switch (event->getType()) {
2891 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002892 KeyEvent keyEvent;
2893 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2894 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895 if (! validateKeyEvent(action)) {
2896 return INPUT_EVENT_INJECTION_FAILED;
2897 }
2898
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002899 int32_t flags = keyEvent.getFlags();
2900 int32_t keyCode = keyEvent.getKeyCode();
2901 int32_t metaState = keyEvent.getMetaState();
2902 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2903 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002904 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002905 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002906 keyEvent.getDownTime(), keyEvent.getEventTime());
2907
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2909 policyFlags |= POLICY_FLAG_VIRTUAL;
2910 }
2911
2912 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002913 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002914 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002915 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2916 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2917 std::to_string(t.duration().count()).c_str());
2918 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919 }
2920
Michael Wrightd02c5b62014-02-10 15:10:22 -08002921 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002922 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002923 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002925 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2926 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 lastInjectedEntry = firstInjectedEntry;
2928 break;
2929 }
2930
2931 case AINPUT_EVENT_TYPE_MOTION: {
2932 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 int32_t action = motionEvent->getAction();
2934 size_t pointerCount = motionEvent->getPointerCount();
2935 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002936 int32_t actionButton = motionEvent->getActionButton();
Charles Chen3611f1f2019-01-29 17:26:18 +08002937 int32_t displayId = motionEvent->getDisplayId();
Michael Wright7b159c92015-05-14 14:48:03 +01002938 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939 return INPUT_EVENT_INJECTION_FAILED;
2940 }
2941
2942 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2943 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002944 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002945 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002946 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2947 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2948 std::to_string(t.duration().count()).c_str());
2949 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002950 }
2951
2952 mLock.lock();
2953 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2954 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002955 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002956 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2957 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002958 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002959 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002960 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002961 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002962 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002963 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2964 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002965 lastInjectedEntry = firstInjectedEntry;
2966 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2967 sampleEventTimes += 1;
2968 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002969 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2970 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002971 motionEvent->getDeviceId(), motionEvent->getSource(),
2972 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002973 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002974 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002975 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002976 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002977 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002978 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2979 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002980 lastInjectedEntry->next = nextInjectedEntry;
2981 lastInjectedEntry = nextInjectedEntry;
2982 }
2983 break;
2984 }
2985
2986 default:
2987 ALOGW("Cannot inject event of type %d", event->getType());
2988 return INPUT_EVENT_INJECTION_FAILED;
2989 }
2990
2991 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2992 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2993 injectionState->injectionIsAsync = true;
2994 }
2995
2996 injectionState->refCount += 1;
2997 lastInjectedEntry->injectionState = injectionState;
2998
2999 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07003000 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003001 EventEntry* nextEntry = entry->next;
3002 needWake |= enqueueInboundEventLocked(entry);
3003 entry = nextEntry;
3004 }
3005
3006 mLock.unlock();
3007
3008 if (needWake) {
3009 mLooper->wake();
3010 }
3011
3012 int32_t injectionResult;
3013 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003014 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015
3016 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
3017 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
3018 } else {
3019 for (;;) {
3020 injectionResult = injectionState->injectionResult;
3021 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
3022 break;
3023 }
3024
3025 nsecs_t remainingTimeout = endTime - now();
3026 if (remainingTimeout <= 0) {
3027#if DEBUG_INJECTION
3028 ALOGD("injectInputEvent - Timed out waiting for injection result "
3029 "to become available.");
3030#endif
3031 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3032 break;
3033 }
3034
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003035 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003036 }
3037
3038 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
3039 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
3040 while (injectionState->pendingForegroundDispatches != 0) {
3041#if DEBUG_INJECTION
3042 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
3043 injectionState->pendingForegroundDispatches);
3044#endif
3045 nsecs_t remainingTimeout = endTime - now();
3046 if (remainingTimeout <= 0) {
3047#if DEBUG_INJECTION
3048 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
3049 "dispatches to finish.");
3050#endif
3051 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
3052 break;
3053 }
3054
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003055 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003056 }
3057 }
3058 }
3059
3060 injectionState->release();
3061 } // release lock
3062
3063#if DEBUG_INJECTION
3064 ALOGD("injectInputEvent - Finished with result %d. "
3065 "injectorPid=%d, injectorUid=%d",
3066 injectionResult, injectorPid, injectorUid);
3067#endif
3068
3069 return injectionResult;
3070}
3071
3072bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
3073 return injectorUid == 0
3074 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
3075}
3076
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003077void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078 InjectionState* injectionState = entry->injectionState;
3079 if (injectionState) {
3080#if DEBUG_INJECTION
3081 ALOGD("Setting input event injection result to %d. "
3082 "injectorPid=%d, injectorUid=%d",
3083 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
3084#endif
3085
3086 if (injectionState->injectionIsAsync
3087 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
3088 // Log the outcome since the injector did not wait for the injection result.
3089 switch (injectionResult) {
3090 case INPUT_EVENT_INJECTION_SUCCEEDED:
3091 ALOGV("Asynchronous input event injection succeeded.");
3092 break;
3093 case INPUT_EVENT_INJECTION_FAILED:
3094 ALOGW("Asynchronous input event injection failed.");
3095 break;
3096 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3097 ALOGW("Asynchronous input event injection permission denied.");
3098 break;
3099 case INPUT_EVENT_INJECTION_TIMED_OUT:
3100 ALOGW("Asynchronous input event injection timed out.");
3101 break;
3102 }
3103 }
3104
3105 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003106 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 }
3108}
3109
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003110void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111 InjectionState* injectionState = entry->injectionState;
3112 if (injectionState) {
3113 injectionState->pendingForegroundDispatches += 1;
3114 }
3115}
3116
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003117void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118 InjectionState* injectionState = entry->injectionState;
3119 if (injectionState) {
3120 injectionState->pendingForegroundDispatches -= 1;
3121
3122 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003123 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 }
3125 }
3126}
3127
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003128std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3129 int32_t displayId) const {
3130 std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>::const_iterator it =
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003131 mWindowHandlesByDisplay.find(displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003132 if(it != mWindowHandlesByDisplay.end()) {
3133 return it->second;
3134 }
3135
3136 // Return an empty one if nothing found.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003137 return std::vector<sp<InputWindowHandle>>();
Arthur Hungb92218b2018-08-14 12:00:21 +08003138}
3139
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003141 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003142 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003143 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3144 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003145 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003146 return windowHandle;
3147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 }
3149 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003150 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003151}
3152
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003153bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003154 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003155 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3156 for (const sp<InputWindowHandle>& handle : windowHandles) {
3157 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003158 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003159 ALOGE("Found window %s in display %" PRId32
3160 ", but it should belong to display %" PRId32,
3161 windowHandle->getName().c_str(), it.first,
3162 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003163 }
3164 return true;
3165 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 }
3167 }
3168 return false;
3169}
3170
Robert Carr5c8a0262018-10-03 16:30:44 -07003171sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3172 size_t count = mInputChannelsByToken.count(token);
3173 if (count == 0) {
3174 return nullptr;
3175 }
3176 return mInputChannelsByToken.at(token);
3177}
3178
Arthur Hungb92218b2018-08-14 12:00:21 +08003179/**
3180 * Called from InputManagerService, update window handle list by displayId that can receive input.
3181 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3182 * If set an empty list, remove all handles from the specific display.
3183 * For focused handle, check if need to change and send a cancel event to previous one.
3184 * For removed handle, check if need to send a cancel event if already in touch.
3185 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003186void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
chaviw291d88a2019-02-14 10:33:58 -08003187 int32_t displayId, const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003189 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190#endif
3191 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003192 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003193
Arthur Hungb92218b2018-08-14 12:00:21 +08003194 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003195 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3196 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197
Tiger Huang721e26f2018-07-24 22:26:19 +08003198 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003200
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003201 if (inputWindowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003202 // Remove all handles on a display if there are no windows left.
3203 mWindowHandlesByDisplay.erase(displayId);
3204 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003205 // Since we compare the pointer of input window handles across window updates, we need
3206 // to make sure the handle object for the same window stays unchanged across updates.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003207 const std::vector<sp<InputWindowHandle>>& oldHandles =
3208 mWindowHandlesByDisplay[displayId];
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003209 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003210 for (const sp<InputWindowHandle>& handle : oldHandles) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003211 oldHandlesByTokens[handle->getToken()] = handle;
3212 }
3213
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003214 std::vector<sp<InputWindowHandle>> newHandles;
3215 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
Siarhei Vishniakou3a179dc2019-01-30 09:50:04 -08003216 if (!handle->updateInfo()) {
3217 // handle no longer valid
3218 continue;
3219 }
3220 const InputWindowInfo* info = handle->getInfo();
3221
3222 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3223 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3224 const bool noInputChannel =
3225 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3226 const bool canReceiveInput =
3227 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3228 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3229 if (canReceiveInput && !noInputChannel) {
3230 ALOGE("Window handle %s has no registered input channel",
3231 handle->getName().c_str());
3232 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003233 continue;
3234 }
3235
Siarhei Vishniakou3a179dc2019-01-30 09:50:04 -08003236 if (info->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003237 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Siarhei Vishniakou3a179dc2019-01-30 09:50:04 -08003238 handle->getName().c_str(), displayId, info->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003239 continue;
3240 }
3241
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003242 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3243 const sp<InputWindowHandle> oldHandle =
3244 oldHandlesByTokens.at(handle->getToken());
3245 oldHandle->updateFrom(handle);
3246 newHandles.push_back(oldHandle);
3247 } else {
3248 newHandles.push_back(handle);
3249 }
3250 }
3251
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003252 for (const sp<InputWindowHandle>& windowHandle : newHandles) {
Arthur Hung7ab76b12019-01-09 19:17:20 +08003253 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3254 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3255 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003256 newFocusedWindowHandle = windowHandle;
3257 }
3258 if (windowHandle == mLastHoverWindowHandle) {
3259 foundHoveredWindow = true;
3260 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003261 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003262
3263 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003264 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265 }
3266
3267 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003268 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269 }
3270
Tiger Huang721e26f2018-07-24 22:26:19 +08003271 sp<InputWindowHandle> oldFocusedWindowHandle =
3272 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3273
3274 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3275 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003277 ALOGD("Focus left window: %s in display %" PRId32,
3278 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003280 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3281 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003282 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3284 "focus left window");
3285 synthesizeCancelationEventsForInputChannelLocked(
3286 focusedInputChannel, options);
3287 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003288 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003290 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003292 ALOGD("Focus entered window: %s in display %" PRId32,
3293 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003295 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003296 }
Robert Carrf759f162018-11-13 12:57:11 -08003297
3298 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003299 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003300 }
3301
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 }
3303
Arthur Hungb92218b2018-08-14 12:00:21 +08003304 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3305 if (stateIndex >= 0) {
3306 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003307 for (size_t i = 0; i < state.windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003308 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003309 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003310#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003311 ALOGD("Touched window was removed: %s in display %" PRId32,
3312 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003314 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003315 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003316 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003317 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3318 "touched window was removed");
3319 synthesizeCancelationEventsForInputChannelLocked(
3320 touchedInputChannel, options);
3321 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003322 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003323 } else {
3324 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326 }
3327 }
3328
3329 // Release information for windows that are no longer present.
3330 // This ensures that unused input channels are released promptly.
3331 // Otherwise, they might stick around until the window handle is destroyed
3332 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003333 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003334 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003335#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003336 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003338 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339 }
3340 }
3341 } // release lock
3342
3343 // Wake up poll loop since it may need to make new input dispatching choices.
3344 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003345
3346 if (setInputWindowsListener) {
3347 setInputWindowsListener->onSetInputWindowsFinished();
3348 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003349}
3350
3351void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003352 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003354 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355#endif
3356 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003357 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003358
Tiger Huang721e26f2018-07-24 22:26:19 +08003359 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3360 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003361 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003362 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3363 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003366 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003367 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003368 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003370 oldFocusedApplicationHandle.clear();
3371 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372 }
3373
3374#if DEBUG_FOCUS
3375 //logDispatchStateLocked();
3376#endif
3377 } // release lock
3378
3379 // Wake up poll loop since it may need to make new input dispatching choices.
3380 mLooper->wake();
3381}
3382
Tiger Huang721e26f2018-07-24 22:26:19 +08003383/**
3384 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3385 * the display not specified.
3386 *
3387 * We track any unreleased events for each window. If a window loses the ability to receive the
3388 * released event, we will send a cancel event to it. So when the focused display is changed, we
3389 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3390 * display. The display-specified events won't be affected.
3391 */
3392void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3393#if DEBUG_FOCUS
3394 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3395#endif
3396 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003397 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003398
3399 if (mFocusedDisplayId != displayId) {
3400 sp<InputWindowHandle> oldFocusedWindowHandle =
3401 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3402 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003403 sp<InputChannel> inputChannel =
3404 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003405 if (inputChannel != nullptr) {
3406 CancelationOptions options(
Michael Wright3dd60e22019-03-27 22:06:44 +00003407 CancelationOptions::CANCEL_NON_POINTER_EVENTS,
Tiger Huang721e26f2018-07-24 22:26:19 +08003408 "The display which contains this window no longer has focus.");
Michael Wright3dd60e22019-03-27 22:06:44 +00003409 options.displayId = ADISPLAY_ID_NONE;
Tiger Huang721e26f2018-07-24 22:26:19 +08003410 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3411 }
3412 }
3413 mFocusedDisplayId = displayId;
3414
3415 // Sanity check
3416 sp<InputWindowHandle> newFocusedWindowHandle =
3417 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003418 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003419
Tiger Huang721e26f2018-07-24 22:26:19 +08003420 if (newFocusedWindowHandle == nullptr) {
3421 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3422 if (!mFocusedWindowHandlesByDisplay.empty()) {
3423 ALOGE("But another display has a focused window:");
3424 for (auto& it : mFocusedWindowHandlesByDisplay) {
3425 const int32_t displayId = it.first;
3426 const sp<InputWindowHandle>& windowHandle = it.second;
3427 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3428 displayId, windowHandle->getName().c_str());
3429 }
3430 }
3431 }
3432 }
3433
3434#if DEBUG_FOCUS
3435 logDispatchStateLocked();
3436#endif
3437 } // release lock
3438
3439 // Wake up poll loop since it may need to make new input dispatching choices.
3440 mLooper->wake();
3441}
3442
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3444#if DEBUG_FOCUS
3445 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3446#endif
3447
3448 bool changed;
3449 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003450 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451
3452 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3453 if (mDispatchFrozen && !frozen) {
3454 resetANRTimeoutsLocked();
3455 }
3456
3457 if (mDispatchEnabled && !enabled) {
3458 resetAndDropEverythingLocked("dispatcher is being disabled");
3459 }
3460
3461 mDispatchEnabled = enabled;
3462 mDispatchFrozen = frozen;
3463 changed = true;
3464 } else {
3465 changed = false;
3466 }
3467
3468#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003469 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003470#endif
3471 } // release lock
3472
3473 if (changed) {
3474 // Wake up poll loop since it may need to make new input dispatching choices.
3475 mLooper->wake();
3476 }
3477}
3478
3479void InputDispatcher::setInputFilterEnabled(bool enabled) {
3480#if DEBUG_FOCUS
3481 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3482#endif
3483
3484 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003485 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486
3487 if (mInputFilterEnabled == enabled) {
3488 return;
3489 }
3490
3491 mInputFilterEnabled = enabled;
3492 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3493 } // release lock
3494
3495 // Wake up poll loop since there might be work to do to drop everything.
3496 mLooper->wake();
3497}
3498
chaviwfbe5d9c2018-12-26 12:23:37 -08003499bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3500 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003501#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003502 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003504 return true;
3505 }
3506
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003508 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509
chaviwfbe5d9c2018-12-26 12:23:37 -08003510 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3511 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003512 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003513 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514 return false;
3515 }
chaviw4f2dd402018-12-26 15:30:27 -08003516#if DEBUG_FOCUS
3517 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3518 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3519#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3521#if DEBUG_FOCUS
3522 ALOGD("Cannot transfer focus because windows are on different displays.");
3523#endif
3524 return false;
3525 }
3526
3527 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003528 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3529 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3530 for (size_t i = 0; i < state.windows.size(); i++) {
3531 const TouchedWindow& touchedWindow = state.windows[i];
3532 if (touchedWindow.windowHandle == fromWindowHandle) {
3533 int32_t oldTargetFlags = touchedWindow.targetFlags;
3534 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003536 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537
Jeff Brownf086ddb2014-02-11 14:28:48 -08003538 int32_t newTargetFlags = oldTargetFlags
3539 & (InputTarget::FLAG_FOREGROUND
3540 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3541 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003542
Jeff Brownf086ddb2014-02-11 14:28:48 -08003543 found = true;
3544 goto Found;
3545 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003546 }
3547 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003548Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549
3550 if (! found) {
3551#if DEBUG_FOCUS
3552 ALOGD("Focus transfer failed because from window did not have focus.");
3553#endif
3554 return false;
3555 }
3556
chaviwfbe5d9c2018-12-26 12:23:37 -08003557
3558 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3559 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3561 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3562 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3563 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3564 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3565
3566 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3567 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3568 "transferring touch focus from this window to another window");
3569 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3570 }
3571
3572#if DEBUG_FOCUS
3573 logDispatchStateLocked();
3574#endif
3575 } // release lock
3576
3577 // Wake up poll loop since it may need to make new input dispatching choices.
3578 mLooper->wake();
3579 return true;
3580}
3581
3582void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3583#if DEBUG_FOCUS
3584 ALOGD("Resetting and dropping all events (%s).", reason);
3585#endif
3586
3587 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3588 synthesizeCancelationEventsForAllConnectionsLocked(options);
3589
3590 resetKeyRepeatLocked();
3591 releasePendingEventLocked();
3592 drainInboundQueueLocked();
3593 resetANRTimeoutsLocked();
3594
Jeff Brownf086ddb2014-02-11 14:28:48 -08003595 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003597 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003598}
3599
3600void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003601 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003602 dumpDispatchStateLocked(dump);
3603
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003604 std::istringstream stream(dump);
3605 std::string line;
3606
3607 while (std::getline(stream, line, '\n')) {
3608 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 }
3610}
3611
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003612void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
Siarhei Vishniakou043a3ec2019-05-01 11:30:46 -07003613 dump += StringPrintf(INDENT "DispatchEnabled: %s\n", toString(mDispatchEnabled));
3614 dump += StringPrintf(INDENT "DispatchFrozen: %s\n", toString(mDispatchFrozen));
3615 dump += StringPrintf(INDENT "InputFilterEnabled: %s\n", toString(mInputFilterEnabled));
Tiger Huang721e26f2018-07-24 22:26:19 +08003616 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617
Tiger Huang721e26f2018-07-24 22:26:19 +08003618 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3619 dump += StringPrintf(INDENT "FocusedApplications:\n");
3620 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3621 const int32_t displayId = it.first;
3622 const sp<InputApplicationHandle>& applicationHandle = it.second;
3623 dump += StringPrintf(
3624 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3625 displayId,
3626 applicationHandle->getName().c_str(),
3627 applicationHandle->getDispatchingTimeout(
3628 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3629 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003631 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003633
3634 if (!mFocusedWindowHandlesByDisplay.empty()) {
3635 dump += StringPrintf(INDENT "FocusedWindows:\n");
3636 for (auto& it : mFocusedWindowHandlesByDisplay) {
3637 const int32_t displayId = it.first;
3638 const sp<InputWindowHandle>& windowHandle = it.second;
3639 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3640 displayId, windowHandle->getName().c_str());
3641 }
3642 } else {
3643 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3644 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645
Jeff Brownf086ddb2014-02-11 14:28:48 -08003646 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003647 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003648 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3649 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003650 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003651 state.displayId, toString(state.down), toString(state.split),
3652 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003653 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003654 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003655 for (size_t i = 0; i < state.windows.size(); i++) {
3656 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003657 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3658 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003659 touchedWindow.pointerIds.value,
3660 touchedWindow.targetFlags);
3661 }
3662 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003663 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003664 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003665 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003666 dump += INDENT3 "Portal windows:\n";
3667 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003668 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003669 dump += StringPrintf(INDENT4 "%zu: name='%s'\n",
3670 i, portalWindowHandle->getName().c_str());
3671 }
3672 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003673 }
3674 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003675 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 }
3677
Arthur Hungb92218b2018-08-14 12:00:21 +08003678 if (!mWindowHandlesByDisplay.empty()) {
3679 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003680 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003681 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003682 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003683 dump += INDENT2 "Windows:\n";
3684 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003685 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003686 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687
Arthur Hungb92218b2018-08-14 12:00:21 +08003688 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003689 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, "
Arthur Hungb92218b2018-08-14 12:00:21 +08003690 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003691 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003692 "touchableRegion=",
3693 i, windowInfo->name.c_str(), windowInfo->displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003694 windowInfo->portalToDisplayId,
Arthur Hungb92218b2018-08-14 12:00:21 +08003695 toString(windowInfo->paused),
3696 toString(windowInfo->hasFocus),
3697 toString(windowInfo->hasWallpaper),
3698 toString(windowInfo->visible),
3699 toString(windowInfo->canReceiveKeys),
3700 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3701 windowInfo->layer,
3702 windowInfo->frameLeft, windowInfo->frameTop,
3703 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003704 windowInfo->globalScaleFactor,
3705 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003706 dumpRegion(dump, windowInfo->touchableRegion);
3707 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3708 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3709 windowInfo->ownerPid, windowInfo->ownerUid,
3710 windowInfo->dispatchingTimeout / 1000000.0);
3711 }
3712 } else {
3713 dump += INDENT2 "Windows: <none>\n";
3714 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 }
3716 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003717 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 }
3719
Michael Wright3dd60e22019-03-27 22:06:44 +00003720 if (!mGlobalMonitorsByDisplay.empty() || !mGestureMonitorsByDisplay.empty()) {
3721 for (auto& it : mGlobalMonitorsByDisplay) {
3722 const std::vector<Monitor>& monitors = it.second;
3723 dump += StringPrintf(INDENT "Global monitors in display %" PRId32 ":\n", it.first);
3724 dumpMonitors(dump, monitors);
3725 }
3726 for (auto& it : mGestureMonitorsByDisplay) {
3727 const std::vector<Monitor>& monitors = it.second;
3728 dump += StringPrintf(INDENT "Gesture monitors in display %" PRId32 ":\n", it.first);
3729 dumpMonitors(dump, monitors);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003730 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 } else {
Michael Wright3dd60e22019-03-27 22:06:44 +00003732 dump += INDENT "Monitors: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 }
3734
3735 nsecs_t currentTime = now();
3736
3737 // Dump recently dispatched or dropped events from oldest to newest.
3738 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003739 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003741 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003743 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744 (currentTime - entry->eventTime) * 0.000001f);
3745 }
3746 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003747 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003748 }
3749
3750 // Dump event currently being dispatched.
3751 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003752 dump += INDENT "PendingEvent:\n";
3753 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003755 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3757 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003758 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759 }
3760
3761 // Dump inbound events from oldest to newest.
3762 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003763 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003765 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003767 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768 (currentTime - entry->eventTime) * 0.000001f);
3769 }
3770 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003771 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772 }
3773
Michael Wright78f24442014-08-06 15:55:28 -07003774 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003775 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003776 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3777 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3778 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003779 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003780 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3781 }
3782 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003783 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003784 }
3785
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003787 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003788 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3789 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003790 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003792 i, connection->getInputChannelName().c_str(),
3793 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003794 connection->getStatusLabel(), toString(connection->monitor),
3795 toString(connection->inputPublisherBlocked));
3796
3797 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003798 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 connection->outboundQueue.count());
3800 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3801 entry = entry->next) {
3802 dump.append(INDENT4);
3803 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003804 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 entry->targetFlags, entry->resolvedAction,
3806 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3807 }
3808 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003809 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003810 }
3811
3812 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003813 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 connection->waitQueue.count());
3815 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3816 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003817 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003818 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003819 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003820 "age=%0.1fms, wait=%0.1fms\n",
3821 entry->targetFlags, entry->resolvedAction,
3822 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3823 (currentTime - entry->deliveryTime) * 0.000001f);
3824 }
3825 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003826 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003827 }
3828 }
3829 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003830 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003831 }
3832
3833 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003834 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 (mAppSwitchDueTime - now()) / 1000000.0);
3836 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003837 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003838 }
3839
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003840 dump += INDENT "Configuration:\n";
3841 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003843 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844 mConfig.keyRepeatTimeout * 0.000001f);
3845}
3846
Michael Wright3dd60e22019-03-27 22:06:44 +00003847void InputDispatcher::dumpMonitors(std::string& dump, const std::vector<Monitor>& monitors) {
3848 const size_t numMonitors = monitors.size();
3849 for (size_t i = 0; i < numMonitors; i++) {
3850 const Monitor& monitor = monitors[i];
3851 const sp<InputChannel>& channel = monitor.inputChannel;
3852 dump += StringPrintf(INDENT2 "%zu: '%s', ", i, channel->getName().c_str());
3853 dump += "\n";
3854 }
3855}
3856
3857status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
3858 int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003859#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003860 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3861 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862#endif
3863
3864 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003865 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866
3867 if (getConnectionIndexLocked(inputChannel) >= 0) {
3868 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003869 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870 return BAD_VALUE;
3871 }
3872
Michael Wright3dd60e22019-03-27 22:06:44 +00003873 sp<Connection> connection = new Connection(inputChannel, false /*monitor*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
3875 int fd = inputChannel->getFd();
3876 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003877 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878
Michael Wrightd02c5b62014-02-10 15:10:22 -08003879 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3880 } // release lock
3881
3882 // Wake the looper because some connections have changed.
3883 mLooper->wake();
3884 return OK;
3885}
3886
Michael Wright3dd60e22019-03-27 22:06:44 +00003887status_t InputDispatcher::registerInputMonitor(const sp<InputChannel>& inputChannel,
3888 int32_t displayId, bool isGestureMonitor) {
3889 { // acquire lock
3890 std::scoped_lock _l(mLock);
3891
3892 if (displayId < 0) {
3893 ALOGW("Attempted to register input monitor without a specified display.");
3894 return BAD_VALUE;
3895 }
3896
3897 if (inputChannel->getToken() == nullptr) {
3898 ALOGW("Attempted to register input monitor without an identifying token.");
3899 return BAD_VALUE;
3900 }
3901
3902 sp<Connection> connection = new Connection(inputChannel, true /*monitor*/);
3903
3904 const int fd = inputChannel->getFd();
3905 mConnectionsByFd.add(fd, connection);
3906 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
3907
3908 auto& monitorsByDisplay = isGestureMonitor
3909 ? mGestureMonitorsByDisplay
3910 : mGlobalMonitorsByDisplay;
3911 monitorsByDisplay[displayId].emplace_back(inputChannel);
3912
3913 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3914
3915 }
3916 // Wake the looper because some connections have changed.
3917 mLooper->wake();
3918 return OK;
3919}
3920
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3922#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003923 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924#endif
3925
3926 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003927 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003928
3929 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3930 if (status) {
3931 return status;
3932 }
3933 } // release lock
3934
3935 // Wake the poll loop because removing the connection may have changed the current
3936 // synchronization state.
3937 mLooper->wake();
3938 return OK;
3939}
3940
3941status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3942 bool notify) {
3943 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3944 if (connectionIndex < 0) {
3945 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003946 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 return BAD_VALUE;
3948 }
3949
3950 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3951 mConnectionsByFd.removeItemsAt(connectionIndex);
3952
Robert Carr5c8a0262018-10-03 16:30:44 -07003953 mInputChannelsByToken.erase(inputChannel->getToken());
3954
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955 if (connection->monitor) {
3956 removeMonitorChannelLocked(inputChannel);
3957 }
3958
3959 mLooper->removeFd(inputChannel->getFd());
3960
3961 nsecs_t currentTime = now();
3962 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3963
3964 connection->status = Connection::STATUS_ZOMBIE;
3965 return OK;
3966}
3967
3968void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Michael Wright3dd60e22019-03-27 22:06:44 +00003969 removeMonitorChannelLocked(inputChannel, mGlobalMonitorsByDisplay);
3970 removeMonitorChannelLocked(inputChannel, mGestureMonitorsByDisplay);
3971}
3972
3973void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel,
3974 std::unordered_map<int32_t, std::vector<Monitor>>& monitorsByDisplay) {
3975 for (auto it = monitorsByDisplay.begin(); it != monitorsByDisplay.end(); ) {
3976 std::vector<Monitor>& monitors = it->second;
3977 const size_t numMonitors = monitors.size();
3978 for (size_t i = 0; i < numMonitors; i++) {
3979 if (monitors[i].inputChannel == inputChannel) {
3980 monitors.erase(monitors.begin() + i);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003981 break;
3982 }
3983 }
Michael Wright3dd60e22019-03-27 22:06:44 +00003984 if (monitors.empty()) {
3985 it = monitorsByDisplay.erase(it);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003986 } else {
3987 ++it;
3988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989 }
3990}
3991
Michael Wright3dd60e22019-03-27 22:06:44 +00003992status_t InputDispatcher::pilferPointers(const sp<IBinder>& token) {
3993 { // acquire lock
3994 std::scoped_lock _l(mLock);
3995 std::optional<int32_t> foundDisplayId = findGestureMonitorDisplayByTokenLocked(token);
3996
3997 if (!foundDisplayId) {
3998 ALOGW("Attempted to pilfer pointers from an un-registered monitor or invalid token");
3999 return BAD_VALUE;
4000 }
4001 int32_t displayId = foundDisplayId.value();
4002
4003 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
4004 if (stateIndex < 0) {
4005 ALOGW("Failed to pilfer pointers: no pointers on display %" PRId32 ".", displayId);
4006 return BAD_VALUE;
4007 }
4008
4009 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
4010 std::optional<int32_t> foundDeviceId;
4011 for (const TouchedMonitor& touchedMonitor : state.gestureMonitors) {
4012 if (touchedMonitor.monitor.inputChannel->getToken() == token) {
4013 foundDeviceId = state.deviceId;
4014 }
4015 }
4016 if (!foundDeviceId || !state.down) {
4017 ALOGW("Attempted to pilfer points from a monitor without any on-going pointer streams."
4018 " Ignoring.");
4019 return BAD_VALUE;
4020 }
4021 int32_t deviceId = foundDeviceId.value();
4022
4023 // Send cancel events to all the input channels we're stealing from.
4024 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
4025 "gesture monitor stole pointer stream");
4026 options.deviceId = deviceId;
4027 options.displayId = displayId;
4028 for (const TouchedWindow& window : state.windows) {
4029 sp<InputChannel> channel = getInputChannelLocked(window.windowHandle->getToken());
4030 synthesizeCancelationEventsForInputChannelLocked(channel, options);
4031 }
4032 // Then clear the current touch state so we stop dispatching to them as well.
4033 state.filterNonMonitors();
4034 }
4035 return OK;
4036}
4037
4038
4039std::optional<int32_t> InputDispatcher::findGestureMonitorDisplayByTokenLocked(
4040 const sp<IBinder>& token) {
4041 for (const auto& it : mGestureMonitorsByDisplay) {
4042 const std::vector<Monitor>& monitors = it.second;
4043 for (const Monitor& monitor : monitors) {
4044 if (monitor.inputChannel->getToken() == token) {
4045 return it.first;
4046 }
4047 }
4048 }
4049 return std::nullopt;
4050}
4051
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07004053 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08004054 return -1;
4055 }
4056
Robert Carr4e670e52018-08-15 13:26:12 -07004057 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
4058 sp<Connection> connection = mConnectionsByFd.valueAt(i);
4059 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
4060 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004061 }
4062 }
Robert Carr4e670e52018-08-15 13:26:12 -07004063
Michael Wrightd02c5b62014-02-10 15:10:22 -08004064 return -1;
4065}
4066
4067void InputDispatcher::onDispatchCycleFinishedLocked(
4068 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
4069 CommandEntry* commandEntry = postCommandLocked(
4070 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
4071 commandEntry->connection = connection;
4072 commandEntry->eventTime = currentTime;
4073 commandEntry->seq = seq;
4074 commandEntry->handled = handled;
4075}
4076
4077void InputDispatcher::onDispatchCycleBrokenLocked(
4078 nsecs_t currentTime, const sp<Connection>& connection) {
4079 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004080 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081
4082 CommandEntry* commandEntry = postCommandLocked(
4083 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
4084 commandEntry->connection = connection;
4085}
4086
chaviw0c06c6e2019-01-09 13:27:07 -08004087void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
4088 const sp<InputWindowHandle>& newFocus) {
4089 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
4090 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08004091 CommandEntry* commandEntry = postCommandLocked(
4092 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08004093 commandEntry->oldToken = oldToken;
4094 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004095}
4096
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097void InputDispatcher::onANRLocked(
4098 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
4099 const sp<InputWindowHandle>& windowHandle,
4100 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
4101 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
4102 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
4103 ALOGI("Application is not responding: %s. "
4104 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004105 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004106 dispatchLatency, waitDuration, reason);
4107
4108 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07004109 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 struct tm tm;
4111 localtime_r(&t, &tm);
4112 char timestr[64];
4113 strftime(timestr, sizeof(timestr), "%F %T", &tm);
4114 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004115 mLastANRState += INDENT "ANR:\n";
4116 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
4117 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004118 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004119 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
4120 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
4121 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 dumpDispatchStateLocked(mLastANRState);
4123
4124 CommandEntry* commandEntry = postCommandLocked(
4125 & InputDispatcher::doNotifyANRLockedInterruptible);
4126 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07004127 commandEntry->inputChannel = windowHandle != nullptr ?
4128 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129 commandEntry->reason = reason;
4130}
4131
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004132void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible (
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 CommandEntry* commandEntry) {
4134 mLock.unlock();
4135
4136 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
4137
4138 mLock.lock();
4139}
4140
4141void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
4142 CommandEntry* commandEntry) {
4143 sp<Connection> connection = commandEntry->connection;
4144
4145 if (connection->status != Connection::STATUS_ZOMBIE) {
4146 mLock.unlock();
4147
Robert Carr803535b2018-08-02 16:38:15 -07004148 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149
4150 mLock.lock();
4151 }
4152}
4153
Robert Carrf759f162018-11-13 12:57:11 -08004154void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
4155 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08004156 sp<IBinder> oldToken = commandEntry->oldToken;
4157 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08004158 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08004159 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08004160 mLock.lock();
4161}
4162
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163void InputDispatcher::doNotifyANRLockedInterruptible(
4164 CommandEntry* commandEntry) {
4165 mLock.unlock();
4166
4167 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07004168 commandEntry->inputApplicationHandle,
4169 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 commandEntry->reason);
4171
4172 mLock.lock();
4173
4174 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07004175 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176}
4177
4178void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
4179 CommandEntry* commandEntry) {
4180 KeyEntry* entry = commandEntry->keyEntry;
4181
4182 KeyEvent event;
4183 initializeKeyEvent(&event, entry);
4184
4185 mLock.unlock();
4186
Michael Wright2b3c3302018-03-02 17:19:13 +00004187 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07004188 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
4189 commandEntry->inputChannel->getToken() : nullptr;
4190 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00004192 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
4193 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
4194 std::to_string(t.duration().count()).c_str());
4195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196
4197 mLock.lock();
4198
4199 if (delay < 0) {
4200 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4201 } else if (!delay) {
4202 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4203 } else {
4204 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4205 entry->interceptKeyWakeupTime = now() + delay;
4206 }
4207 entry->release();
4208}
4209
chaviwfd6d3512019-03-25 13:23:49 -07004210void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4211 mLock.unlock();
4212 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4213 mLock.lock();
4214}
4215
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
4217 CommandEntry* commandEntry) {
4218 sp<Connection> connection = commandEntry->connection;
4219 nsecs_t finishTime = commandEntry->eventTime;
4220 uint32_t seq = commandEntry->seq;
4221 bool handled = commandEntry->handled;
4222
4223 // Handle post-event policy actions.
4224 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4225 if (dispatchEntry) {
4226 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4227 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004228 std::string msg =
4229 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004230 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004232 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 }
4234
4235 bool restartEvent;
4236 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4237 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4238 restartEvent = afterKeyEventLockedInterruptible(connection,
4239 dispatchEntry, keyEntry, handled);
4240 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4241 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4242 restartEvent = afterMotionEventLockedInterruptible(connection,
4243 dispatchEntry, motionEntry, handled);
4244 } else {
4245 restartEvent = false;
4246 }
4247
4248 // Dequeue the event and start the next cycle.
4249 // Note that because the lock might have been released, it is possible that the
4250 // contents of the wait queue to have been drained, so we need to double-check
4251 // a few things.
4252 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4253 connection->waitQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004254 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4256 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004257 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 } else {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08004259 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 }
4261 }
4262
4263 // Start the next dispatch cycle for this connection.
4264 startDispatchCycleLocked(now(), connection);
4265 }
4266}
4267
4268bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4269 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004270 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004271 if (!handled) {
4272 // Report the key as unhandled, since the fallback was not handled.
4273 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4274 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004275 return false;
4276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004278 // Get the fallback key state.
4279 // Clear it out after dispatching the UP.
4280 int32_t originalKeyCode = keyEntry->keyCode;
4281 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4282 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4283 connection->inputState.removeFallbackKey(originalKeyCode);
4284 }
4285
4286 if (handled || !dispatchEntry->hasForegroundTarget()) {
4287 // If the application handles the original key for which we previously
4288 // generated a fallback or if the window is not a foreground window,
4289 // then cancel the associated fallback key, if any.
4290 if (fallbackKeyCode != -1) {
4291 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004293 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4295 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4296 keyEntry->policyFlags);
4297#endif
4298 KeyEvent event;
4299 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004300 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301
4302 mLock.unlock();
4303
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004304 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4305 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306
4307 mLock.lock();
4308
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004309 // Cancel the fallback key.
4310 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004312 "application handled the original non-fallback key "
4313 "or is no longer a foreground target, "
4314 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315 options.keyCode = fallbackKeyCode;
4316 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004318 connection->inputState.removeFallbackKey(originalKeyCode);
4319 }
4320 } else {
4321 // If the application did not handle a non-fallback key, first check
4322 // that we are in a good state to perform unhandled key event processing
4323 // Then ask the policy what to do with it.
4324 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4325 && keyEntry->repeatCount == 0;
4326 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004328 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4329 "since this is not an initial down. "
4330 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4331 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4332 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004334 return false;
4335 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004337 // Dispatch the unhandled key to the policy.
4338#if DEBUG_OUTBOUND_EVENT_DETAILS
4339 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4340 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4341 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4342 keyEntry->policyFlags);
4343#endif
4344 KeyEvent event;
4345 initializeKeyEvent(&event, keyEntry);
4346
4347 mLock.unlock();
4348
4349 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4350 &event, keyEntry->policyFlags, &event);
4351
4352 mLock.lock();
4353
4354 if (connection->status != Connection::STATUS_NORMAL) {
4355 connection->inputState.removeFallbackKey(originalKeyCode);
4356 return false;
4357 }
4358
4359 // Latch the fallback keycode for this key on an initial down.
4360 // The fallback keycode cannot change at any other point in the lifecycle.
4361 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004363 fallbackKeyCode = event.getKeyCode();
4364 } else {
4365 fallbackKeyCode = AKEYCODE_UNKNOWN;
4366 }
4367 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4368 }
4369
4370 ALOG_ASSERT(fallbackKeyCode != -1);
4371
4372 // Cancel the fallback key if the policy decides not to send it anymore.
4373 // We will continue to dispatch the key to the policy but we will no
4374 // longer dispatch a fallback key to the application.
4375 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4376 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4377#if DEBUG_OUTBOUND_EVENT_DETAILS
4378 if (fallback) {
4379 ALOGD("Unhandled key event: Policy requested to send key %d"
4380 "as a fallback for %d, but on the DOWN it had requested "
4381 "to send %d instead. Fallback canceled.",
4382 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4383 } else {
4384 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4385 "but on the DOWN it had requested to send %d. "
4386 "Fallback canceled.",
4387 originalKeyCode, fallbackKeyCode);
4388 }
4389#endif
4390
4391 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4392 "canceling fallback, policy no longer desires it");
4393 options.keyCode = fallbackKeyCode;
4394 synthesizeCancelationEventsForConnectionLocked(connection, options);
4395
4396 fallback = false;
4397 fallbackKeyCode = AKEYCODE_UNKNOWN;
4398 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4399 connection->inputState.setFallbackKey(originalKeyCode,
4400 fallbackKeyCode);
4401 }
4402 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403
4404#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004405 {
4406 std::string msg;
4407 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4408 connection->inputState.getFallbackKeys();
4409 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4410 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4411 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004412 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004413 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4414 fallbackKeys.size(), msg.c_str());
4415 }
4416#endif
4417
4418 if (fallback) {
4419 // Restart the dispatch cycle using the fallback key.
4420 keyEntry->eventTime = event.getEventTime();
4421 keyEntry->deviceId = event.getDeviceId();
4422 keyEntry->source = event.getSource();
4423 keyEntry->displayId = event.getDisplayId();
4424 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4425 keyEntry->keyCode = fallbackKeyCode;
4426 keyEntry->scanCode = event.getScanCode();
4427 keyEntry->metaState = event.getMetaState();
4428 keyEntry->repeatCount = event.getRepeatCount();
4429 keyEntry->downTime = event.getDownTime();
4430 keyEntry->syntheticRepeat = false;
4431
4432#if DEBUG_OUTBOUND_EVENT_DETAILS
4433 ALOGD("Unhandled key event: Dispatching fallback key. "
4434 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4435 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4436#endif
4437 return true; // restart the event
4438 } else {
4439#if DEBUG_OUTBOUND_EVENT_DETAILS
4440 ALOGD("Unhandled key event: No fallback key.");
4441#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004442
4443 // Report the key as unhandled, since there is no fallback key.
4444 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004445 }
4446 }
4447 return false;
4448}
4449
4450bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4451 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4452 return false;
4453}
4454
4455void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4456 mLock.unlock();
4457
4458 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4459
4460 mLock.lock();
4461}
4462
4463void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004464 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4466 entry->downTime, entry->eventTime);
4467}
4468
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004469void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4471 // TODO Write some statistics about how long we spend waiting.
4472}
4473
4474void InputDispatcher::traceInboundQueueLengthLocked() {
4475 if (ATRACE_ENABLED()) {
4476 ATRACE_INT("iq", mInboundQueue.count());
4477 }
4478}
4479
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004480void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004481 if (ATRACE_ENABLED()) {
4482 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004483 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004484 ATRACE_INT(counterName, connection->outboundQueue.count());
4485 }
4486}
4487
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004488void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 if (ATRACE_ENABLED()) {
4490 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004491 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004492 ATRACE_INT(counterName, connection->waitQueue.count());
4493 }
4494}
4495
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004496void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004497 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004498
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004499 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004500 dumpDispatchStateLocked(dump);
4501
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004502 if (!mLastANRState.empty()) {
4503 dump += "\nInput Dispatcher State at time of last ANR:\n";
4504 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004505 }
4506}
4507
4508void InputDispatcher::monitor() {
4509 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004510 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004511 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004512 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004513}
4514
4515
Michael Wrightd02c5b62014-02-10 15:10:22 -08004516// --- InputDispatcher::InjectionState ---
4517
4518InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4519 refCount(1),
4520 injectorPid(injectorPid), injectorUid(injectorUid),
4521 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4522 pendingForegroundDispatches(0) {
4523}
4524
4525InputDispatcher::InjectionState::~InjectionState() {
4526}
4527
4528void InputDispatcher::InjectionState::release() {
4529 refCount -= 1;
4530 if (refCount == 0) {
4531 delete this;
4532 } else {
4533 ALOG_ASSERT(refCount > 0);
4534 }
4535}
4536
4537
4538// --- InputDispatcher::EventEntry ---
4539
Prabir Pradhan42611e02018-11-27 14:04:02 -08004540InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4541 nsecs_t eventTime, uint32_t policyFlags) :
4542 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4543 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004544}
4545
4546InputDispatcher::EventEntry::~EventEntry() {
4547 releaseInjectionState();
4548}
4549
4550void InputDispatcher::EventEntry::release() {
4551 refCount -= 1;
4552 if (refCount == 0) {
4553 delete this;
4554 } else {
4555 ALOG_ASSERT(refCount > 0);
4556 }
4557}
4558
4559void InputDispatcher::EventEntry::releaseInjectionState() {
4560 if (injectionState) {
4561 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004562 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 }
4564}
4565
4566
4567// --- InputDispatcher::ConfigurationChangedEntry ---
4568
Prabir Pradhan42611e02018-11-27 14:04:02 -08004569InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4570 uint32_t sequenceNum, nsecs_t eventTime) :
4571 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572}
4573
4574InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4575}
4576
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004577void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4578 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004579}
4580
4581
4582// --- InputDispatcher::DeviceResetEntry ---
4583
Prabir Pradhan42611e02018-11-27 14:04:02 -08004584InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4585 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4586 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 deviceId(deviceId) {
4588}
4589
4590InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4591}
4592
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004593void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4594 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595 deviceId, policyFlags);
4596}
4597
4598
4599// --- InputDispatcher::KeyEntry ---
4600
Prabir Pradhan42611e02018-11-27 14:04:02 -08004601InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004602 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4604 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004605 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004606 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004607 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4608 repeatCount(repeatCount), downTime(downTime),
4609 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4610 interceptKeyWakeupTime(0) {
4611}
4612
4613InputDispatcher::KeyEntry::~KeyEntry() {
4614}
4615
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004616void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004617 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4619 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004620 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004621 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004622}
4623
4624void InputDispatcher::KeyEntry::recycle() {
4625 releaseInjectionState();
4626
4627 dispatchInProgress = false;
4628 syntheticRepeat = false;
4629 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4630 interceptKeyWakeupTime = 0;
4631}
4632
4633
4634// --- InputDispatcher::MotionEntry ---
4635
Prabir Pradhan42611e02018-11-27 14:04:02 -08004636InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004637 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4638 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004639 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4640 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004641 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004642 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4643 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004644 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004646 deviceId(deviceId), source(source), displayId(displayId), action(action),
4647 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004648 classification(classification), edgeFlags(edgeFlags),
4649 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004650 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651 for (uint32_t i = 0; i < pointerCount; i++) {
4652 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4653 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004654 if (xOffset || yOffset) {
4655 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657 }
4658}
4659
4660InputDispatcher::MotionEntry::~MotionEntry() {
4661}
4662
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004663void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004664 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004665 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004666 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004667 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004668 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4669 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004670
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671 for (uint32_t i = 0; i < pointerCount; i++) {
4672 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004673 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004675 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676 pointerCoords[i].getX(), pointerCoords[i].getY());
4677 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004678 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679}
4680
4681
4682// --- InputDispatcher::DispatchEntry ---
4683
4684volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4685
4686InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004687 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4688 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 seq(nextSeq()),
4690 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004691 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4692 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004693 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4694 eventEntry->refCount += 1;
4695}
4696
4697InputDispatcher::DispatchEntry::~DispatchEntry() {
4698 eventEntry->release();
4699}
4700
4701uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4702 // Sequence number 0 is reserved and will never be returned.
4703 uint32_t seq;
4704 do {
4705 seq = android_atomic_inc(&sNextSeqAtomic);
4706 } while (!seq);
4707 return seq;
4708}
4709
4710
4711// --- InputDispatcher::InputState ---
4712
4713InputDispatcher::InputState::InputState() {
4714}
4715
4716InputDispatcher::InputState::~InputState() {
4717}
4718
4719bool InputDispatcher::InputState::isNeutral() const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004720 return mKeyMementos.empty() && mMotionMementos.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721}
4722
4723bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4724 int32_t displayId) const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004725 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 if (memento.deviceId == deviceId
4727 && memento.source == source
4728 && memento.displayId == displayId
4729 && memento.hovering) {
4730 return true;
4731 }
4732 }
4733 return false;
4734}
4735
4736bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4737 int32_t action, int32_t flags) {
4738 switch (action) {
4739 case AKEY_EVENT_ACTION_UP: {
4740 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4741 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4742 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4743 mFallbackKeys.removeItemsAt(i);
4744 } else {
4745 i += 1;
4746 }
4747 }
4748 }
4749 ssize_t index = findKeyMemento(entry);
4750 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004751 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 return true;
4753 }
4754 /* FIXME: We can't just drop the key up event because that prevents creating
4755 * popup windows that are automatically shown when a key is held and then
4756 * dismissed when the key is released. The problem is that the popup will
4757 * not have received the original key down, so the key up will be considered
4758 * to be inconsistent with its observed state. We could perhaps handle this
4759 * by synthesizing a key down but that will cause other problems.
4760 *
4761 * So for now, allow inconsistent key up events to be dispatched.
4762 *
4763#if DEBUG_OUTBOUND_EVENT_DETAILS
4764 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4765 "keyCode=%d, scanCode=%d",
4766 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4767#endif
4768 return false;
4769 */
4770 return true;
4771 }
4772
4773 case AKEY_EVENT_ACTION_DOWN: {
4774 ssize_t index = findKeyMemento(entry);
4775 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004776 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777 }
4778 addKeyMemento(entry, flags);
4779 return true;
4780 }
4781
4782 default:
4783 return true;
4784 }
4785}
4786
4787bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4788 int32_t action, int32_t flags) {
4789 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4790 switch (actionMasked) {
4791 case AMOTION_EVENT_ACTION_UP:
4792 case AMOTION_EVENT_ACTION_CANCEL: {
4793 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4794 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004795 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796 return true;
4797 }
4798#if DEBUG_OUTBOUND_EVENT_DETAILS
4799 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004800 "displayId=%" PRId32 ", actionMasked=%d",
4801 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802#endif
4803 return false;
4804 }
4805
4806 case AMOTION_EVENT_ACTION_DOWN: {
4807 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4808 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004809 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 }
4811 addMotionMemento(entry, flags, false /*hovering*/);
4812 return true;
4813 }
4814
4815 case AMOTION_EVENT_ACTION_POINTER_UP:
4816 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4817 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004818 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4819 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4820 // generate cancellation events for these since they're based in relative rather than
4821 // absolute units.
4822 return true;
4823 }
4824
Michael Wrightd02c5b62014-02-10 15:10:22 -08004825 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004826
4827 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4828 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4829 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4830 // other value and we need to track the motion so we can send cancellation events for
4831 // anything generating fallback events (e.g. DPad keys for joystick movements).
4832 if (index >= 0) {
4833 if (entry->pointerCoords[0].isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004834 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wright38dcdff2014-03-19 12:06:10 -07004835 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004836 MotionMemento& memento = mMotionMementos[index];
Michael Wright38dcdff2014-03-19 12:06:10 -07004837 memento.setPointers(entry);
4838 }
4839 } else if (!entry->pointerCoords[0].isEmpty()) {
4840 addMotionMemento(entry, flags, false /*hovering*/);
4841 }
4842
4843 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4844 return true;
4845 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004846 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004847 MotionMemento& memento = mMotionMementos[index];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 memento.setPointers(entry);
4849 return true;
4850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851#if DEBUG_OUTBOUND_EVENT_DETAILS
4852 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004853 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4854 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855#endif
4856 return false;
4857 }
4858
4859 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4860 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4861 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004862 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 return true;
4864 }
4865#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004866 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4867 "displayId=%" PRId32,
4868 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004869#endif
4870 return false;
4871 }
4872
4873 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4874 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4875 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4876 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004877 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878 }
4879 addMotionMemento(entry, flags, true /*hovering*/);
4880 return true;
4881 }
4882
4883 default:
4884 return true;
4885 }
4886}
4887
4888ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4889 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004890 const KeyMemento& memento = mKeyMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891 if (memento.deviceId == entry->deviceId
4892 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004893 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 && memento.keyCode == entry->keyCode
4895 && memento.scanCode == entry->scanCode) {
4896 return i;
4897 }
4898 }
4899 return -1;
4900}
4901
4902ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4903 bool hovering) const {
4904 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004905 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906 if (memento.deviceId == entry->deviceId
4907 && memento.source == entry->source
4908 && memento.displayId == entry->displayId
4909 && memento.hovering == hovering) {
4910 return i;
4911 }
4912 }
4913 return -1;
4914}
4915
4916void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004917 KeyMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918 memento.deviceId = entry->deviceId;
4919 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004920 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 memento.keyCode = entry->keyCode;
4922 memento.scanCode = entry->scanCode;
4923 memento.metaState = entry->metaState;
4924 memento.flags = flags;
4925 memento.downTime = entry->downTime;
4926 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004927 mKeyMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928}
4929
4930void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4931 int32_t flags, bool hovering) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004932 MotionMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 memento.deviceId = entry->deviceId;
4934 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004935 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936 memento.flags = flags;
4937 memento.xPrecision = entry->xPrecision;
4938 memento.yPrecision = entry->yPrecision;
4939 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940 memento.setPointers(entry);
4941 memento.hovering = hovering;
4942 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004943 mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944}
4945
4946void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4947 pointerCount = entry->pointerCount;
4948 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4949 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4950 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4951 }
4952}
4953
4954void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004955 std::vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4956 for (KeyMemento& memento : mKeyMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004957 if (shouldCancelKey(memento, options)) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004958 outEvents.push_back(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004959 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4961 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4962 }
4963 }
4964
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004965 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004966 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004967 const int32_t action = memento.hovering ?
4968 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004969 outEvents.push_back(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004970 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004971 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4972 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004974 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004975 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976 }
4977 }
4978}
4979
4980void InputDispatcher::InputState::clear() {
4981 mKeyMementos.clear();
4982 mMotionMementos.clear();
4983 mFallbackKeys.clear();
4984}
4985
4986void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4987 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004988 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004989 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4990 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004991 const MotionMemento& otherMemento = other.mMotionMementos[j];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992 if (memento.deviceId == otherMemento.deviceId
4993 && memento.source == otherMemento.source
4994 && memento.displayId == otherMemento.displayId) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004995 other.mMotionMementos.erase(other.mMotionMementos.begin() + j);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996 } else {
4997 j += 1;
4998 }
4999 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005000 other.mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001 }
5002 }
5003}
5004
5005int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
5006 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
5007 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
5008}
5009
5010void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
5011 int32_t fallbackKeyCode) {
5012 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
5013 if (index >= 0) {
5014 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
5015 } else {
5016 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
5017 }
5018}
5019
5020void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
5021 mFallbackKeys.removeItem(originalKeyCode);
5022}
5023
5024bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
5025 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005026 if (options.keyCode && memento.keyCode != options.keyCode.value()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005027 return false;
5028 }
5029
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 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
5041 return true;
5042 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
5043 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
5044 default:
5045 return false;
5046 }
5047}
5048
5049bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
5050 const CancelationOptions& options) {
Michael Wright3dd60e22019-03-27 22:06:44 +00005051 if (options.deviceId && memento.deviceId != options.deviceId.value()) {
5052 return false;
5053 }
5054
5055 if (options.displayId && memento.displayId != options.displayId.value()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005056 return false;
5057 }
5058
5059 switch (options.mode) {
5060 case CancelationOptions::CANCEL_ALL_EVENTS:
5061 return true;
5062 case CancelationOptions::CANCEL_POINTER_EVENTS:
5063 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
5064 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
5065 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
5066 default:
5067 return false;
5068 }
5069}
5070
5071
5072// --- InputDispatcher::Connection ---
5073
Robert Carr803535b2018-08-02 16:38:15 -07005074InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
5075 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08005076 monitor(monitor),
5077 inputPublisher(inputChannel), inputPublisherBlocked(false) {
5078}
5079
5080InputDispatcher::Connection::~Connection() {
5081}
5082
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08005083const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07005084 if (inputChannel != nullptr) {
5085 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 }
5087 if (monitor) {
5088 return "monitor";
5089 }
5090 return "?";
5091}
5092
5093const char* InputDispatcher::Connection::getStatusLabel() const {
5094 switch (status) {
5095 case STATUS_NORMAL:
5096 return "NORMAL";
5097
5098 case STATUS_BROKEN:
5099 return "BROKEN";
5100
5101 case STATUS_ZOMBIE:
5102 return "ZOMBIE";
5103
5104 default:
5105 return "UNKNOWN";
5106 }
5107}
5108
5109InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07005110 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111 if (entry->seq == seq) {
5112 return entry;
5113 }
5114 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005115 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116}
5117
Michael Wright3dd60e22019-03-27 22:06:44 +00005118// --- InputDispatcher::Monitor
5119InputDispatcher::Monitor::Monitor(const sp<InputChannel>& inputChannel) :
5120 inputChannel(inputChannel) {
5121}
5122
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123
5124// --- InputDispatcher::CommandEntry ---
Michael Wright3dd60e22019-03-27 22:06:44 +00005125//
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07005127 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128 seq(0), handled(false) {
5129}
5130
5131InputDispatcher::CommandEntry::~CommandEntry() {
5132}
5133
Michael Wright3dd60e22019-03-27 22:06:44 +00005134// --- InputDispatcher::TouchedMonitor ---
5135InputDispatcher::TouchedMonitor::TouchedMonitor(const Monitor& monitor, float xOffset,
5136 float yOffset) : monitor(monitor), xOffset(xOffset), yOffset(yOffset) {
5137}
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138
5139// --- InputDispatcher::TouchState ---
5140
5141InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01005142 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005143}
5144
5145InputDispatcher::TouchState::~TouchState() {
5146}
5147
5148void InputDispatcher::TouchState::reset() {
5149 down = false;
5150 split = false;
5151 deviceId = -1;
5152 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01005153 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005155 portalWindows.clear();
Michael Wright3dd60e22019-03-27 22:06:44 +00005156 gestureMonitors.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157}
5158
5159void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
5160 down = other.down;
5161 split = other.split;
5162 deviceId = other.deviceId;
5163 source = other.source;
5164 displayId = other.displayId;
5165 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005166 portalWindows = other.portalWindows;
Michael Wright3dd60e22019-03-27 22:06:44 +00005167 gestureMonitors = other.gestureMonitors;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005168}
5169
5170void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
5171 int32_t targetFlags, BitSet32 pointerIds) {
5172 if (targetFlags & InputTarget::FLAG_SPLIT) {
5173 split = true;
5174 }
5175
5176 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005177 TouchedWindow& touchedWindow = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178 if (touchedWindow.windowHandle == windowHandle) {
5179 touchedWindow.targetFlags |= targetFlags;
5180 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
5181 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
5182 }
5183 touchedWindow.pointerIds.value |= pointerIds.value;
5184 return;
5185 }
5186 }
5187
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005188 TouchedWindow touchedWindow;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005189 touchedWindow.windowHandle = windowHandle;
5190 touchedWindow.targetFlags = targetFlags;
5191 touchedWindow.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005192 windows.push_back(touchedWindow);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193}
5194
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005195void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
5196 size_t numWindows = portalWindows.size();
5197 for (size_t i = 0; i < numWindows; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005198 if (portalWindows[i] == windowHandle) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08005199 return;
5200 }
5201 }
5202 portalWindows.push_back(windowHandle);
5203}
5204
Michael Wright3dd60e22019-03-27 22:06:44 +00005205void InputDispatcher::TouchState::addGestureMonitors(
5206 const std::vector<TouchedMonitor>& newMonitors) {
5207 const size_t newSize = gestureMonitors.size() + newMonitors.size();
5208 gestureMonitors.reserve(newSize);
5209 gestureMonitors.insert(std::end(gestureMonitors),
5210 std::begin(newMonitors), std::end(newMonitors));
5211}
5212
Michael Wrightd02c5b62014-02-10 15:10:22 -08005213void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
5214 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005215 if (windows[i].windowHandle == windowHandle) {
5216 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005217 return;
5218 }
5219 }
5220}
5221
Robert Carr803535b2018-08-02 16:38:15 -07005222void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
5223 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005224 if (windows[i].windowHandle->getToken() == token) {
5225 windows.erase(windows.begin() + i);
Robert Carr803535b2018-08-02 16:38:15 -07005226 return;
5227 }
5228 }
5229}
5230
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
5232 for (size_t i = 0 ; i < windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005233 TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005234 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
5235 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
5236 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
5237 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
5238 i += 1;
5239 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005240 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241 }
5242 }
5243}
5244
Michael Wright3dd60e22019-03-27 22:06:44 +00005245void InputDispatcher::TouchState::filterNonMonitors() {
5246 windows.clear();
5247 portalWindows.clear();
5248}
5249
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
5251 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005252 const TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005253 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5254 return window.windowHandle;
5255 }
5256 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005257 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258}
5259
5260bool InputDispatcher::TouchState::isSlippery() const {
5261 // Must have exactly one foreground window.
5262 bool haveSlipperyForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005263 for (const TouchedWindow& window : windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5265 if (haveSlipperyForegroundWindow
5266 || !(window.windowHandle->getInfo()->layoutParamsFlags
5267 & InputWindowInfo::FLAG_SLIPPERY)) {
5268 return false;
5269 }
5270 haveSlipperyForegroundWindow = true;
5271 }
5272 }
5273 return haveSlipperyForegroundWindow;
5274}
5275
5276
5277// --- InputDispatcherThread ---
5278
5279InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5280 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5281}
5282
5283InputDispatcherThread::~InputDispatcherThread() {
5284}
5285
5286bool InputDispatcherThread::threadLoop() {
5287 mDispatcher->dispatchOnce();
5288 return true;
5289}
5290
5291} // namespace android