blob: 4dc9111bfeb491bd1670a1f0cea5852368602563 [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
chaviwfd6d3512019-03-25 13:23:49 -07002058 dispatchPointerDownOutsideFocus(motionEntry->source,
chaviw8c9cf542019-03-25 13:02:48 -07002059 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
chaviwfd6d3512019-03-25 13:23:49 -07002076void InputDispatcher::dispatchPointerDownOutsideFocus(uint32_t source, int32_t action,
chaviw8c9cf542019-03-25 13:02:48 -07002077 const sp<IBinder>& newToken) {
2078 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
chaviwfd6d3512019-03-25 13:23:49 -07002079 uint32_t maskedSource = source & AINPUT_SOURCE_CLASS_MASK;
2080 if (maskedSource != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
chaviw8c9cf542019-03-25 13:02:48 -07002081 return;
2082 }
2083
2084 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2085 if (inputWindowHandle == nullptr) {
2086 return;
2087 }
2088
2089 int32_t displayId = inputWindowHandle->getInfo()->displayId;
2090 sp<InputWindowHandle> focusedWindowHandle =
2091 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2092
2093 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2094
2095 if (!hasFocusChanged) {
2096 return;
2097 }
2098
chaviwfd6d3512019-03-25 13:23:49 -07002099 CommandEntry* commandEntry = postCommandLocked(
2100 & InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible);
2101 commandEntry->newToken = newToken;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102}
2103
2104void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2105 const sp<Connection>& connection) {
2106#if DEBUG_DISPATCH_CYCLE
2107 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002108 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109#endif
2110
2111 while (connection->status == Connection::STATUS_NORMAL
2112 && !connection->outboundQueue.isEmpty()) {
2113 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2114 dispatchEntry->deliveryTime = currentTime;
2115
2116 // Publish the event.
2117 status_t status;
2118 EventEntry* eventEntry = dispatchEntry->eventEntry;
2119 switch (eventEntry->type) {
2120 case EventEntry::TYPE_KEY: {
2121 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2122
2123 // Publish the key event.
2124 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002125 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002126 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2127 keyEntry->keyCode, keyEntry->scanCode,
2128 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2129 keyEntry->eventTime);
2130 break;
2131 }
2132
2133 case EventEntry::TYPE_MOTION: {
2134 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2135
2136 PointerCoords scaledCoords[MAX_POINTERS];
2137 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2138
2139 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002140 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002141 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2142 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002143 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2144 float wxs = dispatchEntry->windowXScale;
2145 float wys = dispatchEntry->windowYScale;
2146 xOffset = dispatchEntry->xOffset * wxs;
2147 yOffset = dispatchEntry->yOffset * wys;
2148 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002149 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002151 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002152 }
2153 usingCoords = scaledCoords;
2154 }
2155 } else {
2156 xOffset = 0.0f;
2157 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158
2159 // We don't want the dispatch target to know.
2160 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002161 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 scaledCoords[i].clear();
2163 }
2164 usingCoords = scaledCoords;
2165 }
2166 }
2167
2168 // Publish the motion event.
2169 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002170 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002171 dispatchEntry->resolvedAction, motionEntry->actionButton,
2172 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002173 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification,
Michael Wright7b159c92015-05-14 14:48:03 +01002174 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175 motionEntry->downTime, motionEntry->eventTime,
2176 motionEntry->pointerCount, motionEntry->pointerProperties,
2177 usingCoords);
2178 break;
2179 }
2180
2181 default:
2182 ALOG_ASSERT(false);
2183 return;
2184 }
2185
2186 // Check the result.
2187 if (status) {
2188 if (status == WOULD_BLOCK) {
2189 if (connection->waitQueue.isEmpty()) {
2190 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2191 "This is unexpected because the wait queue is empty, so the pipe "
2192 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002193 "event to it, status=%d", connection->getInputChannelName().c_str(),
2194 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2196 } else {
2197 // Pipe is full and we are waiting for the app to finish process some events
2198 // before sending more events to it.
2199#if DEBUG_DISPATCH_CYCLE
2200 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2201 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002202 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203#endif
2204 connection->inputPublisherBlocked = true;
2205 }
2206 } else {
2207 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002208 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2210 }
2211 return;
2212 }
2213
2214 // Re-enqueue the event on the wait queue.
2215 connection->outboundQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002216 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217 connection->waitQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002218 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219 }
2220}
2221
2222void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2223 const sp<Connection>& connection, uint32_t seq, bool handled) {
2224#if DEBUG_DISPATCH_CYCLE
2225 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002226 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227#endif
2228
2229 connection->inputPublisherBlocked = false;
2230
2231 if (connection->status == Connection::STATUS_BROKEN
2232 || connection->status == Connection::STATUS_ZOMBIE) {
2233 return;
2234 }
2235
2236 // Notify other system components and prepare to start the next dispatch cycle.
2237 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2238}
2239
2240void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2241 const sp<Connection>& connection, bool notify) {
2242#if DEBUG_DISPATCH_CYCLE
2243 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002244 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245#endif
2246
2247 // Clear the dispatch queues.
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002248 drainDispatchQueue(&connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002249 traceOutboundQueueLength(connection);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002250 drainDispatchQueue(&connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002251 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252
2253 // The connection appears to be unrecoverably broken.
2254 // Ignore already broken or zombie connections.
2255 if (connection->status == Connection::STATUS_NORMAL) {
2256 connection->status = Connection::STATUS_BROKEN;
2257
2258 if (notify) {
2259 // Notify other system components.
2260 onDispatchCycleBrokenLocked(currentTime, connection);
2261 }
2262 }
2263}
2264
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002265void InputDispatcher::drainDispatchQueue(Queue<DispatchEntry>* queue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 while (!queue->isEmpty()) {
2267 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002268 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 }
2270}
2271
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002272void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002273 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002274 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 }
2276 delete dispatchEntry;
2277}
2278
2279int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2280 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2281
2282 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002283 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284
2285 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2286 if (connectionIndex < 0) {
2287 ALOGE("Received spurious receive callback for unknown input channel. "
2288 "fd=%d, events=0x%x", fd, events);
2289 return 0; // remove the callback
2290 }
2291
2292 bool notify;
2293 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2294 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2295 if (!(events & ALOOPER_EVENT_INPUT)) {
2296 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002297 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002298 return 1;
2299 }
2300
2301 nsecs_t currentTime = now();
2302 bool gotOne = false;
2303 status_t status;
2304 for (;;) {
2305 uint32_t seq;
2306 bool handled;
2307 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2308 if (status) {
2309 break;
2310 }
2311 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2312 gotOne = true;
2313 }
2314 if (gotOne) {
2315 d->runCommandsLockedInterruptible();
2316 if (status == WOULD_BLOCK) {
2317 return 1;
2318 }
2319 }
2320
2321 notify = status != DEAD_OBJECT || !connection->monitor;
2322 if (notify) {
2323 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002324 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 }
2326 } else {
2327 // Monitor channels are never explicitly unregistered.
2328 // We do it automatically when the remote endpoint is closed so don't warn
2329 // about them.
2330 notify = !connection->monitor;
2331 if (notify) {
2332 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002333 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334 }
2335 }
2336
2337 // Unregister the channel.
2338 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2339 return 0; // remove the callback
2340 } // release lock
2341}
2342
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002343void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked (
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344 const CancelationOptions& options) {
2345 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2346 synthesizeCancelationEventsForConnectionLocked(
2347 mConnectionsByFd.valueAt(i), options);
2348 }
2349}
2350
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002351void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked (
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002352 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002353 for (auto& it : mMonitoringChannelsByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002354 const std::vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002355 const size_t numChannels = monitoringChannels.size();
2356 for (size_t i = 0; i < numChannels; i++) {
2357 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2358 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002359 }
2360}
2361
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2363 const sp<InputChannel>& channel, const CancelationOptions& options) {
2364 ssize_t index = getConnectionIndexLocked(channel);
2365 if (index >= 0) {
2366 synthesizeCancelationEventsForConnectionLocked(
2367 mConnectionsByFd.valueAt(index), options);
2368 }
2369}
2370
2371void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2372 const sp<Connection>& connection, const CancelationOptions& options) {
2373 if (connection->status == Connection::STATUS_BROKEN) {
2374 return;
2375 }
2376
2377 nsecs_t currentTime = now();
2378
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002379 std::vector<EventEntry*> cancelationEvents;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 connection->inputState.synthesizeCancelationEvents(currentTime,
2381 cancelationEvents, options);
2382
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002383 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002384#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002385 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002387 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388 options.reason, options.mode);
2389#endif
2390 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002391 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 switch (cancelationEventEntry->type) {
2393 case EventEntry::TYPE_KEY:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002394 logOutboundKeyDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 static_cast<KeyEntry*>(cancelationEventEntry));
2396 break;
2397 case EventEntry::TYPE_MOTION:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002398 logOutboundMotionDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 static_cast<MotionEntry*>(cancelationEventEntry));
2400 break;
2401 }
2402
2403 InputTarget target;
chaviwfbe5d9c2018-12-26 12:23:37 -08002404 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(
2405 connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002406 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2408 target.xOffset = -windowInfo->frameLeft;
2409 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002410 target.globalScaleFactor = windowInfo->globalScaleFactor;
2411 target.windowXScale = windowInfo->windowXScale;
2412 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 } else {
2414 target.xOffset = 0;
2415 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002416 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
2418 target.inputChannel = connection->inputChannel;
2419 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2420
chaviw8c9cf542019-03-25 13:02:48 -07002421 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2423
2424 cancelationEventEntry->release();
2425 }
2426
2427 startDispatchCycleLocked(currentTime, connection);
2428 }
2429}
2430
2431InputDispatcher::MotionEntry*
2432InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2433 ALOG_ASSERT(pointerIds.value != 0);
2434
2435 uint32_t splitPointerIndexMap[MAX_POINTERS];
2436 PointerProperties splitPointerProperties[MAX_POINTERS];
2437 PointerCoords splitPointerCoords[MAX_POINTERS];
2438
2439 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2440 uint32_t splitPointerCount = 0;
2441
2442 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2443 originalPointerIndex++) {
2444 const PointerProperties& pointerProperties =
2445 originalMotionEntry->pointerProperties[originalPointerIndex];
2446 uint32_t pointerId = uint32_t(pointerProperties.id);
2447 if (pointerIds.hasBit(pointerId)) {
2448 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2449 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2450 splitPointerCoords[splitPointerCount].copyFrom(
2451 originalMotionEntry->pointerCoords[originalPointerIndex]);
2452 splitPointerCount += 1;
2453 }
2454 }
2455
2456 if (splitPointerCount != pointerIds.count()) {
2457 // This is bad. We are missing some of the pointers that we expected to deliver.
2458 // Most likely this indicates that we received an ACTION_MOVE events that has
2459 // different pointer ids than we expected based on the previous ACTION_DOWN
2460 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2461 // in this way.
2462 ALOGW("Dropping split motion event because the pointer count is %d but "
2463 "we expected there to be %d pointers. This probably means we received "
2464 "a broken sequence of pointer ids from the input device.",
2465 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002466 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002467 }
2468
2469 int32_t action = originalMotionEntry->action;
2470 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2471 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2472 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2473 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2474 const PointerProperties& pointerProperties =
2475 originalMotionEntry->pointerProperties[originalPointerIndex];
2476 uint32_t pointerId = uint32_t(pointerProperties.id);
2477 if (pointerIds.hasBit(pointerId)) {
2478 if (pointerIds.count() == 1) {
2479 // The first/last pointer went down/up.
2480 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2481 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2482 } else {
2483 // A secondary pointer went down/up.
2484 uint32_t splitPointerIndex = 0;
2485 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2486 splitPointerIndex += 1;
2487 }
2488 action = maskedAction | (splitPointerIndex
2489 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2490 }
2491 } else {
2492 // An unrelated pointer changed.
2493 action = AMOTION_EVENT_ACTION_MOVE;
2494 }
2495 }
2496
2497 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002498 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 originalMotionEntry->eventTime,
2500 originalMotionEntry->deviceId,
2501 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002502 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 originalMotionEntry->policyFlags,
2504 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002505 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002506 originalMotionEntry->flags,
2507 originalMotionEntry->metaState,
2508 originalMotionEntry->buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002509 originalMotionEntry->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002510 originalMotionEntry->edgeFlags,
2511 originalMotionEntry->xPrecision,
2512 originalMotionEntry->yPrecision,
2513 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002514 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002515
2516 if (originalMotionEntry->injectionState) {
2517 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2518 splitMotionEntry->injectionState->refCount += 1;
2519 }
2520
2521 return splitMotionEntry;
2522}
2523
2524void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2525#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002526 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002527#endif
2528
2529 bool needWake;
2530 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002531 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532
Prabir Pradhan42611e02018-11-27 14:04:02 -08002533 ConfigurationChangedEntry* newEntry =
2534 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002535 needWake = enqueueInboundEventLocked(newEntry);
2536 } // release lock
2537
2538 if (needWake) {
2539 mLooper->wake();
2540 }
2541}
2542
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002543/**
2544 * If one of the meta shortcuts is detected, process them here:
2545 * Meta + Backspace -> generate BACK
2546 * Meta + Enter -> generate HOME
2547 * This will potentially overwrite keyCode and metaState.
2548 */
2549void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2550 int32_t& keyCode, int32_t& metaState) {
2551 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2552 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2553 if (keyCode == AKEYCODE_DEL) {
2554 newKeyCode = AKEYCODE_BACK;
2555 } else if (keyCode == AKEYCODE_ENTER) {
2556 newKeyCode = AKEYCODE_HOME;
2557 }
2558 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002559 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002560 struct KeyReplacement replacement = {keyCode, deviceId};
2561 mReplacedKeys.add(replacement, newKeyCode);
2562 keyCode = newKeyCode;
2563 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2564 }
2565 } else if (action == AKEY_EVENT_ACTION_UP) {
2566 // In order to maintain a consistent stream of up and down events, check to see if the key
2567 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2568 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002569 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002570 struct KeyReplacement replacement = {keyCode, deviceId};
2571 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2572 if (index >= 0) {
2573 keyCode = mReplacedKeys.valueAt(index);
2574 mReplacedKeys.removeItemsAt(index);
2575 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2576 }
2577 }
2578}
2579
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2581#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002582 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002583 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002584 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002585 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002587 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002588#endif
2589 if (!validateKeyEvent(args->action)) {
2590 return;
2591 }
2592
2593 uint32_t policyFlags = args->policyFlags;
2594 int32_t flags = args->flags;
2595 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002596 // InputDispatcher tracks and generates key repeats on behalf of
2597 // whatever notifies it, so repeatCount should always be set to 0
2598 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2600 policyFlags |= POLICY_FLAG_VIRTUAL;
2601 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2602 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002603 if (policyFlags & POLICY_FLAG_FUNCTION) {
2604 metaState |= AMETA_FUNCTION_ON;
2605 }
2606
2607 policyFlags |= POLICY_FLAG_TRUSTED;
2608
Michael Wright78f24442014-08-06 15:55:28 -07002609 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002610 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002611
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002613 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002614 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 args->downTime, args->eventTime);
2616
Michael Wright2b3c3302018-03-02 17:19:13 +00002617 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002619 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2620 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2621 std::to_string(t.duration().count()).c_str());
2622 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624 bool needWake;
2625 { // acquire lock
2626 mLock.lock();
2627
2628 if (shouldSendKeyToInputFilterLocked(args)) {
2629 mLock.unlock();
2630
2631 policyFlags |= POLICY_FLAG_FILTERED;
2632 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2633 return; // event was consumed by the filter
2634 }
2635
2636 mLock.lock();
2637 }
2638
Prabir Pradhan42611e02018-11-27 14:04:02 -08002639 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002640 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002641 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 metaState, repeatCount, args->downTime);
2643
2644 needWake = enqueueInboundEventLocked(newEntry);
2645 mLock.unlock();
2646 } // release lock
2647
2648 if (needWake) {
2649 mLooper->wake();
2650 }
2651}
2652
2653bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2654 return mInputFilterEnabled;
2655}
2656
2657void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2658#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002659 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2660 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002661 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002662 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2663 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002664 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002665 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666 for (uint32_t i = 0; i < args->pointerCount; i++) {
2667 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2668 "x=%f, y=%f, pressure=%f, size=%f, "
2669 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2670 "orientation=%f",
2671 i, args->pointerProperties[i].id,
2672 args->pointerProperties[i].toolType,
2673 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2674 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2675 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2676 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2677 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2678 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2679 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2680 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2681 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2682 }
2683#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002684 if (!validateMotionEvent(args->action, args->actionButton,
2685 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 return;
2687 }
2688
2689 uint32_t policyFlags = args->policyFlags;
2690 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002691
2692 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002693 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002694 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2695 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2696 std::to_string(t.duration().count()).c_str());
2697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698
2699 bool needWake;
2700 { // acquire lock
2701 mLock.lock();
2702
2703 if (shouldSendMotionToInputFilterLocked(args)) {
2704 mLock.unlock();
2705
2706 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002707 event.initialize(args->deviceId, args->source, args->displayId,
2708 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002709 args->flags, args->edgeFlags, args->metaState, args->buttonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002710 args->classification, 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 args->downTime, args->eventTime,
2712 args->pointerCount, args->pointerProperties, args->pointerCoords);
2713
2714 policyFlags |= POLICY_FLAG_FILTERED;
2715 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2716 return; // event was consumed by the filter
2717 }
2718
2719 mLock.lock();
2720 }
2721
2722 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002723 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002724 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002725 args->action, args->actionButton, args->flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002726 args->metaState, args->buttonState, args->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002728 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002729
2730 needWake = enqueueInboundEventLocked(newEntry);
2731 mLock.unlock();
2732 } // release lock
2733
2734 if (needWake) {
2735 mLooper->wake();
2736 }
2737}
2738
2739bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002740 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002741}
2742
2743void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2744#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002745 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2746 "switchMask=0x%08x",
2747 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748#endif
2749
2750 uint32_t policyFlags = args->policyFlags;
2751 policyFlags |= POLICY_FLAG_TRUSTED;
2752 mPolicy->notifySwitch(args->eventTime,
2753 args->switchValues, args->switchMask, policyFlags);
2754}
2755
2756void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2757#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002758 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759 args->eventTime, args->deviceId);
2760#endif
2761
2762 bool needWake;
2763 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002764 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765
Prabir Pradhan42611e02018-11-27 14:04:02 -08002766 DeviceResetEntry* newEntry =
2767 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768 needWake = enqueueInboundEventLocked(newEntry);
2769 } // release lock
2770
2771 if (needWake) {
2772 mLooper->wake();
2773 }
2774}
2775
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002776int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2778 uint32_t policyFlags) {
2779#if DEBUG_INBOUND_EVENT_DETAILS
2780 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002781 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2782 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783#endif
2784
2785 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2786
2787 policyFlags |= POLICY_FLAG_INJECTED;
2788 if (hasInjectionPermission(injectorPid, injectorUid)) {
2789 policyFlags |= POLICY_FLAG_TRUSTED;
2790 }
2791
2792 EventEntry* firstInjectedEntry;
2793 EventEntry* lastInjectedEntry;
2794 switch (event->getType()) {
2795 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002796 KeyEvent keyEvent;
2797 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2798 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002799 if (! validateKeyEvent(action)) {
2800 return INPUT_EVENT_INJECTION_FAILED;
2801 }
2802
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002803 int32_t flags = keyEvent.getFlags();
2804 int32_t keyCode = keyEvent.getKeyCode();
2805 int32_t metaState = keyEvent.getMetaState();
2806 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2807 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002808 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002809 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002810 keyEvent.getDownTime(), keyEvent.getEventTime());
2811
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2813 policyFlags |= POLICY_FLAG_VIRTUAL;
2814 }
2815
2816 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002817 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002818 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002819 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2820 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2821 std::to_string(t.duration().count()).c_str());
2822 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 }
2824
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002826 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002827 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002829 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2830 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 lastInjectedEntry = firstInjectedEntry;
2832 break;
2833 }
2834
2835 case AINPUT_EVENT_TYPE_MOTION: {
2836 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 int32_t action = motionEvent->getAction();
2838 size_t pointerCount = motionEvent->getPointerCount();
2839 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002840 int32_t actionButton = motionEvent->getActionButton();
Charles Chen3611f1f2019-01-29 17:26:18 +08002841 int32_t displayId = motionEvent->getDisplayId();
Michael Wright7b159c92015-05-14 14:48:03 +01002842 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 return INPUT_EVENT_INJECTION_FAILED;
2844 }
2845
2846 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2847 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002848 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002849 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002850 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2851 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2852 std::to_string(t.duration().count()).c_str());
2853 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854 }
2855
2856 mLock.lock();
2857 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2858 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002859 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002860 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2861 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002862 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002864 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002866 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002867 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2868 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002869 lastInjectedEntry = firstInjectedEntry;
2870 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2871 sampleEventTimes += 1;
2872 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002873 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2874 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002875 motionEvent->getDeviceId(), motionEvent->getSource(),
2876 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002877 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002879 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002881 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002882 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2883 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884 lastInjectedEntry->next = nextInjectedEntry;
2885 lastInjectedEntry = nextInjectedEntry;
2886 }
2887 break;
2888 }
2889
2890 default:
2891 ALOGW("Cannot inject event of type %d", event->getType());
2892 return INPUT_EVENT_INJECTION_FAILED;
2893 }
2894
2895 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2896 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2897 injectionState->injectionIsAsync = true;
2898 }
2899
2900 injectionState->refCount += 1;
2901 lastInjectedEntry->injectionState = injectionState;
2902
2903 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002904 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905 EventEntry* nextEntry = entry->next;
2906 needWake |= enqueueInboundEventLocked(entry);
2907 entry = nextEntry;
2908 }
2909
2910 mLock.unlock();
2911
2912 if (needWake) {
2913 mLooper->wake();
2914 }
2915
2916 int32_t injectionResult;
2917 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002918 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919
2920 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2921 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2922 } else {
2923 for (;;) {
2924 injectionResult = injectionState->injectionResult;
2925 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2926 break;
2927 }
2928
2929 nsecs_t remainingTimeout = endTime - now();
2930 if (remainingTimeout <= 0) {
2931#if DEBUG_INJECTION
2932 ALOGD("injectInputEvent - Timed out waiting for injection result "
2933 "to become available.");
2934#endif
2935 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2936 break;
2937 }
2938
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002939 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 }
2941
2942 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2943 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2944 while (injectionState->pendingForegroundDispatches != 0) {
2945#if DEBUG_INJECTION
2946 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2947 injectionState->pendingForegroundDispatches);
2948#endif
2949 nsecs_t remainingTimeout = endTime - now();
2950 if (remainingTimeout <= 0) {
2951#if DEBUG_INJECTION
2952 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2953 "dispatches to finish.");
2954#endif
2955 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2956 break;
2957 }
2958
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002959 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002960 }
2961 }
2962 }
2963
2964 injectionState->release();
2965 } // release lock
2966
2967#if DEBUG_INJECTION
2968 ALOGD("injectInputEvent - Finished with result %d. "
2969 "injectorPid=%d, injectorUid=%d",
2970 injectionResult, injectorPid, injectorUid);
2971#endif
2972
2973 return injectionResult;
2974}
2975
2976bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2977 return injectorUid == 0
2978 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2979}
2980
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002981void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002982 InjectionState* injectionState = entry->injectionState;
2983 if (injectionState) {
2984#if DEBUG_INJECTION
2985 ALOGD("Setting input event injection result to %d. "
2986 "injectorPid=%d, injectorUid=%d",
2987 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2988#endif
2989
2990 if (injectionState->injectionIsAsync
2991 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2992 // Log the outcome since the injector did not wait for the injection result.
2993 switch (injectionResult) {
2994 case INPUT_EVENT_INJECTION_SUCCEEDED:
2995 ALOGV("Asynchronous input event injection succeeded.");
2996 break;
2997 case INPUT_EVENT_INJECTION_FAILED:
2998 ALOGW("Asynchronous input event injection failed.");
2999 break;
3000 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
3001 ALOGW("Asynchronous input event injection permission denied.");
3002 break;
3003 case INPUT_EVENT_INJECTION_TIMED_OUT:
3004 ALOGW("Asynchronous input event injection timed out.");
3005 break;
3006 }
3007 }
3008
3009 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003010 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003011 }
3012}
3013
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003014void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015 InjectionState* injectionState = entry->injectionState;
3016 if (injectionState) {
3017 injectionState->pendingForegroundDispatches += 1;
3018 }
3019}
3020
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003021void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003022 InjectionState* injectionState = entry->injectionState;
3023 if (injectionState) {
3024 injectionState->pendingForegroundDispatches -= 1;
3025
3026 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003027 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003028 }
3029 }
3030}
3031
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003032std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3033 int32_t displayId) const {
3034 std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>::const_iterator it =
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003035 mWindowHandlesByDisplay.find(displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003036 if(it != mWindowHandlesByDisplay.end()) {
3037 return it->second;
3038 }
3039
3040 // Return an empty one if nothing found.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003041 return std::vector<sp<InputWindowHandle>>();
Arthur Hungb92218b2018-08-14 12:00:21 +08003042}
3043
Michael Wrightd02c5b62014-02-10 15:10:22 -08003044sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003045 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003046 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003047 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3048 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003049 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003050 return windowHandle;
3051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052 }
3053 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003054 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055}
3056
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003057bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003058 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003059 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3060 for (const sp<InputWindowHandle>& handle : windowHandles) {
3061 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003062 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003063 ALOGE("Found window %s in display %" PRId32
3064 ", but it should belong to display %" PRId32,
3065 windowHandle->getName().c_str(), it.first,
3066 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003067 }
3068 return true;
3069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070 }
3071 }
3072 return false;
3073}
3074
Robert Carr5c8a0262018-10-03 16:30:44 -07003075sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3076 size_t count = mInputChannelsByToken.count(token);
3077 if (count == 0) {
3078 return nullptr;
3079 }
3080 return mInputChannelsByToken.at(token);
3081}
3082
Arthur Hungb92218b2018-08-14 12:00:21 +08003083/**
3084 * Called from InputManagerService, update window handle list by displayId that can receive input.
3085 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3086 * If set an empty list, remove all handles from the specific display.
3087 * For focused handle, check if need to change and send a cancel event to previous one.
3088 * For removed handle, check if need to send a cancel event if already in touch.
3089 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003090void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
chaviw291d88a2019-02-14 10:33:58 -08003091 int32_t displayId, const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003092#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003093 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094#endif
3095 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003096 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097
Arthur Hungb92218b2018-08-14 12:00:21 +08003098 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003099 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3100 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101
Tiger Huang721e26f2018-07-24 22:26:19 +08003102 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003103 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003104
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003105 if (inputWindowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003106 // Remove all handles on a display if there are no windows left.
3107 mWindowHandlesByDisplay.erase(displayId);
3108 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003109 // Since we compare the pointer of input window handles across window updates, we need
3110 // to make sure the handle object for the same window stays unchanged across updates.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003111 const std::vector<sp<InputWindowHandle>>& oldHandles =
3112 mWindowHandlesByDisplay[displayId];
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003113 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003114 for (const sp<InputWindowHandle>& handle : oldHandles) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003115 oldHandlesByTokens[handle->getToken()] = handle;
3116 }
3117
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003118 std::vector<sp<InputWindowHandle>> newHandles;
3119 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003120 if (!handle->updateInfo() || (getInputChannelLocked(handle->getToken()) == nullptr
3121 && handle->getInfo()->portalToDisplayId == ADISPLAY_ID_NONE)) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003122 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003123 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003124 continue;
3125 }
3126
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003127 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003128 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003129 handle->getName().c_str(), displayId,
3130 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003131 continue;
3132 }
3133
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003134 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3135 const sp<InputWindowHandle> oldHandle =
3136 oldHandlesByTokens.at(handle->getToken());
3137 oldHandle->updateFrom(handle);
3138 newHandles.push_back(oldHandle);
3139 } else {
3140 newHandles.push_back(handle);
3141 }
3142 }
3143
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003144 for (const sp<InputWindowHandle>& windowHandle : newHandles) {
Arthur Hung7ab76b12019-01-09 19:17:20 +08003145 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3146 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3147 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003148 newFocusedWindowHandle = windowHandle;
3149 }
3150 if (windowHandle == mLastHoverWindowHandle) {
3151 foundHoveredWindow = true;
3152 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003153 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003154
3155 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003156 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 }
3158
3159 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003160 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 }
3162
Tiger Huang721e26f2018-07-24 22:26:19 +08003163 sp<InputWindowHandle> oldFocusedWindowHandle =
3164 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3165
3166 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3167 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003169 ALOGD("Focus left window: %s in display %" PRId32,
3170 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003172 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3173 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003174 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3176 "focus left window");
3177 synthesizeCancelationEventsForInputChannelLocked(
3178 focusedInputChannel, options);
3179 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003180 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003182 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003184 ALOGD("Focus entered window: %s in display %" PRId32,
3185 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003187 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 }
Robert Carrf759f162018-11-13 12:57:11 -08003189
3190 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003191 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003192 }
3193
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 }
3195
Arthur Hungb92218b2018-08-14 12:00:21 +08003196 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3197 if (stateIndex >= 0) {
3198 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003199 for (size_t i = 0; i < state.windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003200 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003201 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003203 ALOGD("Touched window was removed: %s in display %" PRId32,
3204 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003206 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003207 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003208 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003209 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3210 "touched window was removed");
3211 synthesizeCancelationEventsForInputChannelLocked(
3212 touchedInputChannel, options);
3213 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003214 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003215 } else {
3216 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 }
3219 }
3220
3221 // Release information for windows that are no longer present.
3222 // This ensures that unused input channels are released promptly.
3223 // Otherwise, they might stick around until the window handle is destroyed
3224 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003225 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003226 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003228 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003230 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 }
3232 }
3233 } // release lock
3234
3235 // Wake up poll loop since it may need to make new input dispatching choices.
3236 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003237
3238 if (setInputWindowsListener) {
3239 setInputWindowsListener->onSetInputWindowsFinished();
3240 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241}
3242
3243void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003244 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003246 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247#endif
3248 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003249 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250
Tiger Huang721e26f2018-07-24 22:26:19 +08003251 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3252 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003253 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003254 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3255 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003256 resetANRTimeoutsLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003258 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003260 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003262 oldFocusedApplicationHandle.clear();
3263 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264 }
3265
3266#if DEBUG_FOCUS
3267 //logDispatchStateLocked();
3268#endif
3269 } // release lock
3270
3271 // Wake up poll loop since it may need to make new input dispatching choices.
3272 mLooper->wake();
3273}
3274
Tiger Huang721e26f2018-07-24 22:26:19 +08003275/**
3276 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3277 * the display not specified.
3278 *
3279 * We track any unreleased events for each window. If a window loses the ability to receive the
3280 * released event, we will send a cancel event to it. So when the focused display is changed, we
3281 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3282 * display. The display-specified events won't be affected.
3283 */
3284void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3285#if DEBUG_FOCUS
3286 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3287#endif
3288 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003289 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003290
3291 if (mFocusedDisplayId != displayId) {
3292 sp<InputWindowHandle> oldFocusedWindowHandle =
3293 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3294 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003295 sp<InputChannel> inputChannel =
3296 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003297 if (inputChannel != nullptr) {
3298 CancelationOptions options(
3299 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3300 "The display which contains this window no longer has focus.");
3301 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3302 }
3303 }
3304 mFocusedDisplayId = displayId;
3305
3306 // Sanity check
3307 sp<InputWindowHandle> newFocusedWindowHandle =
3308 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003309 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003310
Tiger Huang721e26f2018-07-24 22:26:19 +08003311 if (newFocusedWindowHandle == nullptr) {
3312 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3313 if (!mFocusedWindowHandlesByDisplay.empty()) {
3314 ALOGE("But another display has a focused window:");
3315 for (auto& it : mFocusedWindowHandlesByDisplay) {
3316 const int32_t displayId = it.first;
3317 const sp<InputWindowHandle>& windowHandle = it.second;
3318 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3319 displayId, windowHandle->getName().c_str());
3320 }
3321 }
3322 }
3323 }
3324
3325#if DEBUG_FOCUS
3326 logDispatchStateLocked();
3327#endif
3328 } // release lock
3329
3330 // Wake up poll loop since it may need to make new input dispatching choices.
3331 mLooper->wake();
3332}
3333
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3335#if DEBUG_FOCUS
3336 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3337#endif
3338
3339 bool changed;
3340 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003341 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342
3343 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3344 if (mDispatchFrozen && !frozen) {
3345 resetANRTimeoutsLocked();
3346 }
3347
3348 if (mDispatchEnabled && !enabled) {
3349 resetAndDropEverythingLocked("dispatcher is being disabled");
3350 }
3351
3352 mDispatchEnabled = enabled;
3353 mDispatchFrozen = frozen;
3354 changed = true;
3355 } else {
3356 changed = false;
3357 }
3358
3359#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003360 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361#endif
3362 } // release lock
3363
3364 if (changed) {
3365 // Wake up poll loop since it may need to make new input dispatching choices.
3366 mLooper->wake();
3367 }
3368}
3369
3370void InputDispatcher::setInputFilterEnabled(bool enabled) {
3371#if DEBUG_FOCUS
3372 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3373#endif
3374
3375 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003376 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003377
3378 if (mInputFilterEnabled == enabled) {
3379 return;
3380 }
3381
3382 mInputFilterEnabled = enabled;
3383 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3384 } // release lock
3385
3386 // Wake up poll loop since there might be work to do to drop everything.
3387 mLooper->wake();
3388}
3389
chaviwfbe5d9c2018-12-26 12:23:37 -08003390bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3391 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003393 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003395 return true;
3396 }
3397
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003399 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400
chaviwfbe5d9c2018-12-26 12:23:37 -08003401 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3402 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003403 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003404 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 return false;
3406 }
chaviw4f2dd402018-12-26 15:30:27 -08003407#if DEBUG_FOCUS
3408 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3409 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3410#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3412#if DEBUG_FOCUS
3413 ALOGD("Cannot transfer focus because windows are on different displays.");
3414#endif
3415 return false;
3416 }
3417
3418 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003419 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3420 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3421 for (size_t i = 0; i < state.windows.size(); i++) {
3422 const TouchedWindow& touchedWindow = state.windows[i];
3423 if (touchedWindow.windowHandle == fromWindowHandle) {
3424 int32_t oldTargetFlags = touchedWindow.targetFlags;
3425 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003427 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428
Jeff Brownf086ddb2014-02-11 14:28:48 -08003429 int32_t newTargetFlags = oldTargetFlags
3430 & (InputTarget::FLAG_FOREGROUND
3431 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3432 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433
Jeff Brownf086ddb2014-02-11 14:28:48 -08003434 found = true;
3435 goto Found;
3436 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437 }
3438 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003439Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440
3441 if (! found) {
3442#if DEBUG_FOCUS
3443 ALOGD("Focus transfer failed because from window did not have focus.");
3444#endif
3445 return false;
3446 }
3447
chaviwfbe5d9c2018-12-26 12:23:37 -08003448
3449 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3450 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003451 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3452 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3453 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3454 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3455 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3456
3457 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3458 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3459 "transferring touch focus from this window to another window");
3460 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3461 }
3462
3463#if DEBUG_FOCUS
3464 logDispatchStateLocked();
3465#endif
3466 } // release lock
3467
3468 // Wake up poll loop since it may need to make new input dispatching choices.
3469 mLooper->wake();
3470 return true;
3471}
3472
3473void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3474#if DEBUG_FOCUS
3475 ALOGD("Resetting and dropping all events (%s).", reason);
3476#endif
3477
3478 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3479 synthesizeCancelationEventsForAllConnectionsLocked(options);
3480
3481 resetKeyRepeatLocked();
3482 releasePendingEventLocked();
3483 drainInboundQueueLocked();
3484 resetANRTimeoutsLocked();
3485
Jeff Brownf086ddb2014-02-11 14:28:48 -08003486 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003488 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489}
3490
3491void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003492 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493 dumpDispatchStateLocked(dump);
3494
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003495 std::istringstream stream(dump);
3496 std::string line;
3497
3498 while (std::getline(stream, line, '\n')) {
3499 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 }
3501}
3502
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003503void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3504 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3505 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003506 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507
Tiger Huang721e26f2018-07-24 22:26:19 +08003508 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3509 dump += StringPrintf(INDENT "FocusedApplications:\n");
3510 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3511 const int32_t displayId = it.first;
3512 const sp<InputApplicationHandle>& applicationHandle = it.second;
3513 dump += StringPrintf(
3514 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3515 displayId,
3516 applicationHandle->getName().c_str(),
3517 applicationHandle->getDispatchingTimeout(
3518 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3519 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003520 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003521 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003523
3524 if (!mFocusedWindowHandlesByDisplay.empty()) {
3525 dump += StringPrintf(INDENT "FocusedWindows:\n");
3526 for (auto& it : mFocusedWindowHandlesByDisplay) {
3527 const int32_t displayId = it.first;
3528 const sp<InputWindowHandle>& windowHandle = it.second;
3529 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3530 displayId, windowHandle->getName().c_str());
3531 }
3532 } else {
3533 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3534 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535
Jeff Brownf086ddb2014-02-11 14:28:48 -08003536 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003537 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003538 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3539 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003540 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003541 state.displayId, toString(state.down), toString(state.split),
3542 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003543 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003544 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003545 for (size_t i = 0; i < state.windows.size(); i++) {
3546 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003547 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3548 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003549 touchedWindow.pointerIds.value,
3550 touchedWindow.targetFlags);
3551 }
3552 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003553 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003554 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003555 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003556 dump += INDENT3 "Portal windows:\n";
3557 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003558 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003559 dump += StringPrintf(INDENT4 "%zu: name='%s'\n",
3560 i, portalWindowHandle->getName().c_str());
3561 }
3562 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563 }
3564 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003565 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566 }
3567
Arthur Hungb92218b2018-08-14 12:00:21 +08003568 if (!mWindowHandlesByDisplay.empty()) {
3569 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003570 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003571 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003572 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003573 dump += INDENT2 "Windows:\n";
3574 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003575 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003576 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003577
Arthur Hungb92218b2018-08-14 12:00:21 +08003578 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003579 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, "
Arthur Hungb92218b2018-08-14 12:00:21 +08003580 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003581 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003582 "touchableRegion=",
3583 i, windowInfo->name.c_str(), windowInfo->displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003584 windowInfo->portalToDisplayId,
Arthur Hungb92218b2018-08-14 12:00:21 +08003585 toString(windowInfo->paused),
3586 toString(windowInfo->hasFocus),
3587 toString(windowInfo->hasWallpaper),
3588 toString(windowInfo->visible),
3589 toString(windowInfo->canReceiveKeys),
3590 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3591 windowInfo->layer,
3592 windowInfo->frameLeft, windowInfo->frameTop,
3593 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003594 windowInfo->globalScaleFactor,
3595 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003596 dumpRegion(dump, windowInfo->touchableRegion);
3597 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3598 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3599 windowInfo->ownerPid, windowInfo->ownerUid,
3600 windowInfo->dispatchingTimeout / 1000000.0);
3601 }
3602 } else {
3603 dump += INDENT2 "Windows: <none>\n";
3604 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 }
3606 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003607 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 }
3609
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003610 if (!mMonitoringChannelsByDisplay.empty()) {
3611 for (auto& it : mMonitoringChannelsByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003612 const std::vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003613 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003614 const size_t numChannels = monitoringChannels.size();
3615 for (size_t i = 0; i < numChannels; i++) {
3616 const sp<InputChannel>& channel = monitoringChannels[i];
3617 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3618 }
3619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003620 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003621 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 }
3623
3624 nsecs_t currentTime = now();
3625
3626 // Dump recently dispatched or dropped events from oldest to newest.
3627 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003628 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003630 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003632 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 (currentTime - entry->eventTime) * 0.000001f);
3634 }
3635 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003636 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 }
3638
3639 // Dump event currently being dispatched.
3640 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003641 dump += INDENT "PendingEvent:\n";
3642 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003644 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003645 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3646 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003647 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003648 }
3649
3650 // Dump inbound events from oldest to newest.
3651 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003652 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003654 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003656 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 (currentTime - entry->eventTime) * 0.000001f);
3658 }
3659 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003660 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 }
3662
Michael Wright78f24442014-08-06 15:55:28 -07003663 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003664 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003665 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3666 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3667 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003668 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003669 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3670 }
3671 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003672 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003673 }
3674
Michael Wrightd02c5b62014-02-10 15:10:22 -08003675 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003676 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3678 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003679 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003681 i, connection->getInputChannelName().c_str(),
3682 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003683 connection->getStatusLabel(), toString(connection->monitor),
3684 toString(connection->inputPublisherBlocked));
3685
3686 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003687 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003688 connection->outboundQueue.count());
3689 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3690 entry = entry->next) {
3691 dump.append(INDENT4);
3692 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003693 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 entry->targetFlags, entry->resolvedAction,
3695 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3696 }
3697 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003698 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003699 }
3700
3701 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003702 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003703 connection->waitQueue.count());
3704 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3705 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003706 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003708 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 "age=%0.1fms, wait=%0.1fms\n",
3710 entry->targetFlags, entry->resolvedAction,
3711 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3712 (currentTime - entry->deliveryTime) * 0.000001f);
3713 }
3714 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003715 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003716 }
3717 }
3718 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003719 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720 }
3721
3722 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003723 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 (mAppSwitchDueTime - now()) / 1000000.0);
3725 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003726 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003727 }
3728
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003729 dump += INDENT "Configuration:\n";
3730 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003731 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003732 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003733 mConfig.keyRepeatTimeout * 0.000001f);
3734}
3735
Robert Carr803535b2018-08-02 16:38:15 -07003736status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003737#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003738 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3739 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740#endif
3741
3742 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003743 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003744
Robert Carr4e670e52018-08-15 13:26:12 -07003745 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3746 // treat inputChannel as monitor channel for displayId.
3747 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3748 if (monitor) {
3749 inputChannel->setToken(new BBinder());
3750 }
3751
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752 if (getConnectionIndexLocked(inputChannel) >= 0) {
3753 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003754 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003755 return BAD_VALUE;
3756 }
3757
Robert Carr803535b2018-08-02 16:38:15 -07003758 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003759
3760 int fd = inputChannel->getFd();
3761 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003762 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003764 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003765 if (monitor) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003766 std::vector<sp<InputChannel>>& monitoringChannels =
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003767 mMonitoringChannelsByDisplay[displayId];
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003768 monitoringChannels.push_back(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003769 }
3770
3771 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3772 } // release lock
3773
3774 // Wake the looper because some connections have changed.
3775 mLooper->wake();
3776 return OK;
3777}
3778
3779status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3780#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003781 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003782#endif
3783
3784 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003785 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003786
3787 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3788 if (status) {
3789 return status;
3790 }
3791 } // release lock
3792
3793 // Wake the poll loop because removing the connection may have changed the current
3794 // synchronization state.
3795 mLooper->wake();
3796 return OK;
3797}
3798
3799status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3800 bool notify) {
3801 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3802 if (connectionIndex < 0) {
3803 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003804 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 return BAD_VALUE;
3806 }
3807
3808 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3809 mConnectionsByFd.removeItemsAt(connectionIndex);
3810
Robert Carr5c8a0262018-10-03 16:30:44 -07003811 mInputChannelsByToken.erase(inputChannel->getToken());
3812
Michael Wrightd02c5b62014-02-10 15:10:22 -08003813 if (connection->monitor) {
3814 removeMonitorChannelLocked(inputChannel);
3815 }
3816
3817 mLooper->removeFd(inputChannel->getFd());
3818
3819 nsecs_t currentTime = now();
3820 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3821
3822 connection->status = Connection::STATUS_ZOMBIE;
3823 return OK;
3824}
3825
3826void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003827 for (auto it = mMonitoringChannelsByDisplay.begin();
3828 it != mMonitoringChannelsByDisplay.end(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003829 std::vector<sp<InputChannel>>& monitoringChannels = it->second;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003830 const size_t numChannels = monitoringChannels.size();
3831 for (size_t i = 0; i < numChannels; i++) {
3832 if (monitoringChannels[i] == inputChannel) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003833 monitoringChannels.erase(monitoringChannels.begin() + i);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003834 break;
3835 }
3836 }
3837 if (monitoringChannels.empty()) {
3838 it = mMonitoringChannelsByDisplay.erase(it);
3839 } else {
3840 ++it;
3841 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 }
3843}
3844
3845ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003846 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003847 return -1;
3848 }
3849
Robert Carr4e670e52018-08-15 13:26:12 -07003850 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3851 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3852 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3853 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003854 }
3855 }
Robert Carr4e670e52018-08-15 13:26:12 -07003856
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857 return -1;
3858}
3859
3860void InputDispatcher::onDispatchCycleFinishedLocked(
3861 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3862 CommandEntry* commandEntry = postCommandLocked(
3863 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3864 commandEntry->connection = connection;
3865 commandEntry->eventTime = currentTime;
3866 commandEntry->seq = seq;
3867 commandEntry->handled = handled;
3868}
3869
3870void InputDispatcher::onDispatchCycleBrokenLocked(
3871 nsecs_t currentTime, const sp<Connection>& connection) {
3872 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003873 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
3875 CommandEntry* commandEntry = postCommandLocked(
3876 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3877 commandEntry->connection = connection;
3878}
3879
chaviw0c06c6e2019-01-09 13:27:07 -08003880void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
3881 const sp<InputWindowHandle>& newFocus) {
3882 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
3883 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08003884 CommandEntry* commandEntry = postCommandLocked(
3885 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08003886 commandEntry->oldToken = oldToken;
3887 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003888}
3889
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890void InputDispatcher::onANRLocked(
3891 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3892 const sp<InputWindowHandle>& windowHandle,
3893 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3894 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3895 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3896 ALOGI("Application is not responding: %s. "
3897 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003898 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 dispatchLatency, waitDuration, reason);
3900
3901 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003902 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 struct tm tm;
3904 localtime_r(&t, &tm);
3905 char timestr[64];
3906 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3907 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003908 mLastANRState += INDENT "ANR:\n";
3909 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3910 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003911 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003912 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3913 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3914 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 dumpDispatchStateLocked(mLastANRState);
3916
3917 CommandEntry* commandEntry = postCommandLocked(
3918 & InputDispatcher::doNotifyANRLockedInterruptible);
3919 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003920 commandEntry->inputChannel = windowHandle != nullptr ?
3921 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 commandEntry->reason = reason;
3923}
3924
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003925void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible (
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926 CommandEntry* commandEntry) {
3927 mLock.unlock();
3928
3929 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3930
3931 mLock.lock();
3932}
3933
3934void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3935 CommandEntry* commandEntry) {
3936 sp<Connection> connection = commandEntry->connection;
3937
3938 if (connection->status != Connection::STATUS_ZOMBIE) {
3939 mLock.unlock();
3940
Robert Carr803535b2018-08-02 16:38:15 -07003941 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003942
3943 mLock.lock();
3944 }
3945}
3946
Robert Carrf759f162018-11-13 12:57:11 -08003947void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3948 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08003949 sp<IBinder> oldToken = commandEntry->oldToken;
3950 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003951 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08003952 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08003953 mLock.lock();
3954}
3955
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956void InputDispatcher::doNotifyANRLockedInterruptible(
3957 CommandEntry* commandEntry) {
3958 mLock.unlock();
3959
3960 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003961 commandEntry->inputApplicationHandle,
3962 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 commandEntry->reason);
3964
3965 mLock.lock();
3966
3967 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003968 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969}
3970
3971void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3972 CommandEntry* commandEntry) {
3973 KeyEntry* entry = commandEntry->keyEntry;
3974
3975 KeyEvent event;
3976 initializeKeyEvent(&event, entry);
3977
3978 mLock.unlock();
3979
Michael Wright2b3c3302018-03-02 17:19:13 +00003980 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003981 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3982 commandEntry->inputChannel->getToken() : nullptr;
3983 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003984 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003985 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3986 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3987 std::to_string(t.duration().count()).c_str());
3988 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003989
3990 mLock.lock();
3991
3992 if (delay < 0) {
3993 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3994 } else if (!delay) {
3995 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3996 } else {
3997 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3998 entry->interceptKeyWakeupTime = now() + delay;
3999 }
4000 entry->release();
4001}
4002
chaviwfd6d3512019-03-25 13:23:49 -07004003void InputDispatcher::doOnPointerDownOutsideFocusLockedInterruptible(CommandEntry* commandEntry) {
4004 mLock.unlock();
4005 mPolicy->onPointerDownOutsideFocus(commandEntry->newToken);
4006 mLock.lock();
4007}
4008
Michael Wrightd02c5b62014-02-10 15:10:22 -08004009void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
4010 CommandEntry* commandEntry) {
4011 sp<Connection> connection = commandEntry->connection;
4012 nsecs_t finishTime = commandEntry->eventTime;
4013 uint32_t seq = commandEntry->seq;
4014 bool handled = commandEntry->handled;
4015
4016 // Handle post-event policy actions.
4017 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4018 if (dispatchEntry) {
4019 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4020 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004021 std::string msg =
4022 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004023 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004025 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026 }
4027
4028 bool restartEvent;
4029 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4030 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4031 restartEvent = afterKeyEventLockedInterruptible(connection,
4032 dispatchEntry, keyEntry, handled);
4033 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4034 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4035 restartEvent = afterMotionEventLockedInterruptible(connection,
4036 dispatchEntry, motionEntry, handled);
4037 } else {
4038 restartEvent = false;
4039 }
4040
4041 // Dequeue the event and start the next cycle.
4042 // Note that because the lock might have been released, it is possible that the
4043 // contents of the wait queue to have been drained, so we need to double-check
4044 // a few things.
4045 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4046 connection->waitQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004047 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004048 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4049 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004050 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004051 } else {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08004052 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004053 }
4054 }
4055
4056 // Start the next dispatch cycle for this connection.
4057 startDispatchCycleLocked(now(), connection);
4058 }
4059}
4060
4061bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4062 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004063 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004064 if (!handled) {
4065 // Report the key as unhandled, since the fallback was not handled.
4066 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4067 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004068 return false;
4069 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004070
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004071 // Get the fallback key state.
4072 // Clear it out after dispatching the UP.
4073 int32_t originalKeyCode = keyEntry->keyCode;
4074 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4075 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4076 connection->inputState.removeFallbackKey(originalKeyCode);
4077 }
4078
4079 if (handled || !dispatchEntry->hasForegroundTarget()) {
4080 // If the application handles the original key for which we previously
4081 // generated a fallback or if the window is not a foreground window,
4082 // then cancel the associated fallback key, if any.
4083 if (fallbackKeyCode != -1) {
4084 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004085#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004086 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4088 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4089 keyEntry->policyFlags);
4090#endif
4091 KeyEvent event;
4092 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004093 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004094
4095 mLock.unlock();
4096
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004097 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4098 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004099
4100 mLock.lock();
4101
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004102 // Cancel the fallback key.
4103 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004105 "application handled the original non-fallback key "
4106 "or is no longer a foreground target, "
4107 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 options.keyCode = fallbackKeyCode;
4109 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004110 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004111 connection->inputState.removeFallbackKey(originalKeyCode);
4112 }
4113 } else {
4114 // If the application did not handle a non-fallback key, first check
4115 // that we are in a good state to perform unhandled key event processing
4116 // Then ask the policy what to do with it.
4117 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4118 && keyEntry->repeatCount == 0;
4119 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004121 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4122 "since this is not an initial down. "
4123 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4124 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4125 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004126#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004127 return false;
4128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004129
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004130 // Dispatch the unhandled key to the policy.
4131#if DEBUG_OUTBOUND_EVENT_DETAILS
4132 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4133 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4134 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4135 keyEntry->policyFlags);
4136#endif
4137 KeyEvent event;
4138 initializeKeyEvent(&event, keyEntry);
4139
4140 mLock.unlock();
4141
4142 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4143 &event, keyEntry->policyFlags, &event);
4144
4145 mLock.lock();
4146
4147 if (connection->status != Connection::STATUS_NORMAL) {
4148 connection->inputState.removeFallbackKey(originalKeyCode);
4149 return false;
4150 }
4151
4152 // Latch the fallback keycode for this key on an initial down.
4153 // The fallback keycode cannot change at any other point in the lifecycle.
4154 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004156 fallbackKeyCode = event.getKeyCode();
4157 } else {
4158 fallbackKeyCode = AKEYCODE_UNKNOWN;
4159 }
4160 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4161 }
4162
4163 ALOG_ASSERT(fallbackKeyCode != -1);
4164
4165 // Cancel the fallback key if the policy decides not to send it anymore.
4166 // We will continue to dispatch the key to the policy but we will no
4167 // longer dispatch a fallback key to the application.
4168 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4169 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4170#if DEBUG_OUTBOUND_EVENT_DETAILS
4171 if (fallback) {
4172 ALOGD("Unhandled key event: Policy requested to send key %d"
4173 "as a fallback for %d, but on the DOWN it had requested "
4174 "to send %d instead. Fallback canceled.",
4175 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4176 } else {
4177 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4178 "but on the DOWN it had requested to send %d. "
4179 "Fallback canceled.",
4180 originalKeyCode, fallbackKeyCode);
4181 }
4182#endif
4183
4184 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4185 "canceling fallback, policy no longer desires it");
4186 options.keyCode = fallbackKeyCode;
4187 synthesizeCancelationEventsForConnectionLocked(connection, options);
4188
4189 fallback = false;
4190 fallbackKeyCode = AKEYCODE_UNKNOWN;
4191 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4192 connection->inputState.setFallbackKey(originalKeyCode,
4193 fallbackKeyCode);
4194 }
4195 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196
4197#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004198 {
4199 std::string msg;
4200 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4201 connection->inputState.getFallbackKeys();
4202 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4203 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4204 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004206 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4207 fallbackKeys.size(), msg.c_str());
4208 }
4209#endif
4210
4211 if (fallback) {
4212 // Restart the dispatch cycle using the fallback key.
4213 keyEntry->eventTime = event.getEventTime();
4214 keyEntry->deviceId = event.getDeviceId();
4215 keyEntry->source = event.getSource();
4216 keyEntry->displayId = event.getDisplayId();
4217 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4218 keyEntry->keyCode = fallbackKeyCode;
4219 keyEntry->scanCode = event.getScanCode();
4220 keyEntry->metaState = event.getMetaState();
4221 keyEntry->repeatCount = event.getRepeatCount();
4222 keyEntry->downTime = event.getDownTime();
4223 keyEntry->syntheticRepeat = false;
4224
4225#if DEBUG_OUTBOUND_EVENT_DETAILS
4226 ALOGD("Unhandled key event: Dispatching fallback key. "
4227 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4228 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4229#endif
4230 return true; // restart the event
4231 } else {
4232#if DEBUG_OUTBOUND_EVENT_DETAILS
4233 ALOGD("Unhandled key event: No fallback key.");
4234#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004235
4236 // Report the key as unhandled, since there is no fallback key.
4237 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 }
4239 }
4240 return false;
4241}
4242
4243bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4244 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4245 return false;
4246}
4247
4248void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4249 mLock.unlock();
4250
4251 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4252
4253 mLock.lock();
4254}
4255
4256void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004257 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4259 entry->downTime, entry->eventTime);
4260}
4261
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004262void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4264 // TODO Write some statistics about how long we spend waiting.
4265}
4266
4267void InputDispatcher::traceInboundQueueLengthLocked() {
4268 if (ATRACE_ENABLED()) {
4269 ATRACE_INT("iq", mInboundQueue.count());
4270 }
4271}
4272
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004273void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004274 if (ATRACE_ENABLED()) {
4275 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004276 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 ATRACE_INT(counterName, connection->outboundQueue.count());
4278 }
4279}
4280
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004281void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 if (ATRACE_ENABLED()) {
4283 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004284 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 ATRACE_INT(counterName, connection->waitQueue.count());
4286 }
4287}
4288
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004289void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004290 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004292 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 dumpDispatchStateLocked(dump);
4294
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004295 if (!mLastANRState.empty()) {
4296 dump += "\nInput Dispatcher State at time of last ANR:\n";
4297 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 }
4299}
4300
4301void InputDispatcher::monitor() {
4302 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004303 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004305 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306}
4307
4308
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309// --- InputDispatcher::InjectionState ---
4310
4311InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4312 refCount(1),
4313 injectorPid(injectorPid), injectorUid(injectorUid),
4314 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4315 pendingForegroundDispatches(0) {
4316}
4317
4318InputDispatcher::InjectionState::~InjectionState() {
4319}
4320
4321void InputDispatcher::InjectionState::release() {
4322 refCount -= 1;
4323 if (refCount == 0) {
4324 delete this;
4325 } else {
4326 ALOG_ASSERT(refCount > 0);
4327 }
4328}
4329
4330
4331// --- InputDispatcher::EventEntry ---
4332
Prabir Pradhan42611e02018-11-27 14:04:02 -08004333InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4334 nsecs_t eventTime, uint32_t policyFlags) :
4335 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4336 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337}
4338
4339InputDispatcher::EventEntry::~EventEntry() {
4340 releaseInjectionState();
4341}
4342
4343void InputDispatcher::EventEntry::release() {
4344 refCount -= 1;
4345 if (refCount == 0) {
4346 delete this;
4347 } else {
4348 ALOG_ASSERT(refCount > 0);
4349 }
4350}
4351
4352void InputDispatcher::EventEntry::releaseInjectionState() {
4353 if (injectionState) {
4354 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004355 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356 }
4357}
4358
4359
4360// --- InputDispatcher::ConfigurationChangedEntry ---
4361
Prabir Pradhan42611e02018-11-27 14:04:02 -08004362InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4363 uint32_t sequenceNum, nsecs_t eventTime) :
4364 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365}
4366
4367InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4368}
4369
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004370void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4371 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372}
4373
4374
4375// --- InputDispatcher::DeviceResetEntry ---
4376
Prabir Pradhan42611e02018-11-27 14:04:02 -08004377InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4378 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4379 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380 deviceId(deviceId) {
4381}
4382
4383InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4384}
4385
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004386void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4387 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 deviceId, policyFlags);
4389}
4390
4391
4392// --- InputDispatcher::KeyEntry ---
4393
Prabir Pradhan42611e02018-11-27 14:04:02 -08004394InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004395 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4397 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004398 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004399 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004400 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4401 repeatCount(repeatCount), downTime(downTime),
4402 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4403 interceptKeyWakeupTime(0) {
4404}
4405
4406InputDispatcher::KeyEntry::~KeyEntry() {
4407}
4408
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004409void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004410 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004411 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4412 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004413 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004414 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004415}
4416
4417void InputDispatcher::KeyEntry::recycle() {
4418 releaseInjectionState();
4419
4420 dispatchInProgress = false;
4421 syntheticRepeat = false;
4422 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4423 interceptKeyWakeupTime = 0;
4424}
4425
4426
4427// --- InputDispatcher::MotionEntry ---
4428
Prabir Pradhan42611e02018-11-27 14:04:02 -08004429InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004430 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4431 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004432 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4433 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004434 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004435 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4436 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004437 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004438 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004439 deviceId(deviceId), source(source), displayId(displayId), action(action),
4440 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004441 classification(classification), edgeFlags(edgeFlags),
4442 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004443 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004444 for (uint32_t i = 0; i < pointerCount; i++) {
4445 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4446 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004447 if (xOffset || yOffset) {
4448 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004450 }
4451}
4452
4453InputDispatcher::MotionEntry::~MotionEntry() {
4454}
4455
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004456void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004457 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004458 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004459 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004460 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004461 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4462 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004463
Michael Wrightd02c5b62014-02-10 15:10:22 -08004464 for (uint32_t i = 0; i < pointerCount; i++) {
4465 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004466 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004467 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004468 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004469 pointerCoords[i].getX(), pointerCoords[i].getY());
4470 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004471 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004472}
4473
4474
4475// --- InputDispatcher::DispatchEntry ---
4476
4477volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4478
4479InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004480 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4481 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004482 seq(nextSeq()),
4483 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004484 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4485 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004486 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4487 eventEntry->refCount += 1;
4488}
4489
4490InputDispatcher::DispatchEntry::~DispatchEntry() {
4491 eventEntry->release();
4492}
4493
4494uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4495 // Sequence number 0 is reserved and will never be returned.
4496 uint32_t seq;
4497 do {
4498 seq = android_atomic_inc(&sNextSeqAtomic);
4499 } while (!seq);
4500 return seq;
4501}
4502
4503
4504// --- InputDispatcher::InputState ---
4505
4506InputDispatcher::InputState::InputState() {
4507}
4508
4509InputDispatcher::InputState::~InputState() {
4510}
4511
4512bool InputDispatcher::InputState::isNeutral() const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004513 return mKeyMementos.empty() && mMotionMementos.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004514}
4515
4516bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4517 int32_t displayId) const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004518 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519 if (memento.deviceId == deviceId
4520 && memento.source == source
4521 && memento.displayId == displayId
4522 && memento.hovering) {
4523 return true;
4524 }
4525 }
4526 return false;
4527}
4528
4529bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4530 int32_t action, int32_t flags) {
4531 switch (action) {
4532 case AKEY_EVENT_ACTION_UP: {
4533 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4534 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4535 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4536 mFallbackKeys.removeItemsAt(i);
4537 } else {
4538 i += 1;
4539 }
4540 }
4541 }
4542 ssize_t index = findKeyMemento(entry);
4543 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004544 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004545 return true;
4546 }
4547 /* FIXME: We can't just drop the key up event because that prevents creating
4548 * popup windows that are automatically shown when a key is held and then
4549 * dismissed when the key is released. The problem is that the popup will
4550 * not have received the original key down, so the key up will be considered
4551 * to be inconsistent with its observed state. We could perhaps handle this
4552 * by synthesizing a key down but that will cause other problems.
4553 *
4554 * So for now, allow inconsistent key up events to be dispatched.
4555 *
4556#if DEBUG_OUTBOUND_EVENT_DETAILS
4557 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4558 "keyCode=%d, scanCode=%d",
4559 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4560#endif
4561 return false;
4562 */
4563 return true;
4564 }
4565
4566 case AKEY_EVENT_ACTION_DOWN: {
4567 ssize_t index = findKeyMemento(entry);
4568 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004569 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004570 }
4571 addKeyMemento(entry, flags);
4572 return true;
4573 }
4574
4575 default:
4576 return true;
4577 }
4578}
4579
4580bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4581 int32_t action, int32_t flags) {
4582 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4583 switch (actionMasked) {
4584 case AMOTION_EVENT_ACTION_UP:
4585 case AMOTION_EVENT_ACTION_CANCEL: {
4586 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4587 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004588 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589 return true;
4590 }
4591#if DEBUG_OUTBOUND_EVENT_DETAILS
4592 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004593 "displayId=%" PRId32 ", actionMasked=%d",
4594 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004595#endif
4596 return false;
4597 }
4598
4599 case AMOTION_EVENT_ACTION_DOWN: {
4600 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4601 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004602 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 }
4604 addMotionMemento(entry, flags, false /*hovering*/);
4605 return true;
4606 }
4607
4608 case AMOTION_EVENT_ACTION_POINTER_UP:
4609 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4610 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004611 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4612 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4613 // generate cancellation events for these since they're based in relative rather than
4614 // absolute units.
4615 return true;
4616 }
4617
Michael Wrightd02c5b62014-02-10 15:10:22 -08004618 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004619
4620 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4621 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4622 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4623 // other value and we need to track the motion so we can send cancellation events for
4624 // anything generating fallback events (e.g. DPad keys for joystick movements).
4625 if (index >= 0) {
4626 if (entry->pointerCoords[0].isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004627 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wright38dcdff2014-03-19 12:06:10 -07004628 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004629 MotionMemento& memento = mMotionMementos[index];
Michael Wright38dcdff2014-03-19 12:06:10 -07004630 memento.setPointers(entry);
4631 }
4632 } else if (!entry->pointerCoords[0].isEmpty()) {
4633 addMotionMemento(entry, flags, false /*hovering*/);
4634 }
4635
4636 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4637 return true;
4638 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004640 MotionMemento& memento = mMotionMementos[index];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641 memento.setPointers(entry);
4642 return true;
4643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644#if DEBUG_OUTBOUND_EVENT_DETAILS
4645 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004646 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4647 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004648#endif
4649 return false;
4650 }
4651
4652 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4653 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4654 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004655 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656 return true;
4657 }
4658#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004659 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4660 "displayId=%" PRId32,
4661 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662#endif
4663 return false;
4664 }
4665
4666 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4667 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4668 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4669 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004670 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004671 }
4672 addMotionMemento(entry, flags, true /*hovering*/);
4673 return true;
4674 }
4675
4676 default:
4677 return true;
4678 }
4679}
4680
4681ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4682 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004683 const KeyMemento& memento = mKeyMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684 if (memento.deviceId == entry->deviceId
4685 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004686 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004687 && memento.keyCode == entry->keyCode
4688 && memento.scanCode == entry->scanCode) {
4689 return i;
4690 }
4691 }
4692 return -1;
4693}
4694
4695ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4696 bool hovering) const {
4697 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004698 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699 if (memento.deviceId == entry->deviceId
4700 && memento.source == entry->source
4701 && memento.displayId == entry->displayId
4702 && memento.hovering == hovering) {
4703 return i;
4704 }
4705 }
4706 return -1;
4707}
4708
4709void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004710 KeyMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 memento.deviceId = entry->deviceId;
4712 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004713 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714 memento.keyCode = entry->keyCode;
4715 memento.scanCode = entry->scanCode;
4716 memento.metaState = entry->metaState;
4717 memento.flags = flags;
4718 memento.downTime = entry->downTime;
4719 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004720 mKeyMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004721}
4722
4723void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4724 int32_t flags, bool hovering) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004725 MotionMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 memento.deviceId = entry->deviceId;
4727 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004728 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729 memento.flags = flags;
4730 memento.xPrecision = entry->xPrecision;
4731 memento.yPrecision = entry->yPrecision;
4732 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 memento.setPointers(entry);
4734 memento.hovering = hovering;
4735 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004736 mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737}
4738
4739void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4740 pointerCount = entry->pointerCount;
4741 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4742 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4743 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4744 }
4745}
4746
4747void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004748 std::vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4749 for (KeyMemento& memento : mKeyMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750 if (shouldCancelKey(memento, options)) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004751 outEvents.push_back(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004752 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4754 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4755 }
4756 }
4757
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004758 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004760 const int32_t action = memento.hovering ?
4761 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004762 outEvents.push_back(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004763 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004764 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4765 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004767 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004768 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004769 }
4770 }
4771}
4772
4773void InputDispatcher::InputState::clear() {
4774 mKeyMementos.clear();
4775 mMotionMementos.clear();
4776 mFallbackKeys.clear();
4777}
4778
4779void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4780 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004781 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4783 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004784 const MotionMemento& otherMemento = other.mMotionMementos[j];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785 if (memento.deviceId == otherMemento.deviceId
4786 && memento.source == otherMemento.source
4787 && memento.displayId == otherMemento.displayId) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004788 other.mMotionMementos.erase(other.mMotionMementos.begin() + j);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789 } else {
4790 j += 1;
4791 }
4792 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004793 other.mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794 }
4795 }
4796}
4797
4798int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4799 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4800 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4801}
4802
4803void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4804 int32_t fallbackKeyCode) {
4805 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4806 if (index >= 0) {
4807 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4808 } else {
4809 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4810 }
4811}
4812
4813void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4814 mFallbackKeys.removeItem(originalKeyCode);
4815}
4816
4817bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4818 const CancelationOptions& options) {
4819 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4820 return false;
4821 }
4822
4823 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4824 return false;
4825 }
4826
4827 switch (options.mode) {
4828 case CancelationOptions::CANCEL_ALL_EVENTS:
4829 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4830 return true;
4831 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4832 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004833 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4834 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 default:
4836 return false;
4837 }
4838}
4839
4840bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4841 const CancelationOptions& options) {
4842 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4843 return false;
4844 }
4845
4846 switch (options.mode) {
4847 case CancelationOptions::CANCEL_ALL_EVENTS:
4848 return true;
4849 case CancelationOptions::CANCEL_POINTER_EVENTS:
4850 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4851 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4852 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004853 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4854 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 default:
4856 return false;
4857 }
4858}
4859
4860
4861// --- InputDispatcher::Connection ---
4862
Robert Carr803535b2018-08-02 16:38:15 -07004863InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4864 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 monitor(monitor),
4866 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4867}
4868
4869InputDispatcher::Connection::~Connection() {
4870}
4871
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004872const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004873 if (inputChannel != nullptr) {
4874 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 }
4876 if (monitor) {
4877 return "monitor";
4878 }
4879 return "?";
4880}
4881
4882const char* InputDispatcher::Connection::getStatusLabel() const {
4883 switch (status) {
4884 case STATUS_NORMAL:
4885 return "NORMAL";
4886
4887 case STATUS_BROKEN:
4888 return "BROKEN";
4889
4890 case STATUS_ZOMBIE:
4891 return "ZOMBIE";
4892
4893 default:
4894 return "UNKNOWN";
4895 }
4896}
4897
4898InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004899 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 if (entry->seq == seq) {
4901 return entry;
4902 }
4903 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004904 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905}
4906
4907
4908// --- InputDispatcher::CommandEntry ---
4909
4910InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004911 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912 seq(0), handled(false) {
4913}
4914
4915InputDispatcher::CommandEntry::~CommandEntry() {
4916}
4917
4918
4919// --- InputDispatcher::TouchState ---
4920
4921InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004922 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004923}
4924
4925InputDispatcher::TouchState::~TouchState() {
4926}
4927
4928void InputDispatcher::TouchState::reset() {
4929 down = false;
4930 split = false;
4931 deviceId = -1;
4932 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004933 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004935 portalWindows.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004936}
4937
4938void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4939 down = other.down;
4940 split = other.split;
4941 deviceId = other.deviceId;
4942 source = other.source;
4943 displayId = other.displayId;
4944 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004945 portalWindows = other.portalWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946}
4947
4948void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4949 int32_t targetFlags, BitSet32 pointerIds) {
4950 if (targetFlags & InputTarget::FLAG_SPLIT) {
4951 split = true;
4952 }
4953
4954 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004955 TouchedWindow& touchedWindow = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956 if (touchedWindow.windowHandle == windowHandle) {
4957 touchedWindow.targetFlags |= targetFlags;
4958 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4959 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4960 }
4961 touchedWindow.pointerIds.value |= pointerIds.value;
4962 return;
4963 }
4964 }
4965
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004966 TouchedWindow touchedWindow;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004967 touchedWindow.windowHandle = windowHandle;
4968 touchedWindow.targetFlags = targetFlags;
4969 touchedWindow.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004970 windows.push_back(touchedWindow);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971}
4972
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004973void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
4974 size_t numWindows = portalWindows.size();
4975 for (size_t i = 0; i < numWindows; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004976 if (portalWindows[i] == windowHandle) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004977 return;
4978 }
4979 }
4980 portalWindows.push_back(windowHandle);
4981}
4982
Michael Wrightd02c5b62014-02-10 15:10:22 -08004983void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4984 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004985 if (windows[i].windowHandle == windowHandle) {
4986 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004987 return;
4988 }
4989 }
4990}
4991
Robert Carr803535b2018-08-02 16:38:15 -07004992void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4993 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004994 if (windows[i].windowHandle->getToken() == token) {
4995 windows.erase(windows.begin() + i);
Robert Carr803535b2018-08-02 16:38:15 -07004996 return;
4997 }
4998 }
4999}
5000
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
5002 for (size_t i = 0 ; i < windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005003 TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
5005 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
5006 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
5007 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
5008 i += 1;
5009 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005010 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 }
5012 }
5013}
5014
5015sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
5016 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005017 const TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005018 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5019 return window.windowHandle;
5020 }
5021 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005022 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005023}
5024
5025bool InputDispatcher::TouchState::isSlippery() const {
5026 // Must have exactly one foreground window.
5027 bool haveSlipperyForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005028 for (const TouchedWindow& window : windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005029 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5030 if (haveSlipperyForegroundWindow
5031 || !(window.windowHandle->getInfo()->layoutParamsFlags
5032 & InputWindowInfo::FLAG_SLIPPERY)) {
5033 return false;
5034 }
5035 haveSlipperyForegroundWindow = true;
5036 }
5037 }
5038 return haveSlipperyForegroundWindow;
5039}
5040
5041
5042// --- InputDispatcherThread ---
5043
5044InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5045 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5046}
5047
5048InputDispatcherThread::~InputDispatcherThread() {
5049}
5050
5051bool InputDispatcherThread::threadLoop() {
5052 mDispatcher->dispatchOnce();
5053 return true;
5054}
5055
5056} // namespace android