blob: 7324c28a816636f7552e6052a4696296e379dbc7 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
20//#define LOG_NDEBUG 0
21
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
38#define DEBUG_FOCUS 0
39
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wrightd02c5b62014-02-10 15:10:22 -080048#include <errno.h>
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>
61#include <ui/Region.h>
Robert Carr4e670e52018-08-15 13:26:12 -070062#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080063
64#define INDENT " "
65#define INDENT2 " "
66#define INDENT3 " "
67#define INDENT4 " "
68
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080069using android::base::StringPrintf;
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071namespace android {
72
73// Default input dispatching timeout if there is no focused application or paused window
74// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000075constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
77// Amount of time to allow for all pending events to be processed when an app switch
78// key is on the way. This is used to preempt input dispatch and drop input events
79// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000080constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080081
82// Amount of time to allow for an event to be dispatched (measured since its eventTime)
83// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000084constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080085
86// Amount of time to allow touch events to be streamed out to a connection before requiring
87// that the first event be finished. This value extends the ANR timeout by the specified
88// amount. For example, if streaming is allowed to get ahead by one second relative to the
89// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// 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 +000093constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
94
95// Log a warning when an interception call takes longer than this to process.
96constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
98// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +000099constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
100
Prabir Pradhan42611e02018-11-27 14:04:02 -0800101// Sequence number for synthesized or injected events.
102constexpr uint32_t SYNTHESIZED_EVENT_SEQUENCE_NUM = 0;
103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104
105static inline nsecs_t now() {
106 return systemTime(SYSTEM_TIME_MONOTONIC);
107}
108
109static inline const char* toString(bool value) {
110 return value ? "true" : "false";
111}
112
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800113static std::string motionActionToString(int32_t action) {
114 // Convert MotionEvent action to string
115 switch(action & AMOTION_EVENT_ACTION_MASK) {
116 case AMOTION_EVENT_ACTION_DOWN:
117 return "DOWN";
118 case AMOTION_EVENT_ACTION_MOVE:
119 return "MOVE";
120 case AMOTION_EVENT_ACTION_UP:
121 return "UP";
122 case AMOTION_EVENT_ACTION_POINTER_DOWN:
123 return "POINTER_DOWN";
124 case AMOTION_EVENT_ACTION_POINTER_UP:
125 return "POINTER_UP";
126 }
127 return StringPrintf("%" PRId32, action);
128}
129
130static std::string keyActionToString(int32_t action) {
131 // Convert KeyEvent action to string
132 switch(action) {
133 case AKEY_EVENT_ACTION_DOWN:
134 return "DOWN";
135 case AKEY_EVENT_ACTION_UP:
136 return "UP";
137 case AKEY_EVENT_ACTION_MULTIPLE:
138 return "MULTIPLE";
139 }
140 return StringPrintf("%" PRId32, action);
141}
142
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
144 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
145 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
146}
147
148static bool isValidKeyAction(int32_t action) {
149 switch (action) {
150 case AKEY_EVENT_ACTION_DOWN:
151 case AKEY_EVENT_ACTION_UP:
152 return true;
153 default:
154 return false;
155 }
156}
157
158static bool validateKeyEvent(int32_t action) {
159 if (! isValidKeyAction(action)) {
160 ALOGE("Key event has invalid action code 0x%x", action);
161 return false;
162 }
163 return true;
164}
165
Michael Wright7b159c92015-05-14 14:48:03 +0100166static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800167 switch (action & AMOTION_EVENT_ACTION_MASK) {
168 case AMOTION_EVENT_ACTION_DOWN:
169 case AMOTION_EVENT_ACTION_UP:
170 case AMOTION_EVENT_ACTION_CANCEL:
171 case AMOTION_EVENT_ACTION_MOVE:
172 case AMOTION_EVENT_ACTION_OUTSIDE:
173 case AMOTION_EVENT_ACTION_HOVER_ENTER:
174 case AMOTION_EVENT_ACTION_HOVER_MOVE:
175 case AMOTION_EVENT_ACTION_HOVER_EXIT:
176 case AMOTION_EVENT_ACTION_SCROLL:
177 return true;
178 case AMOTION_EVENT_ACTION_POINTER_DOWN:
179 case AMOTION_EVENT_ACTION_POINTER_UP: {
180 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800181 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800182 }
Michael Wright7b159c92015-05-14 14:48:03 +0100183 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
184 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
185 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186 default:
187 return false;
188 }
189}
190
Michael Wright7b159c92015-05-14 14:48:03 +0100191static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100193 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 ALOGE("Motion event has invalid action code 0x%x", action);
195 return false;
196 }
197 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000198 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 pointerCount, MAX_POINTERS);
200 return false;
201 }
202 BitSet32 pointerIdBits;
203 for (size_t i = 0; i < pointerCount; i++) {
204 int32_t id = pointerProperties[i].id;
205 if (id < 0 || id > MAX_POINTER_ID) {
206 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
207 id, MAX_POINTER_ID);
208 return false;
209 }
210 if (pointerIdBits.hasBit(id)) {
211 ALOGE("Motion event has duplicate pointer id %d", id);
212 return false;
213 }
214 pointerIdBits.markBit(id);
215 }
216 return true;
217}
218
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800219static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800221 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 return;
223 }
224
225 bool first = true;
226 Region::const_iterator cur = region.begin();
227 Region::const_iterator const tail = region.end();
228 while (cur != tail) {
229 if (first) {
230 first = false;
231 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800232 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800234 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800235 cur++;
236 }
237}
238
Tiger Huang721e26f2018-07-24 22:26:19 +0800239template<typename T, typename U>
240static T getValueByKey(std::unordered_map<U, T>& map, U key) {
241 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
242 return it != map.end() ? it->second : T{};
243}
244
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245
246// --- InputDispatcher ---
247
248InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
249 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700250 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100251 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700252 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800254 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
256 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800257 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258
Yi Kong9b14ac62018-07-17 13:48:38 -0700259 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260
261 policy->getDispatcherConfiguration(&mConfig);
262}
263
264InputDispatcher::~InputDispatcher() {
265 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800266 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267
268 resetKeyRepeatLocked();
269 releasePendingEventLocked();
270 drainInboundQueueLocked();
271 }
272
273 while (mConnectionsByFd.size() != 0) {
274 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
275 }
276}
277
278void InputDispatcher::dispatchOnce() {
279 nsecs_t nextWakeupTime = LONG_LONG_MAX;
280 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800281 std::scoped_lock _l(mLock);
282 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800283
284 // Run a dispatch loop if there are no pending commands.
285 // The dispatch loop might enqueue commands to run afterwards.
286 if (!haveCommandsLocked()) {
287 dispatchOnceInnerLocked(&nextWakeupTime);
288 }
289
290 // Run all pending commands if there are any.
291 // If any commands were run then force the next poll to wake up immediately.
292 if (runCommandsLockedInterruptible()) {
293 nextWakeupTime = LONG_LONG_MIN;
294 }
295 } // release lock
296
297 // Wait for callback or timeout or wake. (make sure we round up, not down)
298 nsecs_t currentTime = now();
299 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
300 mLooper->pollOnce(timeoutMillis);
301}
302
303void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
304 nsecs_t currentTime = now();
305
Jeff Browndc5992e2014-04-11 01:27:26 -0700306 // Reset the key repeat timer whenever normal dispatch is suspended while the
307 // device is in a non-interactive state. This is to ensure that we abort a key
308 // repeat if the device is just coming out of sleep.
309 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800310 resetKeyRepeatLocked();
311 }
312
313 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
314 if (mDispatchFrozen) {
315#if DEBUG_FOCUS
316 ALOGD("Dispatch frozen. Waiting some more.");
317#endif
318 return;
319 }
320
321 // Optimize latency of app switches.
322 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
323 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
324 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
325 if (mAppSwitchDueTime < *nextWakeupTime) {
326 *nextWakeupTime = mAppSwitchDueTime;
327 }
328
329 // Ready to start a new event.
330 // If we don't already have a pending event, go grab one.
331 if (! mPendingEvent) {
332 if (mInboundQueue.isEmpty()) {
333 if (isAppSwitchDue) {
334 // The inbound queue is empty so the app switch key we were waiting
335 // for will never arrive. Stop waiting for it.
336 resetPendingAppSwitchLocked(false);
337 isAppSwitchDue = false;
338 }
339
340 // Synthesize a key repeat if appropriate.
341 if (mKeyRepeatState.lastKeyEntry) {
342 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
343 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
344 } else {
345 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
346 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
347 }
348 }
349 }
350
351 // Nothing to do if there is no pending event.
352 if (!mPendingEvent) {
353 return;
354 }
355 } else {
356 // Inbound queue has at least one entry.
357 mPendingEvent = mInboundQueue.dequeueAtHead();
358 traceInboundQueueLengthLocked();
359 }
360
361 // Poke user activity for this event.
362 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
363 pokeUserActivityLocked(mPendingEvent);
364 }
365
366 // Get ready to dispatch the event.
367 resetANRTimeoutsLocked();
368 }
369
370 // Now we have an event to dispatch.
371 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700372 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800373 bool done = false;
374 DropReason dropReason = DROP_REASON_NOT_DROPPED;
375 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
376 dropReason = DROP_REASON_POLICY;
377 } else if (!mDispatchEnabled) {
378 dropReason = DROP_REASON_DISABLED;
379 }
380
381 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700382 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800383 }
384
385 switch (mPendingEvent->type) {
386 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
387 ConfigurationChangedEntry* typedEntry =
388 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
389 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
390 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
391 break;
392 }
393
394 case EventEntry::TYPE_DEVICE_RESET: {
395 DeviceResetEntry* typedEntry =
396 static_cast<DeviceResetEntry*>(mPendingEvent);
397 done = dispatchDeviceResetLocked(currentTime, typedEntry);
398 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
399 break;
400 }
401
402 case EventEntry::TYPE_KEY: {
403 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
404 if (isAppSwitchDue) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800405 if (isAppSwitchKeyEvent(typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406 resetPendingAppSwitchLocked(true);
407 isAppSwitchDue = false;
408 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
409 dropReason = DROP_REASON_APP_SWITCH;
410 }
411 }
412 if (dropReason == DROP_REASON_NOT_DROPPED
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800413 && isStaleEvent(currentTime, typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414 dropReason = DROP_REASON_STALE;
415 }
416 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
417 dropReason = DROP_REASON_BLOCKED;
418 }
419 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
420 break;
421 }
422
423 case EventEntry::TYPE_MOTION: {
424 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
425 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
426 dropReason = DROP_REASON_APP_SWITCH;
427 }
428 if (dropReason == DROP_REASON_NOT_DROPPED
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800429 && isStaleEvent(currentTime, typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800430 dropReason = DROP_REASON_STALE;
431 }
432 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
433 dropReason = DROP_REASON_BLOCKED;
434 }
435 done = dispatchMotionLocked(currentTime, typedEntry,
436 &dropReason, nextWakeupTime);
437 break;
438 }
439
440 default:
441 ALOG_ASSERT(false);
442 break;
443 }
444
445 if (done) {
446 if (dropReason != DROP_REASON_NOT_DROPPED) {
447 dropInboundEventLocked(mPendingEvent, dropReason);
448 }
Michael Wright3a981722015-06-10 15:26:13 +0100449 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450
451 releasePendingEventLocked();
452 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
453 }
454}
455
456bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
457 bool needWake = mInboundQueue.isEmpty();
458 mInboundQueue.enqueueAtTail(entry);
459 traceInboundQueueLengthLocked();
460
461 switch (entry->type) {
462 case EventEntry::TYPE_KEY: {
463 // Optimize app switch latency.
464 // If the application takes too long to catch up then we drop all events preceding
465 // the app switch key.
466 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800467 if (isAppSwitchKeyEvent(keyEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
469 mAppSwitchSawKeyDown = true;
470 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
471 if (mAppSwitchSawKeyDown) {
472#if DEBUG_APP_SWITCH
473 ALOGD("App switch is pending!");
474#endif
475 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
476 mAppSwitchSawKeyDown = false;
477 needWake = true;
478 }
479 }
480 }
481 break;
482 }
483
484 case EventEntry::TYPE_MOTION: {
485 // Optimize case where the current application is unresponsive and the user
486 // decides to touch a window in a different application.
487 // If the application takes too long to catch up then we drop all events preceding
488 // the touch into the other window.
489 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
490 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
491 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
492 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Robert Carr740167f2018-10-11 19:03:41 -0700493 && mInputTargetWaitApplicationToken != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494 int32_t displayId = motionEntry->displayId;
495 int32_t x = int32_t(motionEntry->pointerCoords[0].
496 getAxisValue(AMOTION_EVENT_AXIS_X));
497 int32_t y = int32_t(motionEntry->pointerCoords[0].
498 getAxisValue(AMOTION_EVENT_AXIS_Y));
499 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700500 if (touchedWindowHandle != nullptr
Robert Carr740167f2018-10-11 19:03:41 -0700501 && touchedWindowHandle->getApplicationToken()
502 != mInputTargetWaitApplicationToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503 // User touched a different application than the one we are waiting on.
504 // Flag the event, and start pruning the input queue.
505 mNextUnblockedEvent = motionEntry;
506 needWake = true;
507 }
508 }
509 break;
510 }
511 }
512
513 return needWake;
514}
515
516void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
517 entry->refCount += 1;
518 mRecentQueue.enqueueAtTail(entry);
519 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
520 mRecentQueue.dequeueAtHead()->release();
521 }
522}
523
524sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800525 int32_t x, int32_t y, bool addOutsideTargets, bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800527 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
528 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529 const InputWindowInfo* windowInfo = windowHandle->getInfo();
530 if (windowInfo->displayId == displayId) {
531 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532
533 if (windowInfo->visible) {
534 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
535 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
536 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
537 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800538 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
539 if (portalToDisplayId != ADISPLAY_ID_NONE
540 && portalToDisplayId != displayId) {
541 if (addPortalWindows) {
542 // For the monitoring channels of the display.
543 mTempTouchState.addPortalWindow(windowHandle);
544 }
545 return findTouchedWindowAtLocked(
546 portalToDisplayId, x, y, addOutsideTargets, addPortalWindows);
547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548 // Found window.
549 return windowHandle;
550 }
551 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800552
553 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
554 mTempTouchState.addOrUpdateWindow(
555 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 }
559 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700560 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561}
562
563void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
564 const char* reason;
565 switch (dropReason) {
566 case DROP_REASON_POLICY:
567#if DEBUG_INBOUND_EVENT_DETAILS
568 ALOGD("Dropped event because policy consumed it.");
569#endif
570 reason = "inbound event was dropped because the policy consumed it";
571 break;
572 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100573 if (mLastDropReason != DROP_REASON_DISABLED) {
574 ALOGI("Dropped event because input dispatch is disabled.");
575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576 reason = "inbound event was dropped because input dispatch is disabled";
577 break;
578 case DROP_REASON_APP_SWITCH:
579 ALOGI("Dropped event because of pending overdue app switch.");
580 reason = "inbound event was dropped because of pending overdue app switch";
581 break;
582 case DROP_REASON_BLOCKED:
583 ALOGI("Dropped event because the current application is not responding and the user "
584 "has started interacting with a different application.");
585 reason = "inbound event was dropped because the current application is not responding "
586 "and the user has started interacting with a different application";
587 break;
588 case DROP_REASON_STALE:
589 ALOGI("Dropped event because it is stale.");
590 reason = "inbound event was dropped because it is stale";
591 break;
592 default:
593 ALOG_ASSERT(false);
594 return;
595 }
596
597 switch (entry->type) {
598 case EventEntry::TYPE_KEY: {
599 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
600 synthesizeCancelationEventsForAllConnectionsLocked(options);
601 break;
602 }
603 case EventEntry::TYPE_MOTION: {
604 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
605 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
606 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
607 synthesizeCancelationEventsForAllConnectionsLocked(options);
608 } else {
609 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
610 synthesizeCancelationEventsForAllConnectionsLocked(options);
611 }
612 break;
613 }
614 }
615}
616
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800617static bool isAppSwitchKeyCode(int32_t keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618 return keyCode == AKEYCODE_HOME
619 || keyCode == AKEYCODE_ENDCALL
620 || keyCode == AKEYCODE_APP_SWITCH;
621}
622
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800623bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
625 && isAppSwitchKeyCode(keyEntry->keyCode)
626 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
627 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
628}
629
630bool InputDispatcher::isAppSwitchPendingLocked() {
631 return mAppSwitchDueTime != LONG_LONG_MAX;
632}
633
634void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
635 mAppSwitchDueTime = LONG_LONG_MAX;
636
637#if DEBUG_APP_SWITCH
638 if (handled) {
639 ALOGD("App switch has arrived.");
640 } else {
641 ALOGD("App switch was abandoned.");
642 }
643#endif
644}
645
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800646bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800647 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
648}
649
650bool InputDispatcher::haveCommandsLocked() const {
651 return !mCommandQueue.isEmpty();
652}
653
654bool InputDispatcher::runCommandsLockedInterruptible() {
655 if (mCommandQueue.isEmpty()) {
656 return false;
657 }
658
659 do {
660 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
661
662 Command command = commandEntry->command;
663 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
664
665 commandEntry->connection.clear();
666 delete commandEntry;
667 } while (! mCommandQueue.isEmpty());
668 return true;
669}
670
671InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
672 CommandEntry* commandEntry = new CommandEntry(command);
673 mCommandQueue.enqueueAtTail(commandEntry);
674 return commandEntry;
675}
676
677void InputDispatcher::drainInboundQueueLocked() {
678 while (! mInboundQueue.isEmpty()) {
679 EventEntry* entry = mInboundQueue.dequeueAtHead();
680 releaseInboundEventLocked(entry);
681 }
682 traceInboundQueueLengthLocked();
683}
684
685void InputDispatcher::releasePendingEventLocked() {
686 if (mPendingEvent) {
687 resetANRTimeoutsLocked();
688 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700689 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 }
691}
692
693void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
694 InjectionState* injectionState = entry->injectionState;
695 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
696#if DEBUG_DISPATCH_CYCLE
697 ALOGD("Injected inbound event was dropped.");
698#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800699 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700 }
701 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700702 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 }
704 addRecentEventLocked(entry);
705 entry->release();
706}
707
708void InputDispatcher::resetKeyRepeatLocked() {
709 if (mKeyRepeatState.lastKeyEntry) {
710 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700711 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 }
713}
714
715InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
716 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
717
718 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700719 uint32_t policyFlags = entry->policyFlags &
720 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721 if (entry->refCount == 1) {
722 entry->recycle();
723 entry->eventTime = currentTime;
724 entry->policyFlags = policyFlags;
725 entry->repeatCount += 1;
726 } else {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800727 KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100728 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 entry->action, entry->flags, entry->keyCode, entry->scanCode,
730 entry->metaState, entry->repeatCount + 1, entry->downTime);
731
732 mKeyRepeatState.lastKeyEntry = newEntry;
733 entry->release();
734
735 entry = newEntry;
736 }
737 entry->syntheticRepeat = true;
738
739 // Increment reference count since we keep a reference to the event in
740 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
741 entry->refCount += 1;
742
743 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
744 return entry;
745}
746
747bool InputDispatcher::dispatchConfigurationChangedLocked(
748 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
749#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700750 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751#endif
752
753 // Reset key repeating in case a keyboard device was added or removed or something.
754 resetKeyRepeatLocked();
755
756 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
757 CommandEntry* commandEntry = postCommandLocked(
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800758 & InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 commandEntry->eventTime = entry->eventTime;
760 return true;
761}
762
763bool InputDispatcher::dispatchDeviceResetLocked(
764 nsecs_t currentTime, DeviceResetEntry* entry) {
765#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700766 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
767 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768#endif
769
770 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
771 "device was reset");
772 options.deviceId = entry->deviceId;
773 synthesizeCancelationEventsForAllConnectionsLocked(options);
774 return true;
775}
776
777bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
778 DropReason* dropReason, nsecs_t* nextWakeupTime) {
779 // Preprocessing.
780 if (! entry->dispatchInProgress) {
781 if (entry->repeatCount == 0
782 && entry->action == AKEY_EVENT_ACTION_DOWN
783 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
784 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
785 if (mKeyRepeatState.lastKeyEntry
786 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
787 // We have seen two identical key downs in a row which indicates that the device
788 // driver is automatically generating key repeats itself. We take note of the
789 // repeat here, but we disable our own next key repeat timer since it is clear that
790 // we will not need to synthesize key repeats ourselves.
791 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
792 resetKeyRepeatLocked();
793 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
794 } else {
795 // Not a repeat. Save key down state in case we do see a repeat later.
796 resetKeyRepeatLocked();
797 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
798 }
799 mKeyRepeatState.lastKeyEntry = entry;
800 entry->refCount += 1;
801 } else if (! entry->syntheticRepeat) {
802 resetKeyRepeatLocked();
803 }
804
805 if (entry->repeatCount == 1) {
806 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
807 } else {
808 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
809 }
810
811 entry->dispatchInProgress = true;
812
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800813 logOutboundKeyDetails("dispatchKey - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 }
815
816 // Handle case where the policy asked us to try again later last time.
817 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
818 if (currentTime < entry->interceptKeyWakeupTime) {
819 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
820 *nextWakeupTime = entry->interceptKeyWakeupTime;
821 }
822 return false; // wait until next wakeup
823 }
824 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
825 entry->interceptKeyWakeupTime = 0;
826 }
827
828 // Give the policy a chance to intercept the key.
829 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
830 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
831 CommandEntry* commandEntry = postCommandLocked(
832 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800833 sp<InputWindowHandle> focusedWindowHandle =
834 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
835 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700836 commandEntry->inputChannel =
837 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 }
839 commandEntry->keyEntry = entry;
840 entry->refCount += 1;
841 return false; // wait for the command to run
842 } else {
843 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
844 }
845 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
846 if (*dropReason == DROP_REASON_NOT_DROPPED) {
847 *dropReason = DROP_REASON_POLICY;
848 }
849 }
850
851 // Clean up if dropping the event.
852 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800853 setInjectionResult(entry, *dropReason == DROP_REASON_POLICY
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800855 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 return true;
857 }
858
859 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800860 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
862 entry, inputTargets, nextWakeupTime);
863 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
864 return false;
865 }
866
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800867 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
869 return true;
870 }
871
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800872 // Add monitor channels from event's or focused display.
873 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874
875 // Dispatch the key.
876 dispatchEventLocked(currentTime, entry, inputTargets);
877 return true;
878}
879
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800880void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100882 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
883 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800884 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100886 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800888 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889#endif
890}
891
892bool InputDispatcher::dispatchMotionLocked(
893 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
894 // Preprocessing.
895 if (! entry->dispatchInProgress) {
896 entry->dispatchInProgress = true;
897
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800898 logOutboundMotionDetails("dispatchMotion - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 }
900
901 // Clean up if dropping the event.
902 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800903 setInjectionResult(entry, *dropReason == DROP_REASON_POLICY
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
905 return true;
906 }
907
908 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
909
910 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800911 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912
913 bool conflictingPointerActions = false;
914 int32_t injectionResult;
915 if (isPointerEvent) {
916 // Pointer event. (eg. touchscreen)
917 injectionResult = findTouchedWindowTargetsLocked(currentTime,
918 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
919 } else {
920 // Non touch event. (eg. trackball)
921 injectionResult = findFocusedWindowTargetsLocked(currentTime,
922 entry, inputTargets, nextWakeupTime);
923 }
924 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
925 return false;
926 }
927
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800928 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100930 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
931 CancelationOptions::Mode mode(isPointerEvent ?
932 CancelationOptions::CANCEL_POINTER_EVENTS :
933 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
934 CancelationOptions options(mode, "input event injection failed");
935 synthesizeCancelationEventsForMonitorsLocked(options);
936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937 return true;
938 }
939
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800940 // Add monitor channels from event's or focused display.
941 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800943 if (isPointerEvent) {
944 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
945 if (stateIndex >= 0) {
946 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800947 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800948 // The event has gone through these portal windows, so we add monitoring targets of
949 // the corresponding displays as well.
950 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800951 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800952 addMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
953 -windowInfo->frameLeft, -windowInfo->frameTop);
954 }
955 }
956 }
957 }
958
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959 // Dispatch the motion.
960 if (conflictingPointerActions) {
961 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
962 "conflicting pointer actions");
963 synthesizeCancelationEventsForAllConnectionsLocked(options);
964 }
965 dispatchEventLocked(currentTime, entry, inputTargets);
966 return true;
967}
968
969
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800970void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800972 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
973 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100974 "action=0x%x, actionButton=0x%x, flags=0x%x, "
975 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800976 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800978 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100979 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 entry->metaState, entry->buttonState,
981 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800982 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983
984 for (uint32_t i = 0; i < entry->pointerCount; i++) {
985 ALOGD(" Pointer %d: id=%d, toolType=%d, "
986 "x=%f, y=%f, pressure=%f, size=%f, "
987 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800988 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 i, entry->pointerProperties[i].id,
990 entry->pointerProperties[i].toolType,
991 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
992 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
993 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
994 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
995 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
996 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
997 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
998 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800999 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 }
1001#endif
1002}
1003
1004void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001005 EventEntry* eventEntry, const std::vector<InputTarget>& inputTargets) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006#if DEBUG_DISPATCH_CYCLE
1007 ALOGD("dispatchEventToCurrentInputTargets");
1008#endif
1009
1010 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1011
1012 pokeUserActivityLocked(eventEntry);
1013
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001014 for (const InputTarget& inputTarget : inputTargets) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
1016 if (connectionIndex >= 0) {
1017 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1018 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1019 } else {
1020#if DEBUG_FOCUS
1021 ALOGD("Dropping event delivery to target with channel '%s' because it "
1022 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001023 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024#endif
1025 }
1026 }
1027}
1028
1029int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1030 const EventEntry* entry,
1031 const sp<InputApplicationHandle>& applicationHandle,
1032 const sp<InputWindowHandle>& windowHandle,
1033 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001034 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1036#if DEBUG_FOCUS
1037 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1038#endif
1039 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1040 mInputTargetWaitStartTime = currentTime;
1041 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1042 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001043 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 }
1045 } else {
1046 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1047#if DEBUG_FOCUS
1048 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001049 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 reason);
1051#endif
1052 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001053 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001055 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 timeout = applicationHandle->getDispatchingTimeout(
1057 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1058 } else {
1059 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1060 }
1061
1062 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1063 mInputTargetWaitStartTime = currentTime;
1064 mInputTargetWaitTimeoutTime = currentTime + timeout;
1065 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001066 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067
Yi Kong9b14ac62018-07-17 13:48:38 -07001068 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001069 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 }
Robert Carr740167f2018-10-11 19:03:41 -07001071 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1072 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
1074 }
1075 }
1076
1077 if (mInputTargetWaitTimeoutExpired) {
1078 return INPUT_EVENT_INJECTION_TIMED_OUT;
1079 }
1080
1081 if (currentTime >= mInputTargetWaitTimeoutTime) {
1082 onANRLocked(currentTime, applicationHandle, windowHandle,
1083 entry->eventTime, mInputTargetWaitStartTime, reason);
1084
1085 // Force poll loop to wake up immediately on next iteration once we get the
1086 // ANR response back from the policy.
1087 *nextWakeupTime = LONG_LONG_MIN;
1088 return INPUT_EVENT_INJECTION_PENDING;
1089 } else {
1090 // Force poll loop to wake up when timeout is due.
1091 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1092 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1093 }
1094 return INPUT_EVENT_INJECTION_PENDING;
1095 }
1096}
1097
Robert Carr803535b2018-08-02 16:38:15 -07001098void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1099 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1100 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1101 state.removeWindowByToken(token);
1102 }
1103}
1104
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1106 const sp<InputChannel>& inputChannel) {
1107 if (newTimeout > 0) {
1108 // Extend the timeout.
1109 mInputTargetWaitTimeoutTime = now() + newTimeout;
1110 } else {
1111 // Give up.
1112 mInputTargetWaitTimeoutExpired = true;
1113
1114 // Input state will not be realistic. Mark it out of sync.
1115 if (inputChannel.get()) {
1116 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1117 if (connectionIndex >= 0) {
1118 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001119 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120
Robert Carr803535b2018-08-02 16:38:15 -07001121 if (token != nullptr) {
1122 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 }
1124
1125 if (connection->status == Connection::STATUS_NORMAL) {
1126 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1127 "application not responding");
1128 synthesizeCancelationEventsForConnectionLocked(connection, options);
1129 }
1130 }
1131 }
1132 }
1133}
1134
1135nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1136 nsecs_t currentTime) {
1137 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1138 return currentTime - mInputTargetWaitStartTime;
1139 }
1140 return 0;
1141}
1142
1143void InputDispatcher::resetANRTimeoutsLocked() {
1144#if DEBUG_FOCUS
1145 ALOGD("Resetting ANR timeouts.");
1146#endif
1147
1148 // Reset input target wait timeout.
1149 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001150 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151}
1152
Tiger Huang721e26f2018-07-24 22:26:19 +08001153/**
1154 * Get the display id that the given event should go to. If this event specifies a valid display id,
1155 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1156 * Focused display is the display that the user most recently interacted with.
1157 */
1158int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1159 int32_t displayId;
1160 switch (entry->type) {
1161 case EventEntry::TYPE_KEY: {
1162 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1163 displayId = typedEntry->displayId;
1164 break;
1165 }
1166 case EventEntry::TYPE_MOTION: {
1167 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1168 displayId = typedEntry->displayId;
1169 break;
1170 }
1171 default: {
1172 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1173 return ADISPLAY_ID_NONE;
1174 }
1175 }
1176 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1177}
1178
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001180 const EventEntry* entry, std::vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001182 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183
Tiger Huang721e26f2018-07-24 22:26:19 +08001184 int32_t displayId = getTargetDisplayId(entry);
1185 sp<InputWindowHandle> focusedWindowHandle =
1186 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1187 sp<InputApplicationHandle> focusedApplicationHandle =
1188 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1189
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 // If there is no currently focused window and no focused application
1191 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001192 if (focusedWindowHandle == nullptr) {
1193 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001195 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 "Waiting because no window has focus but there is a "
1197 "focused application that may eventually add a window "
1198 "when it finishes starting up.");
1199 goto Unresponsive;
1200 }
1201
Arthur Hung3b413f22018-10-26 18:05:34 +08001202 ALOGI("Dropping event because there is no focused window or focused application in display "
1203 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1205 goto Failed;
1206 }
1207
1208 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001209 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1211 goto Failed;
1212 }
1213
Jeff Brownffb49772014-10-10 19:01:34 -07001214 // Check whether the window is ready for more input.
1215 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001216 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001217 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001219 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 goto Unresponsive;
1221 }
1222
1223 // Success! Output targets.
1224 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001225 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1227 inputTargets);
1228
1229 // Done.
1230Failed:
1231Unresponsive:
1232 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001233 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234#if DEBUG_FOCUS
1235 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1236 "timeSpentWaitingForApplication=%0.1fms",
1237 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1238#endif
1239 return injectionResult;
1240}
1241
1242int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001243 const MotionEntry* entry, std::vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 bool* outConflictingPointerActions) {
1245 enum InjectionPermission {
1246 INJECTION_PERMISSION_UNKNOWN,
1247 INJECTION_PERMISSION_GRANTED,
1248 INJECTION_PERMISSION_DENIED
1249 };
1250
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 // For security reasons, we defer updating the touch state until we are sure that
1252 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 int32_t displayId = entry->displayId;
1254 int32_t action = entry->action;
1255 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1256
1257 // Update the touch state as needed based on the properties of the touch event.
1258 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1259 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1260 sp<InputWindowHandle> newHoverWindowHandle;
1261
Jeff Brownf086ddb2014-02-11 14:28:48 -08001262 // Copy current touch state into mTempTouchState.
1263 // This state is always reset at the end of this function, so if we don't find state
1264 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001265 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001266 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1267 if (oldStateIndex >= 0) {
1268 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1269 mTempTouchState.copyFrom(*oldState);
1270 }
1271
1272 bool isSplit = mTempTouchState.split;
1273 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1274 && (mTempTouchState.deviceId != entry->deviceId
1275 || mTempTouchState.source != entry->source
1276 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1278 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1279 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1280 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1281 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1282 || isHoverAction);
1283 bool wrongDevice = false;
1284 if (newGesture) {
1285 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001286 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001288 ALOGD("Dropping event because a pointer for a different device is already down "
1289 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001291 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1293 switchedDevice = false;
1294 wrongDevice = true;
1295 goto Failed;
1296 }
1297 mTempTouchState.reset();
1298 mTempTouchState.down = down;
1299 mTempTouchState.deviceId = entry->deviceId;
1300 mTempTouchState.source = entry->source;
1301 mTempTouchState.displayId = displayId;
1302 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001303 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1304#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001305 ALOGI("Dropping move event because a pointer for a different device is already active "
1306 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001307#endif
1308 // TODO: test multiple simultaneous input streams.
1309 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1310 switchedDevice = false;
1311 wrongDevice = true;
1312 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 }
1314
1315 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1316 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1317
1318 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1319 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1320 getAxisValue(AMOTION_EVENT_AXIS_X));
1321 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1322 getAxisValue(AMOTION_EVENT_AXIS_Y));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001323 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(
1324 displayId, x, y, maskedAction == AMOTION_EVENT_ACTION_DOWN, true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001327 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1329 // New window supports splitting.
1330 isSplit = true;
1331 } else if (isSplit) {
1332 // New window does not support splitting but we have already split events.
1333 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001334 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 }
1336
1337 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001338 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 // Try to assign the pointer to the first foreground window we find, if there is one.
1340 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001341 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001342 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1343 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1345 goto Failed;
1346 }
1347 }
1348
1349 // Set target flags.
1350 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1351 if (isSplit) {
1352 targetFlags |= InputTarget::FLAG_SPLIT;
1353 }
1354 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1355 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001356 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1357 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 }
1359
1360 // Update hover state.
1361 if (isHoverAction) {
1362 newHoverWindowHandle = newTouchedWindowHandle;
1363 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1364 newHoverWindowHandle = mLastHoverWindowHandle;
1365 }
1366
1367 // Update the temporary touch state.
1368 BitSet32 pointerIds;
1369 if (isSplit) {
1370 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1371 pointerIds.markBit(pointerId);
1372 }
1373 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1374 } else {
1375 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1376
1377 // If the pointer is not currently down, then ignore the event.
1378 if (! mTempTouchState.down) {
1379#if DEBUG_FOCUS
1380 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001381 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382#endif
1383 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1384 goto Failed;
1385 }
1386
1387 // Check whether touches should slip outside of the current foreground window.
1388 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1389 && entry->pointerCount == 1
1390 && mTempTouchState.isSlippery()) {
1391 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1392 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1393
1394 sp<InputWindowHandle> oldTouchedWindowHandle =
1395 mTempTouchState.getFirstForegroundWindowHandle();
1396 sp<InputWindowHandle> newTouchedWindowHandle =
1397 findTouchedWindowAtLocked(displayId, x, y);
1398 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001399 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001401 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001402 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001403 newTouchedWindowHandle->getName().c_str(),
1404 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405#endif
1406 // Make a slippery exit from the old window.
1407 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1408 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1409
1410 // Make a slippery entrance into the new window.
1411 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1412 isSplit = true;
1413 }
1414
1415 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1416 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1417 if (isSplit) {
1418 targetFlags |= InputTarget::FLAG_SPLIT;
1419 }
1420 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1421 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1422 }
1423
1424 BitSet32 pointerIds;
1425 if (isSplit) {
1426 pointerIds.markBit(entry->pointerProperties[0].id);
1427 }
1428 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1429 }
1430 }
1431 }
1432
1433 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1434 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001435 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436#if DEBUG_HOVER
1437 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001438 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439#endif
1440 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1441 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1442 }
1443
1444 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001445 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446#if DEBUG_HOVER
1447 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001448 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449#endif
1450 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1451 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1452 }
1453 }
1454
1455 // Check permission to inject into all touched foreground windows and ensure there
1456 // is at least one touched foreground window.
1457 {
1458 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001459 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1461 haveForegroundWindow = true;
1462 if (! checkInjectionPermission(touchedWindow.windowHandle,
1463 entry->injectionState)) {
1464 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1465 injectionPermission = INJECTION_PERMISSION_DENIED;
1466 goto Failed;
1467 }
1468 }
1469 }
1470 if (! haveForegroundWindow) {
1471#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001472 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1473 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474#endif
1475 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1476 goto Failed;
1477 }
1478
1479 // Permission granted to injection into all touched foreground windows.
1480 injectionPermission = INJECTION_PERMISSION_GRANTED;
1481 }
1482
1483 // Check whether windows listening for outside touches are owned by the same UID. If it is
1484 // set the policy flag that we will not reveal coordinate information to this window.
1485 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1486 sp<InputWindowHandle> foregroundWindowHandle =
1487 mTempTouchState.getFirstForegroundWindowHandle();
1488 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001489 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1491 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1492 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1493 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1494 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1495 }
1496 }
1497 }
1498 }
1499
1500 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001501 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001503 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001504 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001505 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001506 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001508 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 goto Unresponsive;
1510 }
1511 }
1512 }
1513
1514 // If this is the first pointer going down and the touched window has a wallpaper
1515 // then also add the touched wallpaper windows so they are locked in for the duration
1516 // of the touch gesture.
1517 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1518 // engine only supports touch events. We would need to add a mechanism similar
1519 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1520 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1521 sp<InputWindowHandle> foregroundWindowHandle =
1522 mTempTouchState.getFirstForegroundWindowHandle();
1523 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001524 const std::vector<sp<InputWindowHandle>> windowHandles =
1525 getWindowHandlesLocked(displayId);
1526 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 const InputWindowInfo* info = windowHandle->getInfo();
1528 if (info->displayId == displayId
1529 && windowHandle->getInfo()->layoutParamsType
1530 == InputWindowInfo::TYPE_WALLPAPER) {
1531 mTempTouchState.addOrUpdateWindow(windowHandle,
1532 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001533 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 | InputTarget::FLAG_DISPATCH_AS_IS,
1535 BitSet32(0));
1536 }
1537 }
1538 }
1539 }
1540
1541 // Success! Output targets.
1542 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1543
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001544 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1546 touchedWindow.pointerIds, inputTargets);
1547 }
1548
1549 // Drop the outside or hover touch windows since we will not care about them
1550 // in the next iteration.
1551 mTempTouchState.filterNonAsIsTouchWindows();
1552
1553Failed:
1554 // Check injection permission once and for all.
1555 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001556 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 injectionPermission = INJECTION_PERMISSION_GRANTED;
1558 } else {
1559 injectionPermission = INJECTION_PERMISSION_DENIED;
1560 }
1561 }
1562
1563 // Update final pieces of touch state if the injector had permission.
1564 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1565 if (!wrongDevice) {
1566 if (switchedDevice) {
1567#if DEBUG_FOCUS
1568 ALOGD("Conflicting pointer actions: Switched to a different device.");
1569#endif
1570 *outConflictingPointerActions = true;
1571 }
1572
1573 if (isHoverAction) {
1574 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001575 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576#if DEBUG_FOCUS
1577 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1578#endif
1579 *outConflictingPointerActions = true;
1580 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001581 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1583 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001584 mTempTouchState.deviceId = entry->deviceId;
1585 mTempTouchState.source = entry->source;
1586 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 }
1588 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1589 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1590 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001591 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1593 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001594 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595#if DEBUG_FOCUS
1596 ALOGD("Conflicting pointer actions: Down received while already down.");
1597#endif
1598 *outConflictingPointerActions = true;
1599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1601 // One pointer went up.
1602 if (isSplit) {
1603 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1604 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1605
1606 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001607 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1609 touchedWindow.pointerIds.clearBit(pointerId);
1610 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001611 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 continue;
1613 }
1614 }
1615 i += 1;
1616 }
1617 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001618 }
1619
1620 // Save changes unless the action was scroll in which case the temporary touch
1621 // state was only valid for this one action.
1622 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1623 if (mTempTouchState.displayId >= 0) {
1624 if (oldStateIndex >= 0) {
1625 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1626 } else {
1627 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1628 }
1629 } else if (oldStateIndex >= 0) {
1630 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 }
1633
1634 // Update hover state.
1635 mLastHoverWindowHandle = newHoverWindowHandle;
1636 }
1637 } else {
1638#if DEBUG_FOCUS
1639 ALOGD("Not updating touch focus because injection was denied.");
1640#endif
1641 }
1642
1643Unresponsive:
1644 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1645 mTempTouchState.reset();
1646
1647 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001648 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649#if DEBUG_FOCUS
1650 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1651 "timeSpentWaitingForApplication=%0.1fms",
1652 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1653#endif
1654 return injectionResult;
1655}
1656
1657void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001658 int32_t targetFlags, BitSet32 pointerIds, std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001659 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1660 if (inputChannel == nullptr) {
1661 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1662 return;
1663 }
1664
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001666 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001667 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 target.flags = targetFlags;
1669 target.xOffset = - windowInfo->frameLeft;
1670 target.yOffset = - windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001671 target.globalScaleFactor = windowInfo->globalScaleFactor;
1672 target.windowXScale = windowInfo->windowXScale;
1673 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001675 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676}
1677
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001678void InputDispatcher::addMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001679 int32_t displayId, float xOffset, float yOffset) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001680 std::unordered_map<int32_t, std::vector<sp<InputChannel>>>::const_iterator it =
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001681 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001683 if (it != mMonitoringChannelsByDisplay.end()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001684 const std::vector<sp<InputChannel>>& monitoringChannels = it->second;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001685 const size_t numChannels = monitoringChannels.size();
1686 for (size_t i = 0; i < numChannels; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001687 InputTarget target;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001688 target.inputChannel = monitoringChannels[i];
1689 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001690 target.xOffset = xOffset;
1691 target.yOffset = yOffset;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001692 target.pointerIds.clear();
Robert Carre07e1032018-11-26 12:55:53 -08001693 target.globalScaleFactor = 1.0f;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001694 inputTargets.push_back(target);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001695 }
1696 } else {
1697 // If there is no monitor channel registered or all monitor channel unregistered,
1698 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001699 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 }
1701}
1702
1703bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1704 const InjectionState* injectionState) {
1705 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001706 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1708 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001709 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1711 "owned by uid %d",
1712 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001713 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 windowHandle->getInfo()->ownerUid);
1715 } else {
1716 ALOGW("Permission denied: injecting event from pid %d uid %d",
1717 injectionState->injectorPid, injectionState->injectorUid);
1718 }
1719 return false;
1720 }
1721 return true;
1722}
1723
1724bool InputDispatcher::isWindowObscuredAtPointLocked(
1725 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1726 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001727 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1728 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 if (otherHandle == windowHandle) {
1730 break;
1731 }
1732
1733 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1734 if (otherInfo->displayId == displayId
1735 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1736 && otherInfo->frameContainsPoint(x, y)) {
1737 return true;
1738 }
1739 }
1740 return false;
1741}
1742
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001743
1744bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1745 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001746 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001747 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001748 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001749 if (otherHandle == windowHandle) {
1750 break;
1751 }
1752
1753 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1754 if (otherInfo->displayId == displayId
1755 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1756 && otherInfo->overlaps(windowInfo)) {
1757 return true;
1758 }
1759 }
1760 return false;
1761}
1762
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001763std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001764 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1765 const char* targetType) {
1766 // If the window is paused then keep waiting.
1767 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001768 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001769 }
1770
1771 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001772 ssize_t connectionIndex = getConnectionIndexLocked(
1773 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001774 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001775 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001776 "registered with the input dispatcher. The window may be in the process "
1777 "of being removed.", targetType);
1778 }
1779
1780 // If the connection is dead then keep waiting.
1781 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1782 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001783 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001784 "The window may be in the process of being removed.", targetType,
1785 connection->getStatusLabel());
1786 }
1787
1788 // If the connection is backed up then keep waiting.
1789 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001790 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001791 "Outbound queue length: %d. Wait queue length: %d.",
1792 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1793 }
1794
1795 // Ensure that the dispatch queues aren't too far backed up for this event.
1796 if (eventEntry->type == EventEntry::TYPE_KEY) {
1797 // If the event is a key event, then we must wait for all previous events to
1798 // complete before delivering it because previous events may have the
1799 // side-effect of transferring focus to a different window and we want to
1800 // ensure that the following keys are sent to the new window.
1801 //
1802 // Suppose the user touches a button in a window then immediately presses "A".
1803 // If the button causes a pop-up window to appear then we want to ensure that
1804 // the "A" key is delivered to the new pop-up window. This is because users
1805 // often anticipate pending UI changes when typing on a keyboard.
1806 // To obtain this behavior, we must serialize key events with respect to all
1807 // prior input events.
1808 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001809 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001810 "finished processing all of the input events that were previously "
1811 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1812 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 }
Jeff Brownffb49772014-10-10 19:01:34 -07001814 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815 // Touch events can always be sent to a window immediately because the user intended
1816 // to touch whatever was visible at the time. Even if focus changes or a new
1817 // window appears moments later, the touch event was meant to be delivered to
1818 // whatever window happened to be on screen at the time.
1819 //
1820 // Generic motion events, such as trackball or joystick events are a little trickier.
1821 // Like key events, generic motion events are delivered to the focused window.
1822 // Unlike key events, generic motion events don't tend to transfer focus to other
1823 // windows and it is not important for them to be serialized. So we prefer to deliver
1824 // generic motion events as soon as possible to improve efficiency and reduce lag
1825 // through batching.
1826 //
1827 // The one case where we pause input event delivery is when the wait queue is piling
1828 // up with lots of events because the application is not responding.
1829 // This condition ensures that ANRs are detected reliably.
1830 if (!connection->waitQueue.isEmpty()
1831 && currentTime >= connection->waitQueue.head->deliveryTime
1832 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001833 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001834 "finished processing certain input events that were delivered to it over "
1835 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1836 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1837 connection->waitQueue.count(),
1838 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 }
1840 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001841 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842}
1843
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001844std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 const sp<InputApplicationHandle>& applicationHandle,
1846 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001847 if (applicationHandle != nullptr) {
1848 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001849 std::string label(applicationHandle->getName());
1850 label += " - ";
1851 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 return label;
1853 } else {
1854 return applicationHandle->getName();
1855 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001856 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 return windowHandle->getName();
1858 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001859 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 }
1861}
1862
1863void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001864 int32_t displayId = getTargetDisplayId(eventEntry);
1865 sp<InputWindowHandle> focusedWindowHandle =
1866 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1867 if (focusedWindowHandle != nullptr) {
1868 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1870#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001871 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872#endif
1873 return;
1874 }
1875 }
1876
1877 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1878 switch (eventEntry->type) {
1879 case EventEntry::TYPE_MOTION: {
1880 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1881 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1882 return;
1883 }
1884
1885 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1886 eventType = USER_ACTIVITY_EVENT_TOUCH;
1887 }
1888 break;
1889 }
1890 case EventEntry::TYPE_KEY: {
1891 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1892 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1893 return;
1894 }
1895 eventType = USER_ACTIVITY_EVENT_BUTTON;
1896 break;
1897 }
1898 }
1899
1900 CommandEntry* commandEntry = postCommandLocked(
1901 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1902 commandEntry->eventTime = eventEntry->eventTime;
1903 commandEntry->userActivityEventType = eventType;
1904}
1905
1906void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1907 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1908#if DEBUG_DISPATCH_CYCLE
1909 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Robert Carre07e1032018-11-26 12:55:53 -08001910 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1911 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001912 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913 inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001914 inputTarget->globalScaleFactor,
1915 inputTarget->windowXScale, inputTarget->windowYScale,
1916 inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917#endif
1918
1919 // Skip this event if the connection status is not normal.
1920 // We don't want to enqueue additional outbound events if the connection is broken.
1921 if (connection->status != Connection::STATUS_NORMAL) {
1922#if DEBUG_DISPATCH_CYCLE
1923 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001924 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925#endif
1926 return;
1927 }
1928
1929 // Split a motion event if needed.
1930 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1931 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1932
1933 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1934 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1935 MotionEntry* splitMotionEntry = splitMotionEvent(
1936 originalMotionEntry, inputTarget->pointerIds);
1937 if (!splitMotionEntry) {
1938 return; // split event was dropped
1939 }
1940#if DEBUG_FOCUS
1941 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001942 connection->getInputChannelName().c_str());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001943 logOutboundMotionDetails(" ", splitMotionEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944#endif
1945 enqueueDispatchEntriesLocked(currentTime, connection,
1946 splitMotionEntry, inputTarget);
1947 splitMotionEntry->release();
1948 return;
1949 }
1950 }
1951
1952 // Not splitting. Enqueue dispatch entries for the event as is.
1953 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1954}
1955
1956void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1957 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1958 bool wasEmpty = connection->outboundQueue.isEmpty();
1959
1960 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07001961 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07001963 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07001965 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07001967 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07001969 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07001971 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1973
1974 // If the outbound queue was previously empty, start the dispatch cycle going.
1975 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1976 startDispatchCycleLocked(currentTime, connection);
1977 }
1978}
1979
chaviw8c9cf542019-03-25 13:02:48 -07001980void InputDispatcher::enqueueDispatchEntryLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1982 int32_t dispatchMode) {
1983 int32_t inputTargetFlags = inputTarget->flags;
1984 if (!(inputTargetFlags & dispatchMode)) {
1985 return;
1986 }
1987 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1988
1989 // This is a new event.
1990 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1991 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1992 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001993 inputTarget->globalScaleFactor, inputTarget->windowXScale,
1994 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995
1996 // Apply target flags and update the connection's input state.
1997 switch (eventEntry->type) {
1998 case EventEntry::TYPE_KEY: {
1999 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2000 dispatchEntry->resolvedAction = keyEntry->action;
2001 dispatchEntry->resolvedFlags = keyEntry->flags;
2002
2003 if (!connection->inputState.trackKey(keyEntry,
2004 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2005#if DEBUG_DISPATCH_CYCLE
2006 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002007 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008#endif
2009 delete dispatchEntry;
2010 return; // skip the inconsistent event
2011 }
2012 break;
2013 }
2014
2015 case EventEntry::TYPE_MOTION: {
2016 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2017 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2018 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2019 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2020 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2021 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2022 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2023 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2024 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2025 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2026 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2027 } else {
2028 dispatchEntry->resolvedAction = motionEntry->action;
2029 }
2030 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2031 && !connection->inputState.isHovering(
2032 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2033#if DEBUG_DISPATCH_CYCLE
2034 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002035 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036#endif
2037 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2038 }
2039
2040 dispatchEntry->resolvedFlags = motionEntry->flags;
2041 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2042 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2043 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002044 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2045 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047
2048 if (!connection->inputState.trackMotion(motionEntry,
2049 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2050#if DEBUG_DISPATCH_CYCLE
2051 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002052 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053#endif
2054 delete dispatchEntry;
2055 return; // skip the inconsistent event
2056 }
chaviw8c9cf542019-03-25 13:02:48 -07002057
2058 dispatchPointerDownOutsideFocusIfNecessary(motionEntry->source,
2059 dispatchEntry->resolvedAction, inputTarget->inputChannel->getToken());
2060
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 break;
2062 }
2063 }
2064
2065 // Remember that we are waiting for this dispatch to complete.
2066 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002067 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068 }
2069
2070 // Enqueue the dispatch entry.
2071 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002072 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002073
2074}
2075
2076void InputDispatcher::dispatchPointerDownOutsideFocusIfNecessary(uint32_t source, int32_t action,
2077 const sp<IBinder>& newToken) {
2078 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2079 if (source != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
2080 return;
2081 }
2082
2083 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2084 if (inputWindowHandle == nullptr) {
2085 return;
2086 }
2087
2088 int32_t displayId = inputWindowHandle->getInfo()->displayId;
2089 sp<InputWindowHandle> focusedWindowHandle =
2090 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2091
2092 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2093
2094 if (!hasFocusChanged) {
2095 return;
2096 }
2097
2098 // Dispatch onPointerDownOutsideFocus to the policy.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099}
2100
2101void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2102 const sp<Connection>& connection) {
2103#if DEBUG_DISPATCH_CYCLE
2104 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002105 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106#endif
2107
2108 while (connection->status == Connection::STATUS_NORMAL
2109 && !connection->outboundQueue.isEmpty()) {
2110 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2111 dispatchEntry->deliveryTime = currentTime;
2112
2113 // Publish the event.
2114 status_t status;
2115 EventEntry* eventEntry = dispatchEntry->eventEntry;
2116 switch (eventEntry->type) {
2117 case EventEntry::TYPE_KEY: {
2118 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2119
2120 // Publish the key event.
2121 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002122 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2124 keyEntry->keyCode, keyEntry->scanCode,
2125 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2126 keyEntry->eventTime);
2127 break;
2128 }
2129
2130 case EventEntry::TYPE_MOTION: {
2131 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2132
2133 PointerCoords scaledCoords[MAX_POINTERS];
2134 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2135
2136 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002137 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2139 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002140 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2141 float wxs = dispatchEntry->windowXScale;
2142 float wys = dispatchEntry->windowYScale;
2143 xOffset = dispatchEntry->xOffset * wxs;
2144 yOffset = dispatchEntry->yOffset * wys;
2145 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002146 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002148 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 }
2150 usingCoords = scaledCoords;
2151 }
2152 } else {
2153 xOffset = 0.0f;
2154 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155
2156 // We don't want the dispatch target to know.
2157 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002158 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 scaledCoords[i].clear();
2160 }
2161 usingCoords = scaledCoords;
2162 }
2163 }
2164
2165 // Publish the motion event.
2166 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002167 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002168 dispatchEntry->resolvedAction, motionEntry->actionButton,
2169 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002170 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification,
Michael Wright7b159c92015-05-14 14:48:03 +01002171 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 motionEntry->downTime, motionEntry->eventTime,
2173 motionEntry->pointerCount, motionEntry->pointerProperties,
2174 usingCoords);
2175 break;
2176 }
2177
2178 default:
2179 ALOG_ASSERT(false);
2180 return;
2181 }
2182
2183 // Check the result.
2184 if (status) {
2185 if (status == WOULD_BLOCK) {
2186 if (connection->waitQueue.isEmpty()) {
2187 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2188 "This is unexpected because the wait queue is empty, so the pipe "
2189 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002190 "event to it, status=%d", connection->getInputChannelName().c_str(),
2191 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2193 } else {
2194 // Pipe is full and we are waiting for the app to finish process some events
2195 // before sending more events to it.
2196#if DEBUG_DISPATCH_CYCLE
2197 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2198 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002199 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200#endif
2201 connection->inputPublisherBlocked = true;
2202 }
2203 } else {
2204 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002205 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2207 }
2208 return;
2209 }
2210
2211 // Re-enqueue the event on the wait queue.
2212 connection->outboundQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002213 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 connection->waitQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002215 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 }
2217}
2218
2219void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2220 const sp<Connection>& connection, uint32_t seq, bool handled) {
2221#if DEBUG_DISPATCH_CYCLE
2222 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002223 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224#endif
2225
2226 connection->inputPublisherBlocked = false;
2227
2228 if (connection->status == Connection::STATUS_BROKEN
2229 || connection->status == Connection::STATUS_ZOMBIE) {
2230 return;
2231 }
2232
2233 // Notify other system components and prepare to start the next dispatch cycle.
2234 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2235}
2236
2237void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2238 const sp<Connection>& connection, bool notify) {
2239#if DEBUG_DISPATCH_CYCLE
2240 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002241 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242#endif
2243
2244 // Clear the dispatch queues.
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002245 drainDispatchQueue(&connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002246 traceOutboundQueueLength(connection);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002247 drainDispatchQueue(&connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002248 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249
2250 // The connection appears to be unrecoverably broken.
2251 // Ignore already broken or zombie connections.
2252 if (connection->status == Connection::STATUS_NORMAL) {
2253 connection->status = Connection::STATUS_BROKEN;
2254
2255 if (notify) {
2256 // Notify other system components.
2257 onDispatchCycleBrokenLocked(currentTime, connection);
2258 }
2259 }
2260}
2261
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002262void InputDispatcher::drainDispatchQueue(Queue<DispatchEntry>* queue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 while (!queue->isEmpty()) {
2264 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002265 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 }
2267}
2268
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002269void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002271 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 }
2273 delete dispatchEntry;
2274}
2275
2276int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2277 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2278
2279 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002280 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281
2282 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2283 if (connectionIndex < 0) {
2284 ALOGE("Received spurious receive callback for unknown input channel. "
2285 "fd=%d, events=0x%x", fd, events);
2286 return 0; // remove the callback
2287 }
2288
2289 bool notify;
2290 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2291 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2292 if (!(events & ALOOPER_EVENT_INPUT)) {
2293 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002294 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 return 1;
2296 }
2297
2298 nsecs_t currentTime = now();
2299 bool gotOne = false;
2300 status_t status;
2301 for (;;) {
2302 uint32_t seq;
2303 bool handled;
2304 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2305 if (status) {
2306 break;
2307 }
2308 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2309 gotOne = true;
2310 }
2311 if (gotOne) {
2312 d->runCommandsLockedInterruptible();
2313 if (status == WOULD_BLOCK) {
2314 return 1;
2315 }
2316 }
2317
2318 notify = status != DEAD_OBJECT || !connection->monitor;
2319 if (notify) {
2320 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002321 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 }
2323 } else {
2324 // Monitor channels are never explicitly unregistered.
2325 // We do it automatically when the remote endpoint is closed so don't warn
2326 // about them.
2327 notify = !connection->monitor;
2328 if (notify) {
2329 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002330 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 }
2332 }
2333
2334 // Unregister the channel.
2335 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2336 return 0; // remove the callback
2337 } // release lock
2338}
2339
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002340void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked (
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341 const CancelationOptions& options) {
2342 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2343 synthesizeCancelationEventsForConnectionLocked(
2344 mConnectionsByFd.valueAt(i), options);
2345 }
2346}
2347
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002348void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked (
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002349 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002350 for (auto& it : mMonitoringChannelsByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002351 const std::vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002352 const size_t numChannels = monitoringChannels.size();
2353 for (size_t i = 0; i < numChannels; i++) {
2354 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2355 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002356 }
2357}
2358
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2360 const sp<InputChannel>& channel, const CancelationOptions& options) {
2361 ssize_t index = getConnectionIndexLocked(channel);
2362 if (index >= 0) {
2363 synthesizeCancelationEventsForConnectionLocked(
2364 mConnectionsByFd.valueAt(index), options);
2365 }
2366}
2367
2368void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2369 const sp<Connection>& connection, const CancelationOptions& options) {
2370 if (connection->status == Connection::STATUS_BROKEN) {
2371 return;
2372 }
2373
2374 nsecs_t currentTime = now();
2375
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002376 std::vector<EventEntry*> cancelationEvents;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377 connection->inputState.synthesizeCancelationEvents(currentTime,
2378 cancelationEvents, options);
2379
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002380 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002382 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002384 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385 options.reason, options.mode);
2386#endif
2387 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002388 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 switch (cancelationEventEntry->type) {
2390 case EventEntry::TYPE_KEY:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002391 logOutboundKeyDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 static_cast<KeyEntry*>(cancelationEventEntry));
2393 break;
2394 case EventEntry::TYPE_MOTION:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002395 logOutboundMotionDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 static_cast<MotionEntry*>(cancelationEventEntry));
2397 break;
2398 }
2399
2400 InputTarget target;
chaviwfbe5d9c2018-12-26 12:23:37 -08002401 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(
2402 connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002403 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2405 target.xOffset = -windowInfo->frameLeft;
2406 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002407 target.globalScaleFactor = windowInfo->globalScaleFactor;
2408 target.windowXScale = windowInfo->windowXScale;
2409 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 } else {
2411 target.xOffset = 0;
2412 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002413 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414 }
2415 target.inputChannel = connection->inputChannel;
2416 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2417
chaviw8c9cf542019-03-25 13:02:48 -07002418 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2420
2421 cancelationEventEntry->release();
2422 }
2423
2424 startDispatchCycleLocked(currentTime, connection);
2425 }
2426}
2427
2428InputDispatcher::MotionEntry*
2429InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2430 ALOG_ASSERT(pointerIds.value != 0);
2431
2432 uint32_t splitPointerIndexMap[MAX_POINTERS];
2433 PointerProperties splitPointerProperties[MAX_POINTERS];
2434 PointerCoords splitPointerCoords[MAX_POINTERS];
2435
2436 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2437 uint32_t splitPointerCount = 0;
2438
2439 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2440 originalPointerIndex++) {
2441 const PointerProperties& pointerProperties =
2442 originalMotionEntry->pointerProperties[originalPointerIndex];
2443 uint32_t pointerId = uint32_t(pointerProperties.id);
2444 if (pointerIds.hasBit(pointerId)) {
2445 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2446 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2447 splitPointerCoords[splitPointerCount].copyFrom(
2448 originalMotionEntry->pointerCoords[originalPointerIndex]);
2449 splitPointerCount += 1;
2450 }
2451 }
2452
2453 if (splitPointerCount != pointerIds.count()) {
2454 // This is bad. We are missing some of the pointers that we expected to deliver.
2455 // Most likely this indicates that we received an ACTION_MOVE events that has
2456 // different pointer ids than we expected based on the previous ACTION_DOWN
2457 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2458 // in this way.
2459 ALOGW("Dropping split motion event because the pointer count is %d but "
2460 "we expected there to be %d pointers. This probably means we received "
2461 "a broken sequence of pointer ids from the input device.",
2462 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002463 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 }
2465
2466 int32_t action = originalMotionEntry->action;
2467 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2468 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2469 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2470 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2471 const PointerProperties& pointerProperties =
2472 originalMotionEntry->pointerProperties[originalPointerIndex];
2473 uint32_t pointerId = uint32_t(pointerProperties.id);
2474 if (pointerIds.hasBit(pointerId)) {
2475 if (pointerIds.count() == 1) {
2476 // The first/last pointer went down/up.
2477 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2478 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2479 } else {
2480 // A secondary pointer went down/up.
2481 uint32_t splitPointerIndex = 0;
2482 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2483 splitPointerIndex += 1;
2484 }
2485 action = maskedAction | (splitPointerIndex
2486 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2487 }
2488 } else {
2489 // An unrelated pointer changed.
2490 action = AMOTION_EVENT_ACTION_MOVE;
2491 }
2492 }
2493
2494 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002495 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 originalMotionEntry->eventTime,
2497 originalMotionEntry->deviceId,
2498 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002499 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 originalMotionEntry->policyFlags,
2501 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002502 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 originalMotionEntry->flags,
2504 originalMotionEntry->metaState,
2505 originalMotionEntry->buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002506 originalMotionEntry->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507 originalMotionEntry->edgeFlags,
2508 originalMotionEntry->xPrecision,
2509 originalMotionEntry->yPrecision,
2510 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002511 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512
2513 if (originalMotionEntry->injectionState) {
2514 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2515 splitMotionEntry->injectionState->refCount += 1;
2516 }
2517
2518 return splitMotionEntry;
2519}
2520
2521void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2522#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002523 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002524#endif
2525
2526 bool needWake;
2527 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002528 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529
Prabir Pradhan42611e02018-11-27 14:04:02 -08002530 ConfigurationChangedEntry* newEntry =
2531 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 needWake = enqueueInboundEventLocked(newEntry);
2533 } // release lock
2534
2535 if (needWake) {
2536 mLooper->wake();
2537 }
2538}
2539
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002540/**
2541 * If one of the meta shortcuts is detected, process them here:
2542 * Meta + Backspace -> generate BACK
2543 * Meta + Enter -> generate HOME
2544 * This will potentially overwrite keyCode and metaState.
2545 */
2546void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2547 int32_t& keyCode, int32_t& metaState) {
2548 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2549 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2550 if (keyCode == AKEYCODE_DEL) {
2551 newKeyCode = AKEYCODE_BACK;
2552 } else if (keyCode == AKEYCODE_ENTER) {
2553 newKeyCode = AKEYCODE_HOME;
2554 }
2555 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002556 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002557 struct KeyReplacement replacement = {keyCode, deviceId};
2558 mReplacedKeys.add(replacement, newKeyCode);
2559 keyCode = newKeyCode;
2560 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2561 }
2562 } else if (action == AKEY_EVENT_ACTION_UP) {
2563 // In order to maintain a consistent stream of up and down events, check to see if the key
2564 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2565 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002566 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002567 struct KeyReplacement replacement = {keyCode, deviceId};
2568 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2569 if (index >= 0) {
2570 keyCode = mReplacedKeys.valueAt(index);
2571 mReplacedKeys.removeItemsAt(index);
2572 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2573 }
2574 }
2575}
2576
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2578#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002579 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002580 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002581 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002582 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002584 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585#endif
2586 if (!validateKeyEvent(args->action)) {
2587 return;
2588 }
2589
2590 uint32_t policyFlags = args->policyFlags;
2591 int32_t flags = args->flags;
2592 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002593 // InputDispatcher tracks and generates key repeats on behalf of
2594 // whatever notifies it, so repeatCount should always be set to 0
2595 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2597 policyFlags |= POLICY_FLAG_VIRTUAL;
2598 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 if (policyFlags & POLICY_FLAG_FUNCTION) {
2601 metaState |= AMETA_FUNCTION_ON;
2602 }
2603
2604 policyFlags |= POLICY_FLAG_TRUSTED;
2605
Michael Wright78f24442014-08-06 15:55:28 -07002606 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002607 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002608
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002610 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002611 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 args->downTime, args->eventTime);
2613
Michael Wright2b3c3302018-03-02 17:19:13 +00002614 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002616 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2617 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2618 std::to_string(t.duration().count()).c_str());
2619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621 bool needWake;
2622 { // acquire lock
2623 mLock.lock();
2624
2625 if (shouldSendKeyToInputFilterLocked(args)) {
2626 mLock.unlock();
2627
2628 policyFlags |= POLICY_FLAG_FILTERED;
2629 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2630 return; // event was consumed by the filter
2631 }
2632
2633 mLock.lock();
2634 }
2635
Prabir Pradhan42611e02018-11-27 14:04:02 -08002636 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002637 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002638 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639 metaState, repeatCount, args->downTime);
2640
2641 needWake = enqueueInboundEventLocked(newEntry);
2642 mLock.unlock();
2643 } // release lock
2644
2645 if (needWake) {
2646 mLooper->wake();
2647 }
2648}
2649
2650bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2651 return mInputFilterEnabled;
2652}
2653
2654void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2655#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002656 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2657 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002658 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002659 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2660 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002661 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002662 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663 for (uint32_t i = 0; i < args->pointerCount; i++) {
2664 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2665 "x=%f, y=%f, pressure=%f, size=%f, "
2666 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2667 "orientation=%f",
2668 i, args->pointerProperties[i].id,
2669 args->pointerProperties[i].toolType,
2670 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2671 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2672 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2673 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2674 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2675 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2676 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2677 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2678 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2679 }
2680#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002681 if (!validateMotionEvent(args->action, args->actionButton,
2682 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683 return;
2684 }
2685
2686 uint32_t policyFlags = args->policyFlags;
2687 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002688
2689 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002690 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002691 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2692 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2693 std::to_string(t.duration().count()).c_str());
2694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695
2696 bool needWake;
2697 { // acquire lock
2698 mLock.lock();
2699
2700 if (shouldSendMotionToInputFilterLocked(args)) {
2701 mLock.unlock();
2702
2703 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002704 event.initialize(args->deviceId, args->source, args->displayId,
2705 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002706 args->flags, args->edgeFlags, args->metaState, args->buttonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002707 args->classification, 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 args->downTime, args->eventTime,
2709 args->pointerCount, args->pointerProperties, args->pointerCoords);
2710
2711 policyFlags |= POLICY_FLAG_FILTERED;
2712 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2713 return; // event was consumed by the filter
2714 }
2715
2716 mLock.lock();
2717 }
2718
2719 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002720 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002721 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002722 args->action, args->actionButton, args->flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002723 args->metaState, args->buttonState, args->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002725 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726
2727 needWake = enqueueInboundEventLocked(newEntry);
2728 mLock.unlock();
2729 } // release lock
2730
2731 if (needWake) {
2732 mLooper->wake();
2733 }
2734}
2735
2736bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002737 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738}
2739
2740void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2741#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002742 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2743 "switchMask=0x%08x",
2744 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745#endif
2746
2747 uint32_t policyFlags = args->policyFlags;
2748 policyFlags |= POLICY_FLAG_TRUSTED;
2749 mPolicy->notifySwitch(args->eventTime,
2750 args->switchValues, args->switchMask, policyFlags);
2751}
2752
2753void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2754#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002755 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756 args->eventTime, args->deviceId);
2757#endif
2758
2759 bool needWake;
2760 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002761 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762
Prabir Pradhan42611e02018-11-27 14:04:02 -08002763 DeviceResetEntry* newEntry =
2764 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 needWake = enqueueInboundEventLocked(newEntry);
2766 } // release lock
2767
2768 if (needWake) {
2769 mLooper->wake();
2770 }
2771}
2772
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002773int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2775 uint32_t policyFlags) {
2776#if DEBUG_INBOUND_EVENT_DETAILS
2777 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002778 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2779 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780#endif
2781
2782 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2783
2784 policyFlags |= POLICY_FLAG_INJECTED;
2785 if (hasInjectionPermission(injectorPid, injectorUid)) {
2786 policyFlags |= POLICY_FLAG_TRUSTED;
2787 }
2788
2789 EventEntry* firstInjectedEntry;
2790 EventEntry* lastInjectedEntry;
2791 switch (event->getType()) {
2792 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002793 KeyEvent keyEvent;
2794 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2795 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 if (! validateKeyEvent(action)) {
2797 return INPUT_EVENT_INJECTION_FAILED;
2798 }
2799
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002800 int32_t flags = keyEvent.getFlags();
2801 int32_t keyCode = keyEvent.getKeyCode();
2802 int32_t metaState = keyEvent.getMetaState();
2803 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2804 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002805 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002806 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002807 keyEvent.getDownTime(), keyEvent.getEventTime());
2808
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2810 policyFlags |= POLICY_FLAG_VIRTUAL;
2811 }
2812
2813 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002814 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002815 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002816 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2817 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2818 std::to_string(t.duration().count()).c_str());
2819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 }
2821
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002823 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002824 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002826 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2827 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 lastInjectedEntry = firstInjectedEntry;
2829 break;
2830 }
2831
2832 case AINPUT_EVENT_TYPE_MOTION: {
2833 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 int32_t action = motionEvent->getAction();
2835 size_t pointerCount = motionEvent->getPointerCount();
2836 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002837 int32_t actionButton = motionEvent->getActionButton();
Charles Chen3611f1f2019-01-29 17:26:18 +08002838 int32_t displayId = motionEvent->getDisplayId();
Michael Wright7b159c92015-05-14 14:48:03 +01002839 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840 return INPUT_EVENT_INJECTION_FAILED;
2841 }
2842
2843 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2844 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002845 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002846 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002847 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2848 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2849 std::to_string(t.duration().count()).c_str());
2850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 }
2852
2853 mLock.lock();
2854 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2855 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002856 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002857 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2858 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002859 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002861 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002863 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002864 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2865 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 lastInjectedEntry = firstInjectedEntry;
2867 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2868 sampleEventTimes += 1;
2869 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002870 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2871 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002872 motionEvent->getDeviceId(), motionEvent->getSource(),
2873 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002874 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002876 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002878 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002879 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2880 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881 lastInjectedEntry->next = nextInjectedEntry;
2882 lastInjectedEntry = nextInjectedEntry;
2883 }
2884 break;
2885 }
2886
2887 default:
2888 ALOGW("Cannot inject event of type %d", event->getType());
2889 return INPUT_EVENT_INJECTION_FAILED;
2890 }
2891
2892 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2893 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2894 injectionState->injectionIsAsync = true;
2895 }
2896
2897 injectionState->refCount += 1;
2898 lastInjectedEntry->injectionState = injectionState;
2899
2900 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002901 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902 EventEntry* nextEntry = entry->next;
2903 needWake |= enqueueInboundEventLocked(entry);
2904 entry = nextEntry;
2905 }
2906
2907 mLock.unlock();
2908
2909 if (needWake) {
2910 mLooper->wake();
2911 }
2912
2913 int32_t injectionResult;
2914 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002915 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916
2917 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2918 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2919 } else {
2920 for (;;) {
2921 injectionResult = injectionState->injectionResult;
2922 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2923 break;
2924 }
2925
2926 nsecs_t remainingTimeout = endTime - now();
2927 if (remainingTimeout <= 0) {
2928#if DEBUG_INJECTION
2929 ALOGD("injectInputEvent - Timed out waiting for injection result "
2930 "to become available.");
2931#endif
2932 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2933 break;
2934 }
2935
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002936 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 }
2938
2939 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2940 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2941 while (injectionState->pendingForegroundDispatches != 0) {
2942#if DEBUG_INJECTION
2943 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2944 injectionState->pendingForegroundDispatches);
2945#endif
2946 nsecs_t remainingTimeout = endTime - now();
2947 if (remainingTimeout <= 0) {
2948#if DEBUG_INJECTION
2949 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2950 "dispatches to finish.");
2951#endif
2952 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2953 break;
2954 }
2955
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002956 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957 }
2958 }
2959 }
2960
2961 injectionState->release();
2962 } // release lock
2963
2964#if DEBUG_INJECTION
2965 ALOGD("injectInputEvent - Finished with result %d. "
2966 "injectorPid=%d, injectorUid=%d",
2967 injectionResult, injectorPid, injectorUid);
2968#endif
2969
2970 return injectionResult;
2971}
2972
2973bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2974 return injectorUid == 0
2975 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2976}
2977
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002978void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002979 InjectionState* injectionState = entry->injectionState;
2980 if (injectionState) {
2981#if DEBUG_INJECTION
2982 ALOGD("Setting input event injection result to %d. "
2983 "injectorPid=%d, injectorUid=%d",
2984 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2985#endif
2986
2987 if (injectionState->injectionIsAsync
2988 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2989 // Log the outcome since the injector did not wait for the injection result.
2990 switch (injectionResult) {
2991 case INPUT_EVENT_INJECTION_SUCCEEDED:
2992 ALOGV("Asynchronous input event injection succeeded.");
2993 break;
2994 case INPUT_EVENT_INJECTION_FAILED:
2995 ALOGW("Asynchronous input event injection failed.");
2996 break;
2997 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2998 ALOGW("Asynchronous input event injection permission denied.");
2999 break;
3000 case INPUT_EVENT_INJECTION_TIMED_OUT:
3001 ALOGW("Asynchronous input event injection timed out.");
3002 break;
3003 }
3004 }
3005
3006 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003007 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003008 }
3009}
3010
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003011void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012 InjectionState* injectionState = entry->injectionState;
3013 if (injectionState) {
3014 injectionState->pendingForegroundDispatches += 1;
3015 }
3016}
3017
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003018void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 InjectionState* injectionState = entry->injectionState;
3020 if (injectionState) {
3021 injectionState->pendingForegroundDispatches -= 1;
3022
3023 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003024 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 }
3026 }
3027}
3028
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003029std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3030 int32_t displayId) const {
3031 std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>::const_iterator it =
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003032 mWindowHandlesByDisplay.find(displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003033 if(it != mWindowHandlesByDisplay.end()) {
3034 return it->second;
3035 }
3036
3037 // Return an empty one if nothing found.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003038 return std::vector<sp<InputWindowHandle>>();
Arthur Hungb92218b2018-08-14 12:00:21 +08003039}
3040
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003042 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003043 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003044 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3045 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003046 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003047 return windowHandle;
3048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049 }
3050 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003051 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052}
3053
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003054bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003055 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003056 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3057 for (const sp<InputWindowHandle>& handle : windowHandles) {
3058 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003059 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003060 ALOGE("Found window %s in display %" PRId32
3061 ", but it should belong to display %" PRId32,
3062 windowHandle->getName().c_str(), it.first,
3063 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003064 }
3065 return true;
3066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067 }
3068 }
3069 return false;
3070}
3071
Robert Carr5c8a0262018-10-03 16:30:44 -07003072sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3073 size_t count = mInputChannelsByToken.count(token);
3074 if (count == 0) {
3075 return nullptr;
3076 }
3077 return mInputChannelsByToken.at(token);
3078}
3079
Arthur Hungb92218b2018-08-14 12:00:21 +08003080/**
3081 * Called from InputManagerService, update window handle list by displayId that can receive input.
3082 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3083 * If set an empty list, remove all handles from the specific display.
3084 * For focused handle, check if need to change and send a cancel event to previous one.
3085 * For removed handle, check if need to send a cancel event if already in touch.
3086 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003087void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
chaviw291d88a2019-02-14 10:33:58 -08003088 int32_t displayId, const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003090 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091#endif
3092 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003093 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094
Arthur Hungb92218b2018-08-14 12:00:21 +08003095 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003096 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3097 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098
Tiger Huang721e26f2018-07-24 22:26:19 +08003099 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003101
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003102 if (inputWindowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003103 // Remove all handles on a display if there are no windows left.
3104 mWindowHandlesByDisplay.erase(displayId);
3105 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003106 // Since we compare the pointer of input window handles across window updates, we need
3107 // to make sure the handle object for the same window stays unchanged across updates.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003108 const std::vector<sp<InputWindowHandle>>& oldHandles =
3109 mWindowHandlesByDisplay[displayId];
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003110 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003111 for (const sp<InputWindowHandle>& handle : oldHandles) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003112 oldHandlesByTokens[handle->getToken()] = handle;
3113 }
3114
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003115 std::vector<sp<InputWindowHandle>> newHandles;
3116 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
Siarhei Vishniakou77dd4972019-01-30 09:50:04 -08003117 if (!handle->updateInfo()) {
3118 // handle no longer valid
3119 continue;
3120 }
3121 const InputWindowInfo* info = handle->getInfo();
3122
3123 if ((getInputChannelLocked(handle->getToken()) == nullptr &&
3124 info->portalToDisplayId == ADISPLAY_ID_NONE)) {
3125 const bool noInputChannel =
3126 info->inputFeatures & InputWindowInfo::INPUT_FEATURE_NO_INPUT_CHANNEL;
3127 const bool canReceiveInput =
3128 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_TOUCHABLE) ||
3129 !(info->layoutParamsFlags & InputWindowInfo::FLAG_NOT_FOCUSABLE);
3130 if (canReceiveInput && !noInputChannel) {
3131 ALOGE("Window handle %s has no registered input channel",
3132 handle->getName().c_str());
3133 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003134 continue;
3135 }
3136
Siarhei Vishniakou77dd4972019-01-30 09:50:04 -08003137 if (info->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003138 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Siarhei Vishniakou77dd4972019-01-30 09:50:04 -08003139 handle->getName().c_str(), displayId, info->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003140 continue;
3141 }
3142
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003143 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3144 const sp<InputWindowHandle> oldHandle =
3145 oldHandlesByTokens.at(handle->getToken());
3146 oldHandle->updateFrom(handle);
3147 newHandles.push_back(oldHandle);
3148 } else {
3149 newHandles.push_back(handle);
3150 }
3151 }
3152
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003153 for (const sp<InputWindowHandle>& windowHandle : newHandles) {
Arthur Hung7ab76b12019-01-09 19:17:20 +08003154 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3155 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3156 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003157 newFocusedWindowHandle = windowHandle;
3158 }
3159 if (windowHandle == mLastHoverWindowHandle) {
3160 foundHoveredWindow = true;
3161 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003162 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003163
3164 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003165 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 }
3167
3168 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003169 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 }
3171
Tiger Huang721e26f2018-07-24 22:26:19 +08003172 sp<InputWindowHandle> oldFocusedWindowHandle =
3173 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3174
3175 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3176 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003178 ALOGD("Focus left window: %s in display %" PRId32,
3179 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003181 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3182 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003183 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3185 "focus left window");
3186 synthesizeCancelationEventsForInputChannelLocked(
3187 focusedInputChannel, options);
3188 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003189 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003191 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003193 ALOGD("Focus entered window: %s in display %" PRId32,
3194 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003195#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003196 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003197 }
Robert Carrf759f162018-11-13 12:57:11 -08003198
3199 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003200 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003201 }
3202
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 }
3204
Arthur Hungb92218b2018-08-14 12:00:21 +08003205 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3206 if (stateIndex >= 0) {
3207 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003208 for (size_t i = 0; i < state.windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003209 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003210 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003211#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003212 ALOGD("Touched window was removed: %s in display %" PRId32,
3213 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003215 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003216 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003217 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003218 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3219 "touched window was removed");
3220 synthesizeCancelationEventsForInputChannelLocked(
3221 touchedInputChannel, options);
3222 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003223 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003224 } else {
3225 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 }
3228 }
3229
3230 // Release information for windows that are no longer present.
3231 // This ensures that unused input channels are released promptly.
3232 // Otherwise, they might stick around until the window handle is destroyed
3233 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003234 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003235 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003237 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003239 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 }
3241 }
3242 } // release lock
3243
3244 // Wake up poll loop since it may need to make new input dispatching choices.
3245 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003246
3247 if (setInputWindowsListener) {
3248 setInputWindowsListener->onSetInputWindowsFinished();
3249 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250}
3251
3252void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003253 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003255 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256#endif
3257 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003258 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259
Tiger Huang721e26f2018-07-24 22:26:19 +08003260 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3261 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003262 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003263 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3264 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003265 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003267 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003269 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003271 oldFocusedApplicationHandle.clear();
3272 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273 }
3274
3275#if DEBUG_FOCUS
3276 //logDispatchStateLocked();
3277#endif
3278 } // release lock
3279
3280 // Wake up poll loop since it may need to make new input dispatching choices.
3281 mLooper->wake();
3282}
3283
Tiger Huang721e26f2018-07-24 22:26:19 +08003284/**
3285 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3286 * the display not specified.
3287 *
3288 * We track any unreleased events for each window. If a window loses the ability to receive the
3289 * released event, we will send a cancel event to it. So when the focused display is changed, we
3290 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3291 * display. The display-specified events won't be affected.
3292 */
3293void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3294#if DEBUG_FOCUS
3295 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3296#endif
3297 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003298 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003299
3300 if (mFocusedDisplayId != displayId) {
3301 sp<InputWindowHandle> oldFocusedWindowHandle =
3302 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3303 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003304 sp<InputChannel> inputChannel =
3305 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003306 if (inputChannel != nullptr) {
3307 CancelationOptions options(
3308 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3309 "The display which contains this window no longer has focus.");
3310 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3311 }
3312 }
3313 mFocusedDisplayId = displayId;
3314
3315 // Sanity check
3316 sp<InputWindowHandle> newFocusedWindowHandle =
3317 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003318 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003319
Tiger Huang721e26f2018-07-24 22:26:19 +08003320 if (newFocusedWindowHandle == nullptr) {
3321 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3322 if (!mFocusedWindowHandlesByDisplay.empty()) {
3323 ALOGE("But another display has a focused window:");
3324 for (auto& it : mFocusedWindowHandlesByDisplay) {
3325 const int32_t displayId = it.first;
3326 const sp<InputWindowHandle>& windowHandle = it.second;
3327 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3328 displayId, windowHandle->getName().c_str());
3329 }
3330 }
3331 }
3332 }
3333
3334#if DEBUG_FOCUS
3335 logDispatchStateLocked();
3336#endif
3337 } // release lock
3338
3339 // Wake up poll loop since it may need to make new input dispatching choices.
3340 mLooper->wake();
3341}
3342
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3344#if DEBUG_FOCUS
3345 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3346#endif
3347
3348 bool changed;
3349 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003350 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351
3352 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3353 if (mDispatchFrozen && !frozen) {
3354 resetANRTimeoutsLocked();
3355 }
3356
3357 if (mDispatchEnabled && !enabled) {
3358 resetAndDropEverythingLocked("dispatcher is being disabled");
3359 }
3360
3361 mDispatchEnabled = enabled;
3362 mDispatchFrozen = frozen;
3363 changed = true;
3364 } else {
3365 changed = false;
3366 }
3367
3368#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003369 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370#endif
3371 } // release lock
3372
3373 if (changed) {
3374 // Wake up poll loop since it may need to make new input dispatching choices.
3375 mLooper->wake();
3376 }
3377}
3378
3379void InputDispatcher::setInputFilterEnabled(bool enabled) {
3380#if DEBUG_FOCUS
3381 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3382#endif
3383
3384 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003385 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386
3387 if (mInputFilterEnabled == enabled) {
3388 return;
3389 }
3390
3391 mInputFilterEnabled = enabled;
3392 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3393 } // release lock
3394
3395 // Wake up poll loop since there might be work to do to drop everything.
3396 mLooper->wake();
3397}
3398
chaviwfbe5d9c2018-12-26 12:23:37 -08003399bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3400 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003402 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003403#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003404 return true;
3405 }
3406
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003408 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409
chaviwfbe5d9c2018-12-26 12:23:37 -08003410 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3411 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003412 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003413 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414 return false;
3415 }
chaviw4f2dd402018-12-26 15:30:27 -08003416#if DEBUG_FOCUS
3417 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3418 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3419#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3421#if DEBUG_FOCUS
3422 ALOGD("Cannot transfer focus because windows are on different displays.");
3423#endif
3424 return false;
3425 }
3426
3427 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003428 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3429 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3430 for (size_t i = 0; i < state.windows.size(); i++) {
3431 const TouchedWindow& touchedWindow = state.windows[i];
3432 if (touchedWindow.windowHandle == fromWindowHandle) {
3433 int32_t oldTargetFlags = touchedWindow.targetFlags;
3434 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003436 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437
Jeff Brownf086ddb2014-02-11 14:28:48 -08003438 int32_t newTargetFlags = oldTargetFlags
3439 & (InputTarget::FLAG_FOREGROUND
3440 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3441 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442
Jeff Brownf086ddb2014-02-11 14:28:48 -08003443 found = true;
3444 goto Found;
3445 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446 }
3447 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003448Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449
3450 if (! found) {
3451#if DEBUG_FOCUS
3452 ALOGD("Focus transfer failed because from window did not have focus.");
3453#endif
3454 return false;
3455 }
3456
chaviwfbe5d9c2018-12-26 12:23:37 -08003457
3458 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3459 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003460 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3461 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3462 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3463 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3464 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3465
3466 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3467 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3468 "transferring touch focus from this window to another window");
3469 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3470 }
3471
3472#if DEBUG_FOCUS
3473 logDispatchStateLocked();
3474#endif
3475 } // release lock
3476
3477 // Wake up poll loop since it may need to make new input dispatching choices.
3478 mLooper->wake();
3479 return true;
3480}
3481
3482void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3483#if DEBUG_FOCUS
3484 ALOGD("Resetting and dropping all events (%s).", reason);
3485#endif
3486
3487 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3488 synthesizeCancelationEventsForAllConnectionsLocked(options);
3489
3490 resetKeyRepeatLocked();
3491 releasePendingEventLocked();
3492 drainInboundQueueLocked();
3493 resetANRTimeoutsLocked();
3494
Jeff Brownf086ddb2014-02-11 14:28:48 -08003495 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003497 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498}
3499
3500void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003501 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003502 dumpDispatchStateLocked(dump);
3503
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003504 std::istringstream stream(dump);
3505 std::string line;
3506
3507 while (std::getline(stream, line, '\n')) {
3508 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 }
3510}
3511
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003512void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3513 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3514 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003515 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516
Tiger Huang721e26f2018-07-24 22:26:19 +08003517 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3518 dump += StringPrintf(INDENT "FocusedApplications:\n");
3519 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3520 const int32_t displayId = it.first;
3521 const sp<InputApplicationHandle>& applicationHandle = it.second;
3522 dump += StringPrintf(
3523 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3524 displayId,
3525 applicationHandle->getName().c_str(),
3526 applicationHandle->getDispatchingTimeout(
3527 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3528 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003530 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003532
3533 if (!mFocusedWindowHandlesByDisplay.empty()) {
3534 dump += StringPrintf(INDENT "FocusedWindows:\n");
3535 for (auto& it : mFocusedWindowHandlesByDisplay) {
3536 const int32_t displayId = it.first;
3537 const sp<InputWindowHandle>& windowHandle = it.second;
3538 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3539 displayId, windowHandle->getName().c_str());
3540 }
3541 } else {
3542 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3543 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544
Jeff Brownf086ddb2014-02-11 14:28:48 -08003545 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003546 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003547 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3548 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003549 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003550 state.displayId, toString(state.down), toString(state.split),
3551 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003552 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003553 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003554 for (size_t i = 0; i < state.windows.size(); i++) {
3555 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003556 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3557 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003558 touchedWindow.pointerIds.value,
3559 touchedWindow.targetFlags);
3560 }
3561 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003562 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003563 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003564 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003565 dump += INDENT3 "Portal windows:\n";
3566 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003567 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003568 dump += StringPrintf(INDENT4 "%zu: name='%s'\n",
3569 i, portalWindowHandle->getName().c_str());
3570 }
3571 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 }
3573 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003574 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003575 }
3576
Arthur Hungb92218b2018-08-14 12:00:21 +08003577 if (!mWindowHandlesByDisplay.empty()) {
3578 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003579 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003580 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003581 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003582 dump += INDENT2 "Windows:\n";
3583 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003584 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003585 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586
Arthur Hungb92218b2018-08-14 12:00:21 +08003587 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003588 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, "
Arthur Hungb92218b2018-08-14 12:00:21 +08003589 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003590 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003591 "touchableRegion=",
3592 i, windowInfo->name.c_str(), windowInfo->displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003593 windowInfo->portalToDisplayId,
Arthur Hungb92218b2018-08-14 12:00:21 +08003594 toString(windowInfo->paused),
3595 toString(windowInfo->hasFocus),
3596 toString(windowInfo->hasWallpaper),
3597 toString(windowInfo->visible),
3598 toString(windowInfo->canReceiveKeys),
3599 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3600 windowInfo->layer,
3601 windowInfo->frameLeft, windowInfo->frameTop,
3602 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003603 windowInfo->globalScaleFactor,
3604 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003605 dumpRegion(dump, windowInfo->touchableRegion);
3606 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3607 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3608 windowInfo->ownerPid, windowInfo->ownerUid,
3609 windowInfo->dispatchingTimeout / 1000000.0);
3610 }
3611 } else {
3612 dump += INDENT2 "Windows: <none>\n";
3613 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003614 }
3615 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003616 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 }
3618
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003619 if (!mMonitoringChannelsByDisplay.empty()) {
3620 for (auto& it : mMonitoringChannelsByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003621 const std::vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003622 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003623 const size_t numChannels = monitoringChannels.size();
3624 for (size_t i = 0; i < numChannels; i++) {
3625 const sp<InputChannel>& channel = monitoringChannels[i];
3626 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3627 }
3628 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003630 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 }
3632
3633 nsecs_t currentTime = now();
3634
3635 // Dump recently dispatched or dropped events from oldest to newest.
3636 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003637 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003638 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003639 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003641 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 (currentTime - entry->eventTime) * 0.000001f);
3643 }
3644 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003645 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 }
3647
3648 // Dump event currently being dispatched.
3649 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003650 dump += INDENT "PendingEvent:\n";
3651 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003653 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3655 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003656 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 }
3658
3659 // Dump inbound events from oldest to newest.
3660 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003661 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003663 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003665 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003666 (currentTime - entry->eventTime) * 0.000001f);
3667 }
3668 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003669 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 }
3671
Michael Wright78f24442014-08-06 15:55:28 -07003672 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003673 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003674 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3675 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3676 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003677 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003678 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3679 }
3680 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003681 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003682 }
3683
Michael Wrightd02c5b62014-02-10 15:10:22 -08003684 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003685 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003686 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3687 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003688 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003689 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003690 i, connection->getInputChannelName().c_str(),
3691 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003692 connection->getStatusLabel(), toString(connection->monitor),
3693 toString(connection->inputPublisherBlocked));
3694
3695 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003696 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003697 connection->outboundQueue.count());
3698 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3699 entry = entry->next) {
3700 dump.append(INDENT4);
3701 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003702 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 entry->targetFlags, entry->resolvedAction,
3704 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3705 }
3706 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003707 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 }
3709
3710 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003711 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 connection->waitQueue.count());
3713 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3714 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003715 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003717 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 "age=%0.1fms, wait=%0.1fms\n",
3719 entry->targetFlags, entry->resolvedAction,
3720 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3721 (currentTime - entry->deliveryTime) * 0.000001f);
3722 }
3723 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003724 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003725 }
3726 }
3727 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003728 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 }
3730
3731 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003732 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 (mAppSwitchDueTime - now()) / 1000000.0);
3734 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003735 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736 }
3737
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003738 dump += INDENT "Configuration:\n";
3739 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003741 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003742 mConfig.keyRepeatTimeout * 0.000001f);
3743}
3744
Robert Carr803535b2018-08-02 16:38:15 -07003745status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003747 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3748 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003749#endif
3750
3751 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003752 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753
Robert Carr4e670e52018-08-15 13:26:12 -07003754 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3755 // treat inputChannel as monitor channel for displayId.
3756 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3757 if (monitor) {
3758 inputChannel->setToken(new BBinder());
3759 }
3760
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761 if (getConnectionIndexLocked(inputChannel) >= 0) {
3762 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003763 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 return BAD_VALUE;
3765 }
3766
Robert Carr803535b2018-08-02 16:38:15 -07003767 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768
3769 int fd = inputChannel->getFd();
3770 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003771 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003772
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003773 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003774 if (monitor) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003775 std::vector<sp<InputChannel>>& monitoringChannels =
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003776 mMonitoringChannelsByDisplay[displayId];
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003777 monitoringChannels.push_back(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003778 }
3779
3780 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3781 } // release lock
3782
3783 // Wake the looper because some connections have changed.
3784 mLooper->wake();
3785 return OK;
3786}
3787
3788status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3789#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003790 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003791#endif
3792
3793 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003794 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003795
3796 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3797 if (status) {
3798 return status;
3799 }
3800 } // release lock
3801
3802 // Wake the poll loop because removing the connection may have changed the current
3803 // synchronization state.
3804 mLooper->wake();
3805 return OK;
3806}
3807
3808status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3809 bool notify) {
3810 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3811 if (connectionIndex < 0) {
3812 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003813 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003814 return BAD_VALUE;
3815 }
3816
3817 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3818 mConnectionsByFd.removeItemsAt(connectionIndex);
3819
Robert Carr5c8a0262018-10-03 16:30:44 -07003820 mInputChannelsByToken.erase(inputChannel->getToken());
3821
Michael Wrightd02c5b62014-02-10 15:10:22 -08003822 if (connection->monitor) {
3823 removeMonitorChannelLocked(inputChannel);
3824 }
3825
3826 mLooper->removeFd(inputChannel->getFd());
3827
3828 nsecs_t currentTime = now();
3829 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3830
3831 connection->status = Connection::STATUS_ZOMBIE;
3832 return OK;
3833}
3834
3835void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003836 for (auto it = mMonitoringChannelsByDisplay.begin();
3837 it != mMonitoringChannelsByDisplay.end(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003838 std::vector<sp<InputChannel>>& monitoringChannels = it->second;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003839 const size_t numChannels = monitoringChannels.size();
3840 for (size_t i = 0; i < numChannels; i++) {
3841 if (monitoringChannels[i] == inputChannel) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003842 monitoringChannels.erase(monitoringChannels.begin() + i);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003843 break;
3844 }
3845 }
3846 if (monitoringChannels.empty()) {
3847 it = mMonitoringChannelsByDisplay.erase(it);
3848 } else {
3849 ++it;
3850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003851 }
3852}
3853
3854ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003855 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003856 return -1;
3857 }
3858
Robert Carr4e670e52018-08-15 13:26:12 -07003859 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3860 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3861 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3862 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003863 }
3864 }
Robert Carr4e670e52018-08-15 13:26:12 -07003865
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866 return -1;
3867}
3868
3869void InputDispatcher::onDispatchCycleFinishedLocked(
3870 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3871 CommandEntry* commandEntry = postCommandLocked(
3872 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3873 commandEntry->connection = connection;
3874 commandEntry->eventTime = currentTime;
3875 commandEntry->seq = seq;
3876 commandEntry->handled = handled;
3877}
3878
3879void InputDispatcher::onDispatchCycleBrokenLocked(
3880 nsecs_t currentTime, const sp<Connection>& connection) {
3881 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003882 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003883
3884 CommandEntry* commandEntry = postCommandLocked(
3885 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3886 commandEntry->connection = connection;
3887}
3888
chaviw0c06c6e2019-01-09 13:27:07 -08003889void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
3890 const sp<InputWindowHandle>& newFocus) {
3891 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
3892 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08003893 CommandEntry* commandEntry = postCommandLocked(
3894 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08003895 commandEntry->oldToken = oldToken;
3896 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003897}
3898
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899void InputDispatcher::onANRLocked(
3900 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3901 const sp<InputWindowHandle>& windowHandle,
3902 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3903 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3904 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3905 ALOGI("Application is not responding: %s. "
3906 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003907 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 dispatchLatency, waitDuration, reason);
3909
3910 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003911 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912 struct tm tm;
3913 localtime_r(&t, &tm);
3914 char timestr[64];
3915 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3916 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003917 mLastANRState += INDENT "ANR:\n";
3918 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3919 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003920 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003921 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3922 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3923 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924 dumpDispatchStateLocked(mLastANRState);
3925
3926 CommandEntry* commandEntry = postCommandLocked(
3927 & InputDispatcher::doNotifyANRLockedInterruptible);
3928 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003929 commandEntry->inputChannel = windowHandle != nullptr ?
3930 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003931 commandEntry->reason = reason;
3932}
3933
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003934void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible (
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 CommandEntry* commandEntry) {
3936 mLock.unlock();
3937
3938 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3939
3940 mLock.lock();
3941}
3942
3943void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3944 CommandEntry* commandEntry) {
3945 sp<Connection> connection = commandEntry->connection;
3946
3947 if (connection->status != Connection::STATUS_ZOMBIE) {
3948 mLock.unlock();
3949
Robert Carr803535b2018-08-02 16:38:15 -07003950 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951
3952 mLock.lock();
3953 }
3954}
3955
Robert Carrf759f162018-11-13 12:57:11 -08003956void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3957 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08003958 sp<IBinder> oldToken = commandEntry->oldToken;
3959 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003960 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08003961 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08003962 mLock.lock();
3963}
3964
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965void InputDispatcher::doNotifyANRLockedInterruptible(
3966 CommandEntry* commandEntry) {
3967 mLock.unlock();
3968
3969 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003970 commandEntry->inputApplicationHandle,
3971 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 commandEntry->reason);
3973
3974 mLock.lock();
3975
3976 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003977 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978}
3979
3980void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3981 CommandEntry* commandEntry) {
3982 KeyEntry* entry = commandEntry->keyEntry;
3983
3984 KeyEvent event;
3985 initializeKeyEvent(&event, entry);
3986
3987 mLock.unlock();
3988
Michael Wright2b3c3302018-03-02 17:19:13 +00003989 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003990 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3991 commandEntry->inputChannel->getToken() : nullptr;
3992 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003994 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3995 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3996 std::to_string(t.duration().count()).c_str());
3997 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998
3999 mLock.lock();
4000
4001 if (delay < 0) {
4002 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
4003 } else if (!delay) {
4004 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
4005 } else {
4006 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
4007 entry->interceptKeyWakeupTime = now() + delay;
4008 }
4009 entry->release();
4010}
4011
4012void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
4013 CommandEntry* commandEntry) {
4014 sp<Connection> connection = commandEntry->connection;
4015 nsecs_t finishTime = commandEntry->eventTime;
4016 uint32_t seq = commandEntry->seq;
4017 bool handled = commandEntry->handled;
4018
4019 // Handle post-event policy actions.
4020 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4021 if (dispatchEntry) {
4022 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4023 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004024 std::string msg =
4025 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004026 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004027 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004028 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004029 }
4030
4031 bool restartEvent;
4032 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4033 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4034 restartEvent = afterKeyEventLockedInterruptible(connection,
4035 dispatchEntry, keyEntry, handled);
4036 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4037 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4038 restartEvent = afterMotionEventLockedInterruptible(connection,
4039 dispatchEntry, motionEntry, handled);
4040 } else {
4041 restartEvent = false;
4042 }
4043
4044 // Dequeue the event and start the next cycle.
4045 // Note that because the lock might have been released, it is possible that the
4046 // contents of the wait queue to have been drained, so we need to double-check
4047 // a few things.
4048 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4049 connection->waitQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004050 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4052 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004053 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054 } else {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08004055 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 }
4057 }
4058
4059 // Start the next dispatch cycle for this connection.
4060 startDispatchCycleLocked(now(), connection);
4061 }
4062}
4063
4064bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4065 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004066 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004067 if (!handled) {
4068 // Report the key as unhandled, since the fallback was not handled.
4069 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4070 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004071 return false;
4072 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004073
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004074 // Get the fallback key state.
4075 // Clear it out after dispatching the UP.
4076 int32_t originalKeyCode = keyEntry->keyCode;
4077 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4078 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4079 connection->inputState.removeFallbackKey(originalKeyCode);
4080 }
4081
4082 if (handled || !dispatchEntry->hasForegroundTarget()) {
4083 // If the application handles the original key for which we previously
4084 // generated a fallback or if the window is not a foreground window,
4085 // then cancel the associated fallback key, if any.
4086 if (fallbackKeyCode != -1) {
4087 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004088#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004089 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004090 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4091 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4092 keyEntry->policyFlags);
4093#endif
4094 KeyEvent event;
4095 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004096 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097
4098 mLock.unlock();
4099
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004100 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4101 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004102
4103 mLock.lock();
4104
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004105 // Cancel the fallback key.
4106 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004108 "application handled the original non-fallback key "
4109 "or is no longer a foreground target, "
4110 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 options.keyCode = fallbackKeyCode;
4112 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004114 connection->inputState.removeFallbackKey(originalKeyCode);
4115 }
4116 } else {
4117 // If the application did not handle a non-fallback key, first check
4118 // that we are in a good state to perform unhandled key event processing
4119 // Then ask the policy what to do with it.
4120 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4121 && keyEntry->repeatCount == 0;
4122 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004123#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004124 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4125 "since this is not an initial down. "
4126 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4127 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4128 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004130 return false;
4131 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004133 // Dispatch the unhandled key to the policy.
4134#if DEBUG_OUTBOUND_EVENT_DETAILS
4135 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4136 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4137 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4138 keyEntry->policyFlags);
4139#endif
4140 KeyEvent event;
4141 initializeKeyEvent(&event, keyEntry);
4142
4143 mLock.unlock();
4144
4145 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4146 &event, keyEntry->policyFlags, &event);
4147
4148 mLock.lock();
4149
4150 if (connection->status != Connection::STATUS_NORMAL) {
4151 connection->inputState.removeFallbackKey(originalKeyCode);
4152 return false;
4153 }
4154
4155 // Latch the fallback keycode for this key on an initial down.
4156 // The fallback keycode cannot change at any other point in the lifecycle.
4157 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004159 fallbackKeyCode = event.getKeyCode();
4160 } else {
4161 fallbackKeyCode = AKEYCODE_UNKNOWN;
4162 }
4163 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4164 }
4165
4166 ALOG_ASSERT(fallbackKeyCode != -1);
4167
4168 // Cancel the fallback key if the policy decides not to send it anymore.
4169 // We will continue to dispatch the key to the policy but we will no
4170 // longer dispatch a fallback key to the application.
4171 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4172 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4173#if DEBUG_OUTBOUND_EVENT_DETAILS
4174 if (fallback) {
4175 ALOGD("Unhandled key event: Policy requested to send key %d"
4176 "as a fallback for %d, but on the DOWN it had requested "
4177 "to send %d instead. Fallback canceled.",
4178 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4179 } else {
4180 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4181 "but on the DOWN it had requested to send %d. "
4182 "Fallback canceled.",
4183 originalKeyCode, fallbackKeyCode);
4184 }
4185#endif
4186
4187 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4188 "canceling fallback, policy no longer desires it");
4189 options.keyCode = fallbackKeyCode;
4190 synthesizeCancelationEventsForConnectionLocked(connection, options);
4191
4192 fallback = false;
4193 fallbackKeyCode = AKEYCODE_UNKNOWN;
4194 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4195 connection->inputState.setFallbackKey(originalKeyCode,
4196 fallbackKeyCode);
4197 }
4198 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199
4200#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004201 {
4202 std::string msg;
4203 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4204 connection->inputState.getFallbackKeys();
4205 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4206 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4207 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004209 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4210 fallbackKeys.size(), msg.c_str());
4211 }
4212#endif
4213
4214 if (fallback) {
4215 // Restart the dispatch cycle using the fallback key.
4216 keyEntry->eventTime = event.getEventTime();
4217 keyEntry->deviceId = event.getDeviceId();
4218 keyEntry->source = event.getSource();
4219 keyEntry->displayId = event.getDisplayId();
4220 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4221 keyEntry->keyCode = fallbackKeyCode;
4222 keyEntry->scanCode = event.getScanCode();
4223 keyEntry->metaState = event.getMetaState();
4224 keyEntry->repeatCount = event.getRepeatCount();
4225 keyEntry->downTime = event.getDownTime();
4226 keyEntry->syntheticRepeat = false;
4227
4228#if DEBUG_OUTBOUND_EVENT_DETAILS
4229 ALOGD("Unhandled key event: Dispatching fallback key. "
4230 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4231 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4232#endif
4233 return true; // restart the event
4234 } else {
4235#if DEBUG_OUTBOUND_EVENT_DETAILS
4236 ALOGD("Unhandled key event: No fallback key.");
4237#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004238
4239 // Report the key as unhandled, since there is no fallback key.
4240 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 }
4242 }
4243 return false;
4244}
4245
4246bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4247 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4248 return false;
4249}
4250
4251void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4252 mLock.unlock();
4253
4254 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4255
4256 mLock.lock();
4257}
4258
4259void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004260 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4262 entry->downTime, entry->eventTime);
4263}
4264
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004265void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4267 // TODO Write some statistics about how long we spend waiting.
4268}
4269
4270void InputDispatcher::traceInboundQueueLengthLocked() {
4271 if (ATRACE_ENABLED()) {
4272 ATRACE_INT("iq", mInboundQueue.count());
4273 }
4274}
4275
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004276void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 if (ATRACE_ENABLED()) {
4278 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004279 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004280 ATRACE_INT(counterName, connection->outboundQueue.count());
4281 }
4282}
4283
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004284void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 if (ATRACE_ENABLED()) {
4286 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004287 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 ATRACE_INT(counterName, connection->waitQueue.count());
4289 }
4290}
4291
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004292void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004293 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004295 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 dumpDispatchStateLocked(dump);
4297
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004298 if (!mLastANRState.empty()) {
4299 dump += "\nInput Dispatcher State at time of last ANR:\n";
4300 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 }
4302}
4303
4304void InputDispatcher::monitor() {
4305 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004306 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004308 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309}
4310
4311
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312// --- InputDispatcher::InjectionState ---
4313
4314InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4315 refCount(1),
4316 injectorPid(injectorPid), injectorUid(injectorUid),
4317 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4318 pendingForegroundDispatches(0) {
4319}
4320
4321InputDispatcher::InjectionState::~InjectionState() {
4322}
4323
4324void InputDispatcher::InjectionState::release() {
4325 refCount -= 1;
4326 if (refCount == 0) {
4327 delete this;
4328 } else {
4329 ALOG_ASSERT(refCount > 0);
4330 }
4331}
4332
4333
4334// --- InputDispatcher::EventEntry ---
4335
Prabir Pradhan42611e02018-11-27 14:04:02 -08004336InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4337 nsecs_t eventTime, uint32_t policyFlags) :
4338 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4339 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340}
4341
4342InputDispatcher::EventEntry::~EventEntry() {
4343 releaseInjectionState();
4344}
4345
4346void InputDispatcher::EventEntry::release() {
4347 refCount -= 1;
4348 if (refCount == 0) {
4349 delete this;
4350 } else {
4351 ALOG_ASSERT(refCount > 0);
4352 }
4353}
4354
4355void InputDispatcher::EventEntry::releaseInjectionState() {
4356 if (injectionState) {
4357 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004358 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 }
4360}
4361
4362
4363// --- InputDispatcher::ConfigurationChangedEntry ---
4364
Prabir Pradhan42611e02018-11-27 14:04:02 -08004365InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4366 uint32_t sequenceNum, nsecs_t eventTime) :
4367 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368}
4369
4370InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4371}
4372
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004373void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4374 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375}
4376
4377
4378// --- InputDispatcher::DeviceResetEntry ---
4379
Prabir Pradhan42611e02018-11-27 14:04:02 -08004380InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4381 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4382 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 deviceId(deviceId) {
4384}
4385
4386InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4387}
4388
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004389void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4390 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 deviceId, policyFlags);
4392}
4393
4394
4395// --- InputDispatcher::KeyEntry ---
4396
Prabir Pradhan42611e02018-11-27 14:04:02 -08004397InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004398 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004399 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4400 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004401 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004402 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004403 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4404 repeatCount(repeatCount), downTime(downTime),
4405 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4406 interceptKeyWakeupTime(0) {
4407}
4408
4409InputDispatcher::KeyEntry::~KeyEntry() {
4410}
4411
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004412void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004413 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004414 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4415 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004416 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004417 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004418}
4419
4420void InputDispatcher::KeyEntry::recycle() {
4421 releaseInjectionState();
4422
4423 dispatchInProgress = false;
4424 syntheticRepeat = false;
4425 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4426 interceptKeyWakeupTime = 0;
4427}
4428
4429
4430// --- InputDispatcher::MotionEntry ---
4431
Prabir Pradhan42611e02018-11-27 14:04:02 -08004432InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004433 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4434 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004435 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4436 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004437 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004438 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4439 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004440 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004441 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004442 deviceId(deviceId), source(source), displayId(displayId), action(action),
4443 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004444 classification(classification), edgeFlags(edgeFlags),
4445 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004446 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004447 for (uint32_t i = 0; i < pointerCount; i++) {
4448 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4449 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004450 if (xOffset || yOffset) {
4451 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4452 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004453 }
4454}
4455
4456InputDispatcher::MotionEntry::~MotionEntry() {
4457}
4458
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004459void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004460 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004461 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004462 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004463 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004464 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4465 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004466
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 for (uint32_t i = 0; i < pointerCount; i++) {
4468 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004469 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004470 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004471 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472 pointerCoords[i].getX(), pointerCoords[i].getY());
4473 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004474 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475}
4476
4477
4478// --- InputDispatcher::DispatchEntry ---
4479
4480volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4481
4482InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004483 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4484 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004485 seq(nextSeq()),
4486 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004487 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4488 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004489 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4490 eventEntry->refCount += 1;
4491}
4492
4493InputDispatcher::DispatchEntry::~DispatchEntry() {
4494 eventEntry->release();
4495}
4496
4497uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4498 // Sequence number 0 is reserved and will never be returned.
4499 uint32_t seq;
4500 do {
4501 seq = android_atomic_inc(&sNextSeqAtomic);
4502 } while (!seq);
4503 return seq;
4504}
4505
4506
4507// --- InputDispatcher::InputState ---
4508
4509InputDispatcher::InputState::InputState() {
4510}
4511
4512InputDispatcher::InputState::~InputState() {
4513}
4514
4515bool InputDispatcher::InputState::isNeutral() const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004516 return mKeyMementos.empty() && mMotionMementos.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004517}
4518
4519bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4520 int32_t displayId) const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004521 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004522 if (memento.deviceId == deviceId
4523 && memento.source == source
4524 && memento.displayId == displayId
4525 && memento.hovering) {
4526 return true;
4527 }
4528 }
4529 return false;
4530}
4531
4532bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4533 int32_t action, int32_t flags) {
4534 switch (action) {
4535 case AKEY_EVENT_ACTION_UP: {
4536 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4537 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4538 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4539 mFallbackKeys.removeItemsAt(i);
4540 } else {
4541 i += 1;
4542 }
4543 }
4544 }
4545 ssize_t index = findKeyMemento(entry);
4546 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004547 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548 return true;
4549 }
4550 /* FIXME: We can't just drop the key up event because that prevents creating
4551 * popup windows that are automatically shown when a key is held and then
4552 * dismissed when the key is released. The problem is that the popup will
4553 * not have received the original key down, so the key up will be considered
4554 * to be inconsistent with its observed state. We could perhaps handle this
4555 * by synthesizing a key down but that will cause other problems.
4556 *
4557 * So for now, allow inconsistent key up events to be dispatched.
4558 *
4559#if DEBUG_OUTBOUND_EVENT_DETAILS
4560 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4561 "keyCode=%d, scanCode=%d",
4562 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4563#endif
4564 return false;
4565 */
4566 return true;
4567 }
4568
4569 case AKEY_EVENT_ACTION_DOWN: {
4570 ssize_t index = findKeyMemento(entry);
4571 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004572 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004573 }
4574 addKeyMemento(entry, flags);
4575 return true;
4576 }
4577
4578 default:
4579 return true;
4580 }
4581}
4582
4583bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4584 int32_t action, int32_t flags) {
4585 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4586 switch (actionMasked) {
4587 case AMOTION_EVENT_ACTION_UP:
4588 case AMOTION_EVENT_ACTION_CANCEL: {
4589 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4590 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004591 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592 return true;
4593 }
4594#if DEBUG_OUTBOUND_EVENT_DETAILS
4595 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004596 "displayId=%" PRId32 ", actionMasked=%d",
4597 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004598#endif
4599 return false;
4600 }
4601
4602 case AMOTION_EVENT_ACTION_DOWN: {
4603 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4604 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004605 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004606 }
4607 addMotionMemento(entry, flags, false /*hovering*/);
4608 return true;
4609 }
4610
4611 case AMOTION_EVENT_ACTION_POINTER_UP:
4612 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4613 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004614 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4615 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4616 // generate cancellation events for these since they're based in relative rather than
4617 // absolute units.
4618 return true;
4619 }
4620
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004622
4623 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4624 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4625 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4626 // other value and we need to track the motion so we can send cancellation events for
4627 // anything generating fallback events (e.g. DPad keys for joystick movements).
4628 if (index >= 0) {
4629 if (entry->pointerCoords[0].isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004630 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wright38dcdff2014-03-19 12:06:10 -07004631 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004632 MotionMemento& memento = mMotionMementos[index];
Michael Wright38dcdff2014-03-19 12:06:10 -07004633 memento.setPointers(entry);
4634 }
4635 } else if (!entry->pointerCoords[0].isEmpty()) {
4636 addMotionMemento(entry, flags, false /*hovering*/);
4637 }
4638
4639 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4640 return true;
4641 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004642 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004643 MotionMemento& memento = mMotionMementos[index];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644 memento.setPointers(entry);
4645 return true;
4646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647#if DEBUG_OUTBOUND_EVENT_DETAILS
4648 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004649 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4650 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651#endif
4652 return false;
4653 }
4654
4655 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4656 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4657 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004658 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659 return true;
4660 }
4661#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004662 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4663 "displayId=%" PRId32,
4664 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665#endif
4666 return false;
4667 }
4668
4669 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4670 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4671 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4672 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004673 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004674 }
4675 addMotionMemento(entry, flags, true /*hovering*/);
4676 return true;
4677 }
4678
4679 default:
4680 return true;
4681 }
4682}
4683
4684ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4685 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004686 const KeyMemento& memento = mKeyMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687 if (memento.deviceId == entry->deviceId
4688 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004689 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690 && memento.keyCode == entry->keyCode
4691 && memento.scanCode == entry->scanCode) {
4692 return i;
4693 }
4694 }
4695 return -1;
4696}
4697
4698ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4699 bool hovering) const {
4700 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004701 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 if (memento.deviceId == entry->deviceId
4703 && memento.source == entry->source
4704 && memento.displayId == entry->displayId
4705 && memento.hovering == hovering) {
4706 return i;
4707 }
4708 }
4709 return -1;
4710}
4711
4712void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004713 KeyMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714 memento.deviceId = entry->deviceId;
4715 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004716 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 memento.keyCode = entry->keyCode;
4718 memento.scanCode = entry->scanCode;
4719 memento.metaState = entry->metaState;
4720 memento.flags = flags;
4721 memento.downTime = entry->downTime;
4722 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004723 mKeyMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724}
4725
4726void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4727 int32_t flags, bool hovering) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004728 MotionMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729 memento.deviceId = entry->deviceId;
4730 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004731 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004732 memento.flags = flags;
4733 memento.xPrecision = entry->xPrecision;
4734 memento.yPrecision = entry->yPrecision;
4735 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 memento.setPointers(entry);
4737 memento.hovering = hovering;
4738 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004739 mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740}
4741
4742void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4743 pointerCount = entry->pointerCount;
4744 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4745 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4746 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4747 }
4748}
4749
4750void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004751 std::vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4752 for (KeyMemento& memento : mKeyMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 if (shouldCancelKey(memento, options)) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004754 outEvents.push_back(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004755 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4757 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4758 }
4759 }
4760
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004761 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004763 const int32_t action = memento.hovering ?
4764 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004765 outEvents.push_back(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004766 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004767 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4768 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004770 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004771 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 }
4773 }
4774}
4775
4776void InputDispatcher::InputState::clear() {
4777 mKeyMementos.clear();
4778 mMotionMementos.clear();
4779 mFallbackKeys.clear();
4780}
4781
4782void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4783 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004784 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4786 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004787 const MotionMemento& otherMemento = other.mMotionMementos[j];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 if (memento.deviceId == otherMemento.deviceId
4789 && memento.source == otherMemento.source
4790 && memento.displayId == otherMemento.displayId) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004791 other.mMotionMementos.erase(other.mMotionMementos.begin() + j);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004792 } else {
4793 j += 1;
4794 }
4795 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004796 other.mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 }
4798 }
4799}
4800
4801int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4802 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4803 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4804}
4805
4806void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4807 int32_t fallbackKeyCode) {
4808 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4809 if (index >= 0) {
4810 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4811 } else {
4812 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4813 }
4814}
4815
4816void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4817 mFallbackKeys.removeItem(originalKeyCode);
4818}
4819
4820bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4821 const CancelationOptions& options) {
4822 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4823 return false;
4824 }
4825
4826 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4827 return false;
4828 }
4829
4830 switch (options.mode) {
4831 case CancelationOptions::CANCEL_ALL_EVENTS:
4832 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4833 return true;
4834 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4835 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004836 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4837 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004838 default:
4839 return false;
4840 }
4841}
4842
4843bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4844 const CancelationOptions& options) {
4845 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4846 return false;
4847 }
4848
4849 switch (options.mode) {
4850 case CancelationOptions::CANCEL_ALL_EVENTS:
4851 return true;
4852 case CancelationOptions::CANCEL_POINTER_EVENTS:
4853 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4854 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4855 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004856 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4857 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858 default:
4859 return false;
4860 }
4861}
4862
4863
4864// --- InputDispatcher::Connection ---
4865
Robert Carr803535b2018-08-02 16:38:15 -07004866InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4867 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 monitor(monitor),
4869 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4870}
4871
4872InputDispatcher::Connection::~Connection() {
4873}
4874
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004875const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004876 if (inputChannel != nullptr) {
4877 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878 }
4879 if (monitor) {
4880 return "monitor";
4881 }
4882 return "?";
4883}
4884
4885const char* InputDispatcher::Connection::getStatusLabel() const {
4886 switch (status) {
4887 case STATUS_NORMAL:
4888 return "NORMAL";
4889
4890 case STATUS_BROKEN:
4891 return "BROKEN";
4892
4893 case STATUS_ZOMBIE:
4894 return "ZOMBIE";
4895
4896 default:
4897 return "UNKNOWN";
4898 }
4899}
4900
4901InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004902 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903 if (entry->seq == seq) {
4904 return entry;
4905 }
4906 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004907 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908}
4909
4910
4911// --- InputDispatcher::CommandEntry ---
4912
4913InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004914 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915 seq(0), handled(false) {
4916}
4917
4918InputDispatcher::CommandEntry::~CommandEntry() {
4919}
4920
4921
4922// --- InputDispatcher::TouchState ---
4923
4924InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004925 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926}
4927
4928InputDispatcher::TouchState::~TouchState() {
4929}
4930
4931void InputDispatcher::TouchState::reset() {
4932 down = false;
4933 split = false;
4934 deviceId = -1;
4935 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004936 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004937 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004938 portalWindows.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939}
4940
4941void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4942 down = other.down;
4943 split = other.split;
4944 deviceId = other.deviceId;
4945 source = other.source;
4946 displayId = other.displayId;
4947 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004948 portalWindows = other.portalWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949}
4950
4951void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4952 int32_t targetFlags, BitSet32 pointerIds) {
4953 if (targetFlags & InputTarget::FLAG_SPLIT) {
4954 split = true;
4955 }
4956
4957 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004958 TouchedWindow& touchedWindow = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 if (touchedWindow.windowHandle == windowHandle) {
4960 touchedWindow.targetFlags |= targetFlags;
4961 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4962 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4963 }
4964 touchedWindow.pointerIds.value |= pointerIds.value;
4965 return;
4966 }
4967 }
4968
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004969 TouchedWindow touchedWindow;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970 touchedWindow.windowHandle = windowHandle;
4971 touchedWindow.targetFlags = targetFlags;
4972 touchedWindow.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004973 windows.push_back(touchedWindow);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974}
4975
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004976void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
4977 size_t numWindows = portalWindows.size();
4978 for (size_t i = 0; i < numWindows; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004979 if (portalWindows[i] == windowHandle) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004980 return;
4981 }
4982 }
4983 portalWindows.push_back(windowHandle);
4984}
4985
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4987 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004988 if (windows[i].windowHandle == windowHandle) {
4989 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990 return;
4991 }
4992 }
4993}
4994
Robert Carr803535b2018-08-02 16:38:15 -07004995void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4996 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004997 if (windows[i].windowHandle->getToken() == token) {
4998 windows.erase(windows.begin() + i);
Robert Carr803535b2018-08-02 16:38:15 -07004999 return;
5000 }
5001 }
5002}
5003
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
5005 for (size_t i = 0 ; i < windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005006 TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005007 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
5008 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
5009 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
5010 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
5011 i += 1;
5012 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005013 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 }
5015 }
5016}
5017
5018sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
5019 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005020 const TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5022 return window.windowHandle;
5023 }
5024 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005025 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005026}
5027
5028bool InputDispatcher::TouchState::isSlippery() const {
5029 // Must have exactly one foreground window.
5030 bool haveSlipperyForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005031 for (const TouchedWindow& window : windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005032 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5033 if (haveSlipperyForegroundWindow
5034 || !(window.windowHandle->getInfo()->layoutParamsFlags
5035 & InputWindowInfo::FLAG_SLIPPERY)) {
5036 return false;
5037 }
5038 haveSlipperyForegroundWindow = true;
5039 }
5040 }
5041 return haveSlipperyForegroundWindow;
5042}
5043
5044
5045// --- InputDispatcherThread ---
5046
5047InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5048 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5049}
5050
5051InputDispatcherThread::~InputDispatcherThread() {
5052}
5053
5054bool InputDispatcherThread::threadLoop() {
5055 mDispatcher->dispatchOnce();
5056 return true;
5057}
5058
5059} // namespace android