blob: 3a255da23fa5311199526e7bf2e0c215a02c34cb [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputDispatcher"
18#define ATRACE_TAG ATRACE_TAG_INPUT
19
20//#define LOG_NDEBUG 0
21
22// Log detailed debug messages about each inbound event notification to the dispatcher.
23#define DEBUG_INBOUND_EVENT_DETAILS 0
24
25// Log detailed debug messages about each outbound event processed by the dispatcher.
26#define DEBUG_OUTBOUND_EVENT_DETAILS 0
27
28// Log debug messages about the dispatch cycle.
29#define DEBUG_DISPATCH_CYCLE 0
30
31// Log debug messages about registrations.
32#define DEBUG_REGISTRATION 0
33
34// Log debug messages about input event injection.
35#define DEBUG_INJECTION 0
36
37// Log debug messages about input focus tracking.
38#define DEBUG_FOCUS 0
39
40// Log debug messages about the app switch latency optimization.
41#define DEBUG_APP_SWITCH 0
42
43// Log debug messages about hover events.
44#define DEBUG_HOVER 0
45
46#include "InputDispatcher.h"
47
Michael Wrightd02c5b62014-02-10 15:10:22 -080048#include <errno.h>
Siarhei Vishniakou443ad902019-03-06 17:25:41 -080049#include <inttypes.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080050#include <limits.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080051#include <sstream>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070052#include <stddef.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080053#include <time.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054#include <unistd.h>
55
Michael Wright2b3c3302018-03-02 17:19:13 +000056#include <android-base/chrono_utils.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057#include <android-base/stringprintf.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070058#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070059#include <utils/Trace.h>
60#include <powermanager/PowerManager.h>
61#include <ui/Region.h>
Robert Carr4e670e52018-08-15 13:26:12 -070062#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080063
64#define INDENT " "
65#define INDENT2 " "
66#define INDENT3 " "
67#define INDENT4 " "
68
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080069using android::base::StringPrintf;
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071namespace android {
72
73// Default input dispatching timeout if there is no focused application or paused window
74// from which to determine an appropriate dispatching timeout.
Michael Wright2b3c3302018-03-02 17:19:13 +000075constexpr nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
77// Amount of time to allow for all pending events to be processed when an app switch
78// key is on the way. This is used to preempt input dispatch and drop input events
79// when an application takes too long to respond and the user has pressed an app switch key.
Michael Wright2b3c3302018-03-02 17:19:13 +000080constexpr nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080081
82// Amount of time to allow for an event to be dispatched (measured since its eventTime)
83// before considering it stale and dropping it.
Michael Wright2b3c3302018-03-02 17:19:13 +000084constexpr nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080085
86// Amount of time to allow touch events to be streamed out to a connection before requiring
87// that the first event be finished. This value extends the ANR timeout by the specified
88// amount. For example, if streaming is allowed to get ahead by one second relative to the
89// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
Michael Wright2b3c3302018-03-02 17:19:13 +000090constexpr nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
Michael Wright2b3c3302018-03-02 17:19:13 +000093constexpr nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
94
95// Log a warning when an interception call takes longer than this to process.
96constexpr std::chrono::milliseconds SLOW_INTERCEPTION_THRESHOLD = 50ms;
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
98// Number of recent events to keep for debugging purposes.
Michael Wright2b3c3302018-03-02 17:19:13 +000099constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
100
Prabir Pradhan42611e02018-11-27 14:04:02 -0800101// Sequence number for synthesized or injected events.
102constexpr uint32_t SYNTHESIZED_EVENT_SEQUENCE_NUM = 0;
103
Michael Wrightd02c5b62014-02-10 15:10:22 -0800104
105static inline nsecs_t now() {
106 return systemTime(SYSTEM_TIME_MONOTONIC);
107}
108
109static inline const char* toString(bool value) {
110 return value ? "true" : "false";
111}
112
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -0800113static std::string motionActionToString(int32_t action) {
114 // Convert MotionEvent action to string
115 switch(action & AMOTION_EVENT_ACTION_MASK) {
116 case AMOTION_EVENT_ACTION_DOWN:
117 return "DOWN";
118 case AMOTION_EVENT_ACTION_MOVE:
119 return "MOVE";
120 case AMOTION_EVENT_ACTION_UP:
121 return "UP";
122 case AMOTION_EVENT_ACTION_POINTER_DOWN:
123 return "POINTER_DOWN";
124 case AMOTION_EVENT_ACTION_POINTER_UP:
125 return "POINTER_UP";
126 }
127 return StringPrintf("%" PRId32, action);
128}
129
130static std::string keyActionToString(int32_t action) {
131 // Convert KeyEvent action to string
132 switch(action) {
133 case AKEY_EVENT_ACTION_DOWN:
134 return "DOWN";
135 case AKEY_EVENT_ACTION_UP:
136 return "UP";
137 case AKEY_EVENT_ACTION_MULTIPLE:
138 return "MULTIPLE";
139 }
140 return StringPrintf("%" PRId32, action);
141}
142
Michael Wrightd02c5b62014-02-10 15:10:22 -0800143static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
144 return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
145 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
146}
147
148static bool isValidKeyAction(int32_t action) {
149 switch (action) {
150 case AKEY_EVENT_ACTION_DOWN:
151 case AKEY_EVENT_ACTION_UP:
152 return true;
153 default:
154 return false;
155 }
156}
157
158static bool validateKeyEvent(int32_t action) {
159 if (! isValidKeyAction(action)) {
160 ALOGE("Key event has invalid action code 0x%x", action);
161 return false;
162 }
163 return true;
164}
165
Michael Wright7b159c92015-05-14 14:48:03 +0100166static bool isValidMotionAction(int32_t action, int32_t actionButton, int32_t pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800167 switch (action & AMOTION_EVENT_ACTION_MASK) {
168 case AMOTION_EVENT_ACTION_DOWN:
169 case AMOTION_EVENT_ACTION_UP:
170 case AMOTION_EVENT_ACTION_CANCEL:
171 case AMOTION_EVENT_ACTION_MOVE:
172 case AMOTION_EVENT_ACTION_OUTSIDE:
173 case AMOTION_EVENT_ACTION_HOVER_ENTER:
174 case AMOTION_EVENT_ACTION_HOVER_MOVE:
175 case AMOTION_EVENT_ACTION_HOVER_EXIT:
176 case AMOTION_EVENT_ACTION_SCROLL:
177 return true;
178 case AMOTION_EVENT_ACTION_POINTER_DOWN:
179 case AMOTION_EVENT_ACTION_POINTER_UP: {
180 int32_t index = getMotionEventActionPointerIndex(action);
Dan Albert1bd2fc02016-02-02 15:11:57 -0800181 return index >= 0 && index < pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800182 }
Michael Wright7b159c92015-05-14 14:48:03 +0100183 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
184 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
185 return actionButton != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186 default:
187 return false;
188 }
189}
190
Michael Wright7b159c92015-05-14 14:48:03 +0100191static bool validateMotionEvent(int32_t action, int32_t actionButton, size_t pointerCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800192 const PointerProperties* pointerProperties) {
Michael Wright7b159c92015-05-14 14:48:03 +0100193 if (! isValidMotionAction(action, actionButton, pointerCount)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800194 ALOGE("Motion event has invalid action code 0x%x", action);
195 return false;
196 }
197 if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
Narayan Kamath37764c72014-03-27 14:21:09 +0000198 ALOGE("Motion event has invalid pointer count %zu; value must be between 1 and %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800199 pointerCount, MAX_POINTERS);
200 return false;
201 }
202 BitSet32 pointerIdBits;
203 for (size_t i = 0; i < pointerCount; i++) {
204 int32_t id = pointerProperties[i].id;
205 if (id < 0 || id > MAX_POINTER_ID) {
206 ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
207 id, MAX_POINTER_ID);
208 return false;
209 }
210 if (pointerIdBits.hasBit(id)) {
211 ALOGE("Motion event has duplicate pointer id %d", id);
212 return false;
213 }
214 pointerIdBits.markBit(id);
215 }
216 return true;
217}
218
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800219static void dumpRegion(std::string& dump, const Region& region) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220 if (region.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800221 dump += "<empty>";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800222 return;
223 }
224
225 bool first = true;
226 Region::const_iterator cur = region.begin();
227 Region::const_iterator const tail = region.end();
228 while (cur != tail) {
229 if (first) {
230 first = false;
231 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800232 dump += "|";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800233 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800234 dump += StringPrintf("[%d,%d][%d,%d]", cur->left, cur->top, cur->right, cur->bottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800235 cur++;
236 }
237}
238
Tiger Huang721e26f2018-07-24 22:26:19 +0800239template<typename T, typename U>
240static T getValueByKey(std::unordered_map<U, T>& map, U key) {
241 typename std::unordered_map<U, T>::const_iterator it = map.find(key);
242 return it != map.end() ? it->second : T{};
243}
244
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245
246// --- InputDispatcher ---
247
248InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
249 mPolicy(policy),
Yi Kong9b14ac62018-07-17 13:48:38 -0700250 mPendingEvent(nullptr), mLastDropReason(DROP_REASON_NOT_DROPPED),
Michael Wright3a981722015-06-10 15:26:13 +0100251 mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
Yi Kong9b14ac62018-07-17 13:48:38 -0700252 mNextUnblockedEvent(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
Tiger Huang721e26f2018-07-24 22:26:19 +0800254 mFocusedDisplayId(ADISPLAY_ID_DEFAULT),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800255 mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
256 mLooper = new Looper(false);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800257 mReporter = createInputReporter();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258
Yi Kong9b14ac62018-07-17 13:48:38 -0700259 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260
261 policy->getDispatcherConfiguration(&mConfig);
262}
263
264InputDispatcher::~InputDispatcher() {
265 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800266 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267
268 resetKeyRepeatLocked();
269 releasePendingEventLocked();
270 drainInboundQueueLocked();
271 }
272
273 while (mConnectionsByFd.size() != 0) {
274 unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
275 }
276}
277
278void InputDispatcher::dispatchOnce() {
279 nsecs_t nextWakeupTime = LONG_LONG_MAX;
280 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -0800281 std::scoped_lock _l(mLock);
282 mDispatcherIsAlive.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800283
284 // Run a dispatch loop if there are no pending commands.
285 // The dispatch loop might enqueue commands to run afterwards.
286 if (!haveCommandsLocked()) {
287 dispatchOnceInnerLocked(&nextWakeupTime);
288 }
289
290 // Run all pending commands if there are any.
291 // If any commands were run then force the next poll to wake up immediately.
292 if (runCommandsLockedInterruptible()) {
293 nextWakeupTime = LONG_LONG_MIN;
294 }
295 } // release lock
296
297 // Wait for callback or timeout or wake. (make sure we round up, not down)
298 nsecs_t currentTime = now();
299 int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
300 mLooper->pollOnce(timeoutMillis);
301}
302
303void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
304 nsecs_t currentTime = now();
305
Jeff Browndc5992e2014-04-11 01:27:26 -0700306 // Reset the key repeat timer whenever normal dispatch is suspended while the
307 // device is in a non-interactive state. This is to ensure that we abort a key
308 // repeat if the device is just coming out of sleep.
309 if (!mDispatchEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800310 resetKeyRepeatLocked();
311 }
312
313 // If dispatching is frozen, do not process timeouts or try to deliver any new events.
314 if (mDispatchFrozen) {
315#if DEBUG_FOCUS
316 ALOGD("Dispatch frozen. Waiting some more.");
317#endif
318 return;
319 }
320
321 // Optimize latency of app switches.
322 // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
323 // been pressed. When it expires, we preempt dispatch and drop all other pending events.
324 bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
325 if (mAppSwitchDueTime < *nextWakeupTime) {
326 *nextWakeupTime = mAppSwitchDueTime;
327 }
328
329 // Ready to start a new event.
330 // If we don't already have a pending event, go grab one.
331 if (! mPendingEvent) {
332 if (mInboundQueue.isEmpty()) {
333 if (isAppSwitchDue) {
334 // The inbound queue is empty so the app switch key we were waiting
335 // for will never arrive. Stop waiting for it.
336 resetPendingAppSwitchLocked(false);
337 isAppSwitchDue = false;
338 }
339
340 // Synthesize a key repeat if appropriate.
341 if (mKeyRepeatState.lastKeyEntry) {
342 if (currentTime >= mKeyRepeatState.nextRepeatTime) {
343 mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
344 } else {
345 if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
346 *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
347 }
348 }
349 }
350
351 // Nothing to do if there is no pending event.
352 if (!mPendingEvent) {
353 return;
354 }
355 } else {
356 // Inbound queue has at least one entry.
357 mPendingEvent = mInboundQueue.dequeueAtHead();
358 traceInboundQueueLengthLocked();
359 }
360
361 // Poke user activity for this event.
362 if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
363 pokeUserActivityLocked(mPendingEvent);
364 }
365
366 // Get ready to dispatch the event.
367 resetANRTimeoutsLocked();
368 }
369
370 // Now we have an event to dispatch.
371 // All events are eventually dequeued and processed this way, even if we intend to drop them.
Yi Kong9b14ac62018-07-17 13:48:38 -0700372 ALOG_ASSERT(mPendingEvent != nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800373 bool done = false;
374 DropReason dropReason = DROP_REASON_NOT_DROPPED;
375 if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
376 dropReason = DROP_REASON_POLICY;
377 } else if (!mDispatchEnabled) {
378 dropReason = DROP_REASON_DISABLED;
379 }
380
381 if (mNextUnblockedEvent == mPendingEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700382 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800383 }
384
385 switch (mPendingEvent->type) {
386 case EventEntry::TYPE_CONFIGURATION_CHANGED: {
387 ConfigurationChangedEntry* typedEntry =
388 static_cast<ConfigurationChangedEntry*>(mPendingEvent);
389 done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
390 dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
391 break;
392 }
393
394 case EventEntry::TYPE_DEVICE_RESET: {
395 DeviceResetEntry* typedEntry =
396 static_cast<DeviceResetEntry*>(mPendingEvent);
397 done = dispatchDeviceResetLocked(currentTime, typedEntry);
398 dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
399 break;
400 }
401
402 case EventEntry::TYPE_KEY: {
403 KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
404 if (isAppSwitchDue) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800405 if (isAppSwitchKeyEvent(typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406 resetPendingAppSwitchLocked(true);
407 isAppSwitchDue = false;
408 } else if (dropReason == DROP_REASON_NOT_DROPPED) {
409 dropReason = DROP_REASON_APP_SWITCH;
410 }
411 }
412 if (dropReason == DROP_REASON_NOT_DROPPED
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800413 && isStaleEvent(currentTime, typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414 dropReason = DROP_REASON_STALE;
415 }
416 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
417 dropReason = DROP_REASON_BLOCKED;
418 }
419 done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
420 break;
421 }
422
423 case EventEntry::TYPE_MOTION: {
424 MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
425 if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
426 dropReason = DROP_REASON_APP_SWITCH;
427 }
428 if (dropReason == DROP_REASON_NOT_DROPPED
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800429 && isStaleEvent(currentTime, typedEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800430 dropReason = DROP_REASON_STALE;
431 }
432 if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
433 dropReason = DROP_REASON_BLOCKED;
434 }
435 done = dispatchMotionLocked(currentTime, typedEntry,
436 &dropReason, nextWakeupTime);
437 break;
438 }
439
440 default:
441 ALOG_ASSERT(false);
442 break;
443 }
444
445 if (done) {
446 if (dropReason != DROP_REASON_NOT_DROPPED) {
447 dropInboundEventLocked(mPendingEvent, dropReason);
448 }
Michael Wright3a981722015-06-10 15:26:13 +0100449 mLastDropReason = dropReason;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450
451 releasePendingEventLocked();
452 *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
453 }
454}
455
456bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
457 bool needWake = mInboundQueue.isEmpty();
458 mInboundQueue.enqueueAtTail(entry);
459 traceInboundQueueLengthLocked();
460
461 switch (entry->type) {
462 case EventEntry::TYPE_KEY: {
463 // Optimize app switch latency.
464 // If the application takes too long to catch up then we drop all events preceding
465 // the app switch key.
466 KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800467 if (isAppSwitchKeyEvent(keyEntry)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468 if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
469 mAppSwitchSawKeyDown = true;
470 } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
471 if (mAppSwitchSawKeyDown) {
472#if DEBUG_APP_SWITCH
473 ALOGD("App switch is pending!");
474#endif
475 mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
476 mAppSwitchSawKeyDown = false;
477 needWake = true;
478 }
479 }
480 }
481 break;
482 }
483
484 case EventEntry::TYPE_MOTION: {
485 // Optimize case where the current application is unresponsive and the user
486 // decides to touch a window in a different application.
487 // If the application takes too long to catch up then we drop all events preceding
488 // the touch into the other window.
489 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
490 if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
491 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
492 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
Robert Carr740167f2018-10-11 19:03:41 -0700493 && mInputTargetWaitApplicationToken != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494 int32_t displayId = motionEntry->displayId;
495 int32_t x = int32_t(motionEntry->pointerCoords[0].
496 getAxisValue(AMOTION_EVENT_AXIS_X));
497 int32_t y = int32_t(motionEntry->pointerCoords[0].
498 getAxisValue(AMOTION_EVENT_AXIS_Y));
499 sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
Yi Kong9b14ac62018-07-17 13:48:38 -0700500 if (touchedWindowHandle != nullptr
Robert Carr740167f2018-10-11 19:03:41 -0700501 && touchedWindowHandle->getApplicationToken()
502 != mInputTargetWaitApplicationToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503 // User touched a different application than the one we are waiting on.
504 // Flag the event, and start pruning the input queue.
505 mNextUnblockedEvent = motionEntry;
506 needWake = true;
507 }
508 }
509 break;
510 }
511 }
512
513 return needWake;
514}
515
516void InputDispatcher::addRecentEventLocked(EventEntry* entry) {
517 entry->refCount += 1;
518 mRecentQueue.enqueueAtTail(entry);
519 if (mRecentQueue.count() > RECENT_QUEUE_MAX_SIZE) {
520 mRecentQueue.dequeueAtHead()->release();
521 }
522}
523
524sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800525 int32_t x, int32_t y, bool addOutsideTargets, bool addPortalWindows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526 // Traverse windows from front to back to find touched window.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800527 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
528 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529 const InputWindowInfo* windowInfo = windowHandle->getInfo();
530 if (windowInfo->displayId == displayId) {
531 int32_t flags = windowInfo->layoutParamsFlags;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532
533 if (windowInfo->visible) {
534 if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
535 bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
536 | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
537 if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800538 int32_t portalToDisplayId = windowInfo->portalToDisplayId;
539 if (portalToDisplayId != ADISPLAY_ID_NONE
540 && portalToDisplayId != displayId) {
541 if (addPortalWindows) {
542 // For the monitoring channels of the display.
543 mTempTouchState.addPortalWindow(windowHandle);
544 }
545 return findTouchedWindowAtLocked(
546 portalToDisplayId, x, y, addOutsideTargets, addPortalWindows);
547 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548 // Found window.
549 return windowHandle;
550 }
551 }
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800552
553 if (addOutsideTargets && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
554 mTempTouchState.addOrUpdateWindow(
555 windowHandle, InputTarget::FLAG_DISPATCH_AS_OUTSIDE, BitSet32(0));
556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 }
559 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700560 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561}
562
563void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
564 const char* reason;
565 switch (dropReason) {
566 case DROP_REASON_POLICY:
567#if DEBUG_INBOUND_EVENT_DETAILS
568 ALOGD("Dropped event because policy consumed it.");
569#endif
570 reason = "inbound event was dropped because the policy consumed it";
571 break;
572 case DROP_REASON_DISABLED:
Michael Wright3a981722015-06-10 15:26:13 +0100573 if (mLastDropReason != DROP_REASON_DISABLED) {
574 ALOGI("Dropped event because input dispatch is disabled.");
575 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576 reason = "inbound event was dropped because input dispatch is disabled";
577 break;
578 case DROP_REASON_APP_SWITCH:
579 ALOGI("Dropped event because of pending overdue app switch.");
580 reason = "inbound event was dropped because of pending overdue app switch";
581 break;
582 case DROP_REASON_BLOCKED:
583 ALOGI("Dropped event because the current application is not responding and the user "
584 "has started interacting with a different application.");
585 reason = "inbound event was dropped because the current application is not responding "
586 "and the user has started interacting with a different application";
587 break;
588 case DROP_REASON_STALE:
589 ALOGI("Dropped event because it is stale.");
590 reason = "inbound event was dropped because it is stale";
591 break;
592 default:
593 ALOG_ASSERT(false);
594 return;
595 }
596
597 switch (entry->type) {
598 case EventEntry::TYPE_KEY: {
599 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
600 synthesizeCancelationEventsForAllConnectionsLocked(options);
601 break;
602 }
603 case EventEntry::TYPE_MOTION: {
604 MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
605 if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
606 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
607 synthesizeCancelationEventsForAllConnectionsLocked(options);
608 } else {
609 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
610 synthesizeCancelationEventsForAllConnectionsLocked(options);
611 }
612 break;
613 }
614 }
615}
616
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800617static bool isAppSwitchKeyCode(int32_t keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618 return keyCode == AKEYCODE_HOME
619 || keyCode == AKEYCODE_ENDCALL
620 || keyCode == AKEYCODE_APP_SWITCH;
621}
622
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800623bool InputDispatcher::isAppSwitchKeyEvent(KeyEntry* keyEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
625 && isAppSwitchKeyCode(keyEntry->keyCode)
626 && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
627 && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
628}
629
630bool InputDispatcher::isAppSwitchPendingLocked() {
631 return mAppSwitchDueTime != LONG_LONG_MAX;
632}
633
634void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
635 mAppSwitchDueTime = LONG_LONG_MAX;
636
637#if DEBUG_APP_SWITCH
638 if (handled) {
639 ALOGD("App switch has arrived.");
640 } else {
641 ALOGD("App switch was abandoned.");
642 }
643#endif
644}
645
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800646bool InputDispatcher::isStaleEvent(nsecs_t currentTime, EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800647 return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
648}
649
650bool InputDispatcher::haveCommandsLocked() const {
651 return !mCommandQueue.isEmpty();
652}
653
654bool InputDispatcher::runCommandsLockedInterruptible() {
655 if (mCommandQueue.isEmpty()) {
656 return false;
657 }
658
659 do {
660 CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
661
662 Command command = commandEntry->command;
663 (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
664
665 commandEntry->connection.clear();
666 delete commandEntry;
667 } while (! mCommandQueue.isEmpty());
668 return true;
669}
670
671InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
672 CommandEntry* commandEntry = new CommandEntry(command);
673 mCommandQueue.enqueueAtTail(commandEntry);
674 return commandEntry;
675}
676
677void InputDispatcher::drainInboundQueueLocked() {
678 while (! mInboundQueue.isEmpty()) {
679 EventEntry* entry = mInboundQueue.dequeueAtHead();
680 releaseInboundEventLocked(entry);
681 }
682 traceInboundQueueLengthLocked();
683}
684
685void InputDispatcher::releasePendingEventLocked() {
686 if (mPendingEvent) {
687 resetANRTimeoutsLocked();
688 releaseInboundEventLocked(mPendingEvent);
Yi Kong9b14ac62018-07-17 13:48:38 -0700689 mPendingEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 }
691}
692
693void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
694 InjectionState* injectionState = entry->injectionState;
695 if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
696#if DEBUG_DISPATCH_CYCLE
697 ALOGD("Injected inbound event was dropped.");
698#endif
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800699 setInjectionResult(entry, INPUT_EVENT_INJECTION_FAILED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800700 }
701 if (entry == mNextUnblockedEvent) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700702 mNextUnblockedEvent = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800703 }
704 addRecentEventLocked(entry);
705 entry->release();
706}
707
708void InputDispatcher::resetKeyRepeatLocked() {
709 if (mKeyRepeatState.lastKeyEntry) {
710 mKeyRepeatState.lastKeyEntry->release();
Yi Kong9b14ac62018-07-17 13:48:38 -0700711 mKeyRepeatState.lastKeyEntry = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 }
713}
714
715InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
716 KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
717
718 // Reuse the repeated key entry if it is otherwise unreferenced.
Michael Wright2e732952014-09-24 13:26:59 -0700719 uint32_t policyFlags = entry->policyFlags &
720 (POLICY_FLAG_RAW_MASK | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800721 if (entry->refCount == 1) {
722 entry->recycle();
723 entry->eventTime = currentTime;
724 entry->policyFlags = policyFlags;
725 entry->repeatCount += 1;
726 } else {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800727 KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100728 entry->deviceId, entry->source, entry->displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 entry->action, entry->flags, entry->keyCode, entry->scanCode,
730 entry->metaState, entry->repeatCount + 1, entry->downTime);
731
732 mKeyRepeatState.lastKeyEntry = newEntry;
733 entry->release();
734
735 entry = newEntry;
736 }
737 entry->syntheticRepeat = true;
738
739 // Increment reference count since we keep a reference to the event in
740 // mKeyRepeatState.lastKeyEntry in addition to the one we return.
741 entry->refCount += 1;
742
743 mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
744 return entry;
745}
746
747bool InputDispatcher::dispatchConfigurationChangedLocked(
748 nsecs_t currentTime, ConfigurationChangedEntry* entry) {
749#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700750 ALOGD("dispatchConfigurationChanged - eventTime=%" PRId64, entry->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800751#endif
752
753 // Reset key repeating in case a keyboard device was added or removed or something.
754 resetKeyRepeatLocked();
755
756 // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
757 CommandEntry* commandEntry = postCommandLocked(
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800758 & InputDispatcher::doNotifyConfigurationChangedLockedInterruptible);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800759 commandEntry->eventTime = entry->eventTime;
760 return true;
761}
762
763bool InputDispatcher::dispatchDeviceResetLocked(
764 nsecs_t currentTime, DeviceResetEntry* entry) {
765#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700766 ALOGD("dispatchDeviceReset - eventTime=%" PRId64 ", deviceId=%d", entry->eventTime,
767 entry->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768#endif
769
770 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
771 "device was reset");
772 options.deviceId = entry->deviceId;
773 synthesizeCancelationEventsForAllConnectionsLocked(options);
774 return true;
775}
776
777bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
778 DropReason* dropReason, nsecs_t* nextWakeupTime) {
779 // Preprocessing.
780 if (! entry->dispatchInProgress) {
781 if (entry->repeatCount == 0
782 && entry->action == AKEY_EVENT_ACTION_DOWN
783 && (entry->policyFlags & POLICY_FLAG_TRUSTED)
784 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
785 if (mKeyRepeatState.lastKeyEntry
786 && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
787 // We have seen two identical key downs in a row which indicates that the device
788 // driver is automatically generating key repeats itself. We take note of the
789 // repeat here, but we disable our own next key repeat timer since it is clear that
790 // we will not need to synthesize key repeats ourselves.
791 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
792 resetKeyRepeatLocked();
793 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
794 } else {
795 // Not a repeat. Save key down state in case we do see a repeat later.
796 resetKeyRepeatLocked();
797 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
798 }
799 mKeyRepeatState.lastKeyEntry = entry;
800 entry->refCount += 1;
801 } else if (! entry->syntheticRepeat) {
802 resetKeyRepeatLocked();
803 }
804
805 if (entry->repeatCount == 1) {
806 entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
807 } else {
808 entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
809 }
810
811 entry->dispatchInProgress = true;
812
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800813 logOutboundKeyDetails("dispatchKey - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800814 }
815
816 // Handle case where the policy asked us to try again later last time.
817 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
818 if (currentTime < entry->interceptKeyWakeupTime) {
819 if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
820 *nextWakeupTime = entry->interceptKeyWakeupTime;
821 }
822 return false; // wait until next wakeup
823 }
824 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
825 entry->interceptKeyWakeupTime = 0;
826 }
827
828 // Give the policy a chance to intercept the key.
829 if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
830 if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
831 CommandEntry* commandEntry = postCommandLocked(
832 & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
Tiger Huang721e26f2018-07-24 22:26:19 +0800833 sp<InputWindowHandle> focusedWindowHandle =
834 getValueByKey(mFocusedWindowHandlesByDisplay, getTargetDisplayId(entry));
835 if (focusedWindowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -0700836 commandEntry->inputChannel =
837 getInputChannelLocked(focusedWindowHandle->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800838 }
839 commandEntry->keyEntry = entry;
840 entry->refCount += 1;
841 return false; // wait for the command to run
842 } else {
843 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
844 }
845 } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
846 if (*dropReason == DROP_REASON_NOT_DROPPED) {
847 *dropReason = DROP_REASON_POLICY;
848 }
849 }
850
851 // Clean up if dropping the event.
852 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800853 setInjectionResult(entry, *dropReason == DROP_REASON_POLICY
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
Prabir Pradhanf93562f2018-11-29 12:13:37 -0800855 mReporter->reportDroppedKey(entry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 return true;
857 }
858
859 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800860 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
862 entry, inputTargets, nextWakeupTime);
863 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
864 return false;
865 }
866
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800867 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
869 return true;
870 }
871
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800872 // Add monitor channels from event's or focused display.
873 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874
875 // Dispatch the key.
876 dispatchEventLocked(currentTime, entry, inputTargets);
877 return true;
878}
879
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800880void InputDispatcher::logOutboundKeyDetails(const char* prefix, const KeyEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100882 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32 ", "
883 "policyFlags=0x%x, action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +0800884 "metaState=0x%x, repeatCount=%d, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 prefix,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100886 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800888 entry->repeatCount, entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889#endif
890}
891
892bool InputDispatcher::dispatchMotionLocked(
893 nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
894 // Preprocessing.
895 if (! entry->dispatchInProgress) {
896 entry->dispatchInProgress = true;
897
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800898 logOutboundMotionDetails("dispatchMotion - ", entry);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 }
900
901 // Clean up if dropping the event.
902 if (*dropReason != DROP_REASON_NOT_DROPPED) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800903 setInjectionResult(entry, *dropReason == DROP_REASON_POLICY
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
905 return true;
906 }
907
908 bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
909
910 // Identify targets.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800911 std::vector<InputTarget> inputTargets;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912
913 bool conflictingPointerActions = false;
914 int32_t injectionResult;
915 if (isPointerEvent) {
916 // Pointer event. (eg. touchscreen)
917 injectionResult = findTouchedWindowTargetsLocked(currentTime,
918 entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
919 } else {
920 // Non touch event. (eg. trackball)
921 injectionResult = findFocusedWindowTargetsLocked(currentTime,
922 entry, inputTargets, nextWakeupTime);
923 }
924 if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
925 return false;
926 }
927
Siarhei Vishniakou62683e82019-03-06 17:59:56 -0800928 setInjectionResult(entry, injectionResult);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100930 if (injectionResult != INPUT_EVENT_INJECTION_PERMISSION_DENIED) {
931 CancelationOptions::Mode mode(isPointerEvent ?
932 CancelationOptions::CANCEL_POINTER_EVENTS :
933 CancelationOptions::CANCEL_NON_POINTER_EVENTS);
934 CancelationOptions options(mode, "input event injection failed");
935 synthesizeCancelationEventsForMonitorsLocked(options);
936 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937 return true;
938 }
939
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800940 // Add monitor channels from event's or focused display.
941 addMonitoringTargetsLocked(inputTargets, getTargetDisplayId(entry));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800943 if (isPointerEvent) {
944 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(entry->displayId);
945 if (stateIndex >= 0) {
946 const TouchState& state = mTouchStatesByDisplay.valueAt(stateIndex);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800947 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800948 // The event has gone through these portal windows, so we add monitoring targets of
949 // the corresponding displays as well.
950 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800951 const InputWindowInfo* windowInfo = state.portalWindows[i]->getInfo();
Tiger Huang85b8c5e2019-01-17 18:34:54 +0800952 addMonitoringTargetsLocked(inputTargets, windowInfo->portalToDisplayId,
953 -windowInfo->frameLeft, -windowInfo->frameTop);
954 }
955 }
956 }
957 }
958
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959 // Dispatch the motion.
960 if (conflictingPointerActions) {
961 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
962 "conflicting pointer actions");
963 synthesizeCancelationEventsForAllConnectionsLocked(options);
964 }
965 dispatchEventLocked(currentTime, entry, inputTargets);
966 return true;
967}
968
969
Siarhei Vishniakou61291d42019-02-11 18:13:20 -0800970void InputDispatcher::logOutboundMotionDetails(const char* prefix, const MotionEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800972 ALOGD("%seventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
973 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +0100974 "action=0x%x, actionButton=0x%x, flags=0x%x, "
975 "metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +0800976 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 prefix,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800978 entry->eventTime, entry->deviceId, entry->source, entry->displayId, entry->policyFlags,
Michael Wrightfa13dcf2015-06-12 13:25:11 +0100979 entry->action, entry->actionButton, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980 entry->metaState, entry->buttonState,
981 entry->edgeFlags, entry->xPrecision, entry->yPrecision,
Arthur Hung82a4cad2018-11-15 12:10:30 +0800982 entry->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983
984 for (uint32_t i = 0; i < entry->pointerCount; i++) {
985 ALOGD(" Pointer %d: id=%d, toolType=%d, "
986 "x=%f, y=%f, pressure=%f, size=%f, "
987 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800988 "orientation=%f",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 i, entry->pointerProperties[i].id,
990 entry->pointerProperties[i].toolType,
991 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
992 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
993 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
994 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
995 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
996 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
997 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
998 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -0800999 entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001000 }
1001#endif
1002}
1003
1004void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001005 EventEntry* eventEntry, const std::vector<InputTarget>& inputTargets) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006#if DEBUG_DISPATCH_CYCLE
1007 ALOGD("dispatchEventToCurrentInputTargets");
1008#endif
1009
1010 ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
1011
1012 pokeUserActivityLocked(eventEntry);
1013
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001014 for (const InputTarget& inputTarget : inputTargets) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001015 ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
1016 if (connectionIndex >= 0) {
1017 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1018 prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
1019 } else {
1020#if DEBUG_FOCUS
1021 ALOGD("Dropping event delivery to target with channel '%s' because it "
1022 "is no longer registered with the input dispatcher.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001023 inputTarget.inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024#endif
1025 }
1026 }
1027}
1028
1029int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
1030 const EventEntry* entry,
1031 const sp<InputApplicationHandle>& applicationHandle,
1032 const sp<InputWindowHandle>& windowHandle,
1033 nsecs_t* nextWakeupTime, const char* reason) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001034 if (applicationHandle == nullptr && windowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
1036#if DEBUG_FOCUS
1037 ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
1038#endif
1039 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
1040 mInputTargetWaitStartTime = currentTime;
1041 mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
1042 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001043 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001044 }
1045 } else {
1046 if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1047#if DEBUG_FOCUS
1048 ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001049 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 reason);
1051#endif
1052 nsecs_t timeout;
Yi Kong9b14ac62018-07-17 13:48:38 -07001053 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
Yi Kong9b14ac62018-07-17 13:48:38 -07001055 } else if (applicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 timeout = applicationHandle->getDispatchingTimeout(
1057 DEFAULT_INPUT_DISPATCHING_TIMEOUT);
1058 } else {
1059 timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
1060 }
1061
1062 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
1063 mInputTargetWaitStartTime = currentTime;
1064 mInputTargetWaitTimeoutTime = currentTime + timeout;
1065 mInputTargetWaitTimeoutExpired = false;
Robert Carr740167f2018-10-11 19:03:41 -07001066 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067
Yi Kong9b14ac62018-07-17 13:48:38 -07001068 if (windowHandle != nullptr) {
Robert Carr740167f2018-10-11 19:03:41 -07001069 mInputTargetWaitApplicationToken = windowHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001070 }
Robert Carr740167f2018-10-11 19:03:41 -07001071 if (mInputTargetWaitApplicationToken == nullptr && applicationHandle != nullptr) {
1072 mInputTargetWaitApplicationToken = applicationHandle->getApplicationToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001073 }
1074 }
1075 }
1076
1077 if (mInputTargetWaitTimeoutExpired) {
1078 return INPUT_EVENT_INJECTION_TIMED_OUT;
1079 }
1080
1081 if (currentTime >= mInputTargetWaitTimeoutTime) {
1082 onANRLocked(currentTime, applicationHandle, windowHandle,
1083 entry->eventTime, mInputTargetWaitStartTime, reason);
1084
1085 // Force poll loop to wake up immediately on next iteration once we get the
1086 // ANR response back from the policy.
1087 *nextWakeupTime = LONG_LONG_MIN;
1088 return INPUT_EVENT_INJECTION_PENDING;
1089 } else {
1090 // Force poll loop to wake up when timeout is due.
1091 if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
1092 *nextWakeupTime = mInputTargetWaitTimeoutTime;
1093 }
1094 return INPUT_EVENT_INJECTION_PENDING;
1095 }
1096}
1097
Robert Carr803535b2018-08-02 16:38:15 -07001098void InputDispatcher::removeWindowByTokenLocked(const sp<IBinder>& token) {
1099 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
1100 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
1101 state.removeWindowByToken(token);
1102 }
1103}
1104
Michael Wrightd02c5b62014-02-10 15:10:22 -08001105void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
1106 const sp<InputChannel>& inputChannel) {
1107 if (newTimeout > 0) {
1108 // Extend the timeout.
1109 mInputTargetWaitTimeoutTime = now() + newTimeout;
1110 } else {
1111 // Give up.
1112 mInputTargetWaitTimeoutExpired = true;
1113
1114 // Input state will not be realistic. Mark it out of sync.
1115 if (inputChannel.get()) {
1116 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
1117 if (connectionIndex >= 0) {
1118 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
Robert Carr803535b2018-08-02 16:38:15 -07001119 sp<IBinder> token = connection->inputChannel->getToken();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120
Robert Carr803535b2018-08-02 16:38:15 -07001121 if (token != nullptr) {
1122 removeWindowByTokenLocked(token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001123 }
1124
1125 if (connection->status == Connection::STATUS_NORMAL) {
1126 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
1127 "application not responding");
1128 synthesizeCancelationEventsForConnectionLocked(connection, options);
1129 }
1130 }
1131 }
1132 }
1133}
1134
1135nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
1136 nsecs_t currentTime) {
1137 if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
1138 return currentTime - mInputTargetWaitStartTime;
1139 }
1140 return 0;
1141}
1142
1143void InputDispatcher::resetANRTimeoutsLocked() {
1144#if DEBUG_FOCUS
1145 ALOGD("Resetting ANR timeouts.");
1146#endif
1147
1148 // Reset input target wait timeout.
1149 mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
Robert Carr740167f2018-10-11 19:03:41 -07001150 mInputTargetWaitApplicationToken.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151}
1152
Tiger Huang721e26f2018-07-24 22:26:19 +08001153/**
1154 * Get the display id that the given event should go to. If this event specifies a valid display id,
1155 * then it should be dispatched to that display. Otherwise, the event goes to the focused display.
1156 * Focused display is the display that the user most recently interacted with.
1157 */
1158int32_t InputDispatcher::getTargetDisplayId(const EventEntry* entry) {
1159 int32_t displayId;
1160 switch (entry->type) {
1161 case EventEntry::TYPE_KEY: {
1162 const KeyEntry* typedEntry = static_cast<const KeyEntry*>(entry);
1163 displayId = typedEntry->displayId;
1164 break;
1165 }
1166 case EventEntry::TYPE_MOTION: {
1167 const MotionEntry* typedEntry = static_cast<const MotionEntry*>(entry);
1168 displayId = typedEntry->displayId;
1169 break;
1170 }
1171 default: {
1172 ALOGE("Unsupported event type '%" PRId32 "' for target display.", entry->type);
1173 return ADISPLAY_ID_NONE;
1174 }
1175 }
1176 return displayId == ADISPLAY_ID_NONE ? mFocusedDisplayId : displayId;
1177}
1178
Michael Wrightd02c5b62014-02-10 15:10:22 -08001179int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001180 const EventEntry* entry, std::vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 int32_t injectionResult;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001182 std::string reason;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183
Tiger Huang721e26f2018-07-24 22:26:19 +08001184 int32_t displayId = getTargetDisplayId(entry);
1185 sp<InputWindowHandle> focusedWindowHandle =
1186 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1187 sp<InputApplicationHandle> focusedApplicationHandle =
1188 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
1189
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 // If there is no currently focused window and no focused application
1191 // then drop the event.
Tiger Huang721e26f2018-07-24 22:26:19 +08001192 if (focusedWindowHandle == nullptr) {
1193 if (focusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001195 focusedApplicationHandle, nullptr, nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001196 "Waiting because no window has focus but there is a "
1197 "focused application that may eventually add a window "
1198 "when it finishes starting up.");
1199 goto Unresponsive;
1200 }
1201
Arthur Hung3b413f22018-10-26 18:05:34 +08001202 ALOGI("Dropping event because there is no focused window or focused application in display "
1203 "%" PRId32 ".", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1205 goto Failed;
1206 }
1207
1208 // Check permissions.
Tiger Huang721e26f2018-07-24 22:26:19 +08001209 if (!checkInjectionPermission(focusedWindowHandle, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1211 goto Failed;
1212 }
1213
Jeff Brownffb49772014-10-10 19:01:34 -07001214 // Check whether the window is ready for more input.
1215 reason = checkWindowReadyForMoreInputLocked(currentTime,
Tiger Huang721e26f2018-07-24 22:26:19 +08001216 focusedWindowHandle, entry, "focused");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001217 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Tiger Huang721e26f2018-07-24 22:26:19 +08001219 focusedApplicationHandle, focusedWindowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 goto Unresponsive;
1221 }
1222
1223 // Success! Output targets.
1224 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
Tiger Huang721e26f2018-07-24 22:26:19 +08001225 addWindowTargetLocked(focusedWindowHandle,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001226 InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
1227 inputTargets);
1228
1229 // Done.
1230Failed:
1231Unresponsive:
1232 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001233 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234#if DEBUG_FOCUS
1235 ALOGD("findFocusedWindow finished: injectionResult=%d, "
1236 "timeSpentWaitingForApplication=%0.1fms",
1237 injectionResult, timeSpentWaitingForApplication / 1000000.0);
1238#endif
1239 return injectionResult;
1240}
1241
1242int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001243 const MotionEntry* entry, std::vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 bool* outConflictingPointerActions) {
1245 enum InjectionPermission {
1246 INJECTION_PERMISSION_UNKNOWN,
1247 INJECTION_PERMISSION_GRANTED,
1248 INJECTION_PERMISSION_DENIED
1249 };
1250
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 // For security reasons, we defer updating the touch state until we are sure that
1252 // event injection will be allowed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 int32_t displayId = entry->displayId;
1254 int32_t action = entry->action;
1255 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
1256
1257 // Update the touch state as needed based on the properties of the touch event.
1258 int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
1259 InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
1260 sp<InputWindowHandle> newHoverWindowHandle;
1261
Jeff Brownf086ddb2014-02-11 14:28:48 -08001262 // Copy current touch state into mTempTouchState.
1263 // This state is always reset at the end of this function, so if we don't find state
1264 // for the specified display then our initial state will be empty.
Yi Kong9b14ac62018-07-17 13:48:38 -07001265 const TouchState* oldState = nullptr;
Jeff Brownf086ddb2014-02-11 14:28:48 -08001266 ssize_t oldStateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
1267 if (oldStateIndex >= 0) {
1268 oldState = &mTouchStatesByDisplay.valueAt(oldStateIndex);
1269 mTempTouchState.copyFrom(*oldState);
1270 }
1271
1272 bool isSplit = mTempTouchState.split;
1273 bool switchedDevice = mTempTouchState.deviceId >= 0 && mTempTouchState.displayId >= 0
1274 && (mTempTouchState.deviceId != entry->deviceId
1275 || mTempTouchState.source != entry->source
1276 || mTempTouchState.displayId != displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001277 bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
1278 || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1279 || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
1280 bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
1281 || maskedAction == AMOTION_EVENT_ACTION_SCROLL
1282 || isHoverAction);
1283 bool wrongDevice = false;
1284 if (newGesture) {
1285 bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001286 if (switchedDevice && mTempTouchState.down && !down && !isHoverAction) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001288 ALOGD("Dropping event because a pointer for a different device is already down "
1289 "in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290#endif
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001291 // TODO: test multiple simultaneous input streams.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001292 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1293 switchedDevice = false;
1294 wrongDevice = true;
1295 goto Failed;
1296 }
1297 mTempTouchState.reset();
1298 mTempTouchState.down = down;
1299 mTempTouchState.deviceId = entry->deviceId;
1300 mTempTouchState.source = entry->source;
1301 mTempTouchState.displayId = displayId;
1302 isSplit = false;
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001303 } else if (switchedDevice && maskedAction == AMOTION_EVENT_ACTION_MOVE) {
1304#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001305 ALOGI("Dropping move event because a pointer for a different device is already active "
1306 "in display %" PRId32, displayId);
Kevin Schoedel1eb587b2017-05-03 13:58:56 -04001307#endif
1308 // TODO: test multiple simultaneous input streams.
1309 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1310 switchedDevice = false;
1311 wrongDevice = true;
1312 goto Failed;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313 }
1314
1315 if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
1316 /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
1317
1318 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1319 int32_t x = int32_t(entry->pointerCoords[pointerIndex].
1320 getAxisValue(AMOTION_EVENT_AXIS_X));
1321 int32_t y = int32_t(entry->pointerCoords[pointerIndex].
1322 getAxisValue(AMOTION_EVENT_AXIS_Y));
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001323 sp<InputWindowHandle> newTouchedWindowHandle = findTouchedWindowAtLocked(
1324 displayId, x, y, maskedAction == AMOTION_EVENT_ACTION_DOWN, true);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325
Michael Wrightd02c5b62014-02-10 15:10:22 -08001326 // Figure out whether splitting will be allowed for this window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001327 if (newTouchedWindowHandle != nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1329 // New window supports splitting.
1330 isSplit = true;
1331 } else if (isSplit) {
1332 // New window does not support splitting but we have already split events.
1333 // Ignore the new window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001334 newTouchedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335 }
1336
1337 // Handle the case where we did not find a window.
Yi Kong9b14ac62018-07-17 13:48:38 -07001338 if (newTouchedWindowHandle == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001339 // Try to assign the pointer to the first foreground window we find, if there is one.
1340 newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
Yi Kong9b14ac62018-07-17 13:48:38 -07001341 if (newTouchedWindowHandle == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08001342 ALOGI("Dropping event because there is no touchable window at (%d, %d) in display "
1343 "%" PRId32 ".", x, y, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001344 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1345 goto Failed;
1346 }
1347 }
1348
1349 // Set target flags.
1350 int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
1351 if (isSplit) {
1352 targetFlags |= InputTarget::FLAG_SPLIT;
1353 }
1354 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1355 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001356 } else if (isWindowObscuredLocked(newTouchedWindowHandle)) {
1357 targetFlags |= InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 }
1359
1360 // Update hover state.
1361 if (isHoverAction) {
1362 newHoverWindowHandle = newTouchedWindowHandle;
1363 } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
1364 newHoverWindowHandle = mLastHoverWindowHandle;
1365 }
1366
1367 // Update the temporary touch state.
1368 BitSet32 pointerIds;
1369 if (isSplit) {
1370 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1371 pointerIds.markBit(pointerId);
1372 }
1373 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1374 } else {
1375 /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
1376
1377 // If the pointer is not currently down, then ignore the event.
1378 if (! mTempTouchState.down) {
1379#if DEBUG_FOCUS
1380 ALOGD("Dropping event because the pointer is not down or we previously "
Arthur Hung3b413f22018-10-26 18:05:34 +08001381 "dropped the pointer down event in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001382#endif
1383 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1384 goto Failed;
1385 }
1386
1387 // Check whether touches should slip outside of the current foreground window.
1388 if (maskedAction == AMOTION_EVENT_ACTION_MOVE
1389 && entry->pointerCount == 1
1390 && mTempTouchState.isSlippery()) {
1391 int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
1392 int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
1393
1394 sp<InputWindowHandle> oldTouchedWindowHandle =
1395 mTempTouchState.getFirstForegroundWindowHandle();
1396 sp<InputWindowHandle> newTouchedWindowHandle =
1397 findTouchedWindowAtLocked(displayId, x, y);
1398 if (oldTouchedWindowHandle != newTouchedWindowHandle
Yi Kong9b14ac62018-07-17 13:48:38 -07001399 && newTouchedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001401 ALOGD("Touch is slipping out of window %s into window %s in display %" PRId32,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001402 oldTouchedWindowHandle->getName().c_str(),
Arthur Hung3b413f22018-10-26 18:05:34 +08001403 newTouchedWindowHandle->getName().c_str(),
1404 displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405#endif
1406 // Make a slippery exit from the old window.
1407 mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
1408 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
1409
1410 // Make a slippery entrance into the new window.
1411 if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
1412 isSplit = true;
1413 }
1414
1415 int32_t targetFlags = InputTarget::FLAG_FOREGROUND
1416 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
1417 if (isSplit) {
1418 targetFlags |= InputTarget::FLAG_SPLIT;
1419 }
1420 if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
1421 targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
1422 }
1423
1424 BitSet32 pointerIds;
1425 if (isSplit) {
1426 pointerIds.markBit(entry->pointerProperties[0].id);
1427 }
1428 mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
1429 }
1430 }
1431 }
1432
1433 if (newHoverWindowHandle != mLastHoverWindowHandle) {
1434 // Let the previous window know that the hover sequence is over.
Yi Kong9b14ac62018-07-17 13:48:38 -07001435 if (mLastHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001436#if DEBUG_HOVER
1437 ALOGD("Sending hover exit event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001438 mLastHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001439#endif
1440 mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
1441 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
1442 }
1443
1444 // Let the new window know that the hover sequence is starting.
Yi Kong9b14ac62018-07-17 13:48:38 -07001445 if (newHoverWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446#if DEBUG_HOVER
1447 ALOGD("Sending hover enter event to window %s.",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001448 newHoverWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449#endif
1450 mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
1451 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
1452 }
1453 }
1454
1455 // Check permission to inject into all touched foreground windows and ensure there
1456 // is at least one touched foreground window.
1457 {
1458 bool haveForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001459 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001460 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
1461 haveForegroundWindow = true;
1462 if (! checkInjectionPermission(touchedWindow.windowHandle,
1463 entry->injectionState)) {
1464 injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
1465 injectionPermission = INJECTION_PERMISSION_DENIED;
1466 goto Failed;
1467 }
1468 }
1469 }
1470 if (! haveForegroundWindow) {
1471#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08001472 ALOGD("Dropping event because there is no touched foreground window in display %" PRId32
1473 " to receive it.", displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474#endif
1475 injectionResult = INPUT_EVENT_INJECTION_FAILED;
1476 goto Failed;
1477 }
1478
1479 // Permission granted to injection into all touched foreground windows.
1480 injectionPermission = INJECTION_PERMISSION_GRANTED;
1481 }
1482
1483 // Check whether windows listening for outside touches are owned by the same UID. If it is
1484 // set the policy flag that we will not reveal coordinate information to this window.
1485 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1486 sp<InputWindowHandle> foregroundWindowHandle =
1487 mTempTouchState.getFirstForegroundWindowHandle();
1488 const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001489 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
1491 sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
1492 if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
1493 mTempTouchState.addOrUpdateWindow(inputWindowHandle,
1494 InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
1495 }
1496 }
1497 }
1498 }
1499
1500 // Ensure all touched foreground windows are ready for new input.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001501 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
Jeff Brownffb49772014-10-10 19:01:34 -07001503 // Check whether the window is ready for more input.
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001504 std::string reason = checkWindowReadyForMoreInputLocked(currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001505 touchedWindow.windowHandle, entry, "touched");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001506 if (!reason.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001507 injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
Yi Kong9b14ac62018-07-17 13:48:38 -07001508 nullptr, touchedWindow.windowHandle, nextWakeupTime, reason.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 goto Unresponsive;
1510 }
1511 }
1512 }
1513
1514 // If this is the first pointer going down and the touched window has a wallpaper
1515 // then also add the touched wallpaper windows so they are locked in for the duration
1516 // of the touch gesture.
1517 // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
1518 // engine only supports touch events. We would need to add a mechanism similar
1519 // to View.onGenericMotionEvent to enable wallpapers to handle these events.
1520 if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1521 sp<InputWindowHandle> foregroundWindowHandle =
1522 mTempTouchState.getFirstForegroundWindowHandle();
1523 if (foregroundWindowHandle->getInfo()->hasWallpaper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001524 const std::vector<sp<InputWindowHandle>> windowHandles =
1525 getWindowHandlesLocked(displayId);
1526 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001527 const InputWindowInfo* info = windowHandle->getInfo();
1528 if (info->displayId == displayId
1529 && windowHandle->getInfo()->layoutParamsType
1530 == InputWindowInfo::TYPE_WALLPAPER) {
1531 mTempTouchState.addOrUpdateWindow(windowHandle,
1532 InputTarget::FLAG_WINDOW_IS_OBSCURED
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001533 | InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 | InputTarget::FLAG_DISPATCH_AS_IS,
1535 BitSet32(0));
1536 }
1537 }
1538 }
1539 }
1540
1541 // Success! Output targets.
1542 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
1543
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001544 for (const TouchedWindow& touchedWindow : mTempTouchState.windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
1546 touchedWindow.pointerIds, inputTargets);
1547 }
1548
1549 // Drop the outside or hover touch windows since we will not care about them
1550 // in the next iteration.
1551 mTempTouchState.filterNonAsIsTouchWindows();
1552
1553Failed:
1554 // Check injection permission once and for all.
1555 if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001556 if (checkInjectionPermission(nullptr, entry->injectionState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 injectionPermission = INJECTION_PERMISSION_GRANTED;
1558 } else {
1559 injectionPermission = INJECTION_PERMISSION_DENIED;
1560 }
1561 }
1562
1563 // Update final pieces of touch state if the injector had permission.
1564 if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
1565 if (!wrongDevice) {
1566 if (switchedDevice) {
1567#if DEBUG_FOCUS
1568 ALOGD("Conflicting pointer actions: Switched to a different device.");
1569#endif
1570 *outConflictingPointerActions = true;
1571 }
1572
1573 if (isHoverAction) {
1574 // Started hovering, therefore no longer down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001575 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576#if DEBUG_FOCUS
1577 ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
1578#endif
1579 *outConflictingPointerActions = true;
1580 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001581 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582 if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
1583 || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08001584 mTempTouchState.deviceId = entry->deviceId;
1585 mTempTouchState.source = entry->source;
1586 mTempTouchState.displayId = displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 }
1588 } else if (maskedAction == AMOTION_EVENT_ACTION_UP
1589 || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
1590 // All pointers up or canceled.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001591 mTempTouchState.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
1593 // First pointer went down.
Jeff Brownf086ddb2014-02-11 14:28:48 -08001594 if (oldState && oldState->down) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001595#if DEBUG_FOCUS
1596 ALOGD("Conflicting pointer actions: Down received while already down.");
1597#endif
1598 *outConflictingPointerActions = true;
1599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
1601 // One pointer went up.
1602 if (isSplit) {
1603 int32_t pointerIndex = getMotionEventActionPointerIndex(action);
1604 uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
1605
1606 for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001607 TouchedWindow& touchedWindow = mTempTouchState.windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001608 if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
1609 touchedWindow.pointerIds.clearBit(pointerId);
1610 if (touchedWindow.pointerIds.isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001611 mTempTouchState.windows.erase(mTempTouchState.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612 continue;
1613 }
1614 }
1615 i += 1;
1616 }
1617 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08001618 }
1619
1620 // Save changes unless the action was scroll in which case the temporary touch
1621 // state was only valid for this one action.
1622 if (maskedAction != AMOTION_EVENT_ACTION_SCROLL) {
1623 if (mTempTouchState.displayId >= 0) {
1624 if (oldStateIndex >= 0) {
1625 mTouchStatesByDisplay.editValueAt(oldStateIndex).copyFrom(mTempTouchState);
1626 } else {
1627 mTouchStatesByDisplay.add(displayId, mTempTouchState);
1628 }
1629 } else if (oldStateIndex >= 0) {
1630 mTouchStatesByDisplay.removeItemsAt(oldStateIndex);
1631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632 }
1633
1634 // Update hover state.
1635 mLastHoverWindowHandle = newHoverWindowHandle;
1636 }
1637 } else {
1638#if DEBUG_FOCUS
1639 ALOGD("Not updating touch focus because injection was denied.");
1640#endif
1641 }
1642
1643Unresponsive:
1644 // Reset temporary touch state to ensure we release unnecessary references to input channels.
1645 mTempTouchState.reset();
1646
1647 nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001648 updateDispatchStatistics(currentTime, entry, injectionResult, timeSpentWaitingForApplication);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649#if DEBUG_FOCUS
1650 ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
1651 "timeSpentWaitingForApplication=%0.1fms",
1652 injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
1653#endif
1654 return injectionResult;
1655}
1656
1657void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001658 int32_t targetFlags, BitSet32 pointerIds, std::vector<InputTarget>& inputTargets) {
Arthur Hungceeb5d72018-12-05 16:14:18 +08001659 sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
1660 if (inputChannel == nullptr) {
1661 ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
1662 return;
1663 }
1664
Michael Wrightd02c5b62014-02-10 15:10:22 -08001665 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001666 InputTarget target;
Arthur Hungceeb5d72018-12-05 16:14:18 +08001667 target.inputChannel = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 target.flags = targetFlags;
1669 target.xOffset = - windowInfo->frameLeft;
1670 target.yOffset = - windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08001671 target.globalScaleFactor = windowInfo->globalScaleFactor;
1672 target.windowXScale = windowInfo->windowXScale;
1673 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 target.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001675 inputTargets.push_back(target);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676}
1677
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001678void InputDispatcher::addMonitoringTargetsLocked(std::vector<InputTarget>& inputTargets,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001679 int32_t displayId, float xOffset, float yOffset) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001680 std::unordered_map<int32_t, std::vector<sp<InputChannel>>>::const_iterator it =
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001681 mMonitoringChannelsByDisplay.find(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001683 if (it != mMonitoringChannelsByDisplay.end()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001684 const std::vector<sp<InputChannel>>& monitoringChannels = it->second;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001685 const size_t numChannels = monitoringChannels.size();
1686 for (size_t i = 0; i < numChannels; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001687 InputTarget target;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001688 target.inputChannel = monitoringChannels[i];
1689 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08001690 target.xOffset = xOffset;
1691 target.yOffset = yOffset;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001692 target.pointerIds.clear();
Robert Carre07e1032018-11-26 12:55:53 -08001693 target.globalScaleFactor = 1.0f;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001694 inputTargets.push_back(target);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001695 }
1696 } else {
1697 // If there is no monitor channel registered or all monitor channel unregistered,
1698 // the display can't detect the extra system gesture by a copy of input events.
Arthur Hung3b413f22018-10-26 18:05:34 +08001699 ALOGW("There is no monitor channel found in display %" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001700 }
1701}
1702
1703bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
1704 const InjectionState* injectionState) {
1705 if (injectionState
Yi Kong9b14ac62018-07-17 13:48:38 -07001706 && (windowHandle == nullptr
Michael Wrightd02c5b62014-02-10 15:10:22 -08001707 || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
1708 && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001709 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001710 ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
1711 "owned by uid %d",
1712 injectionState->injectorPid, injectionState->injectorUid,
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001713 windowHandle->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001714 windowHandle->getInfo()->ownerUid);
1715 } else {
1716 ALOGW("Permission denied: injecting event from pid %d uid %d",
1717 injectionState->injectorPid, injectionState->injectorUid);
1718 }
1719 return false;
1720 }
1721 return true;
1722}
1723
1724bool InputDispatcher::isWindowObscuredAtPointLocked(
1725 const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
1726 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001727 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
1728 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 if (otherHandle == windowHandle) {
1730 break;
1731 }
1732
1733 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1734 if (otherInfo->displayId == displayId
1735 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1736 && otherInfo->frameContainsPoint(x, y)) {
1737 return true;
1738 }
1739 }
1740 return false;
1741}
1742
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001743
1744bool InputDispatcher::isWindowObscuredLocked(const sp<InputWindowHandle>& windowHandle) const {
1745 int32_t displayId = windowHandle->getInfo()->displayId;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001746 const std::vector<sp<InputWindowHandle>> windowHandles = getWindowHandlesLocked(displayId);
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001747 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001748 for (const sp<InputWindowHandle>& otherHandle : windowHandles) {
Michael Wrightcdcd8f22016-03-22 16:52:13 -07001749 if (otherHandle == windowHandle) {
1750 break;
1751 }
1752
1753 const InputWindowInfo* otherInfo = otherHandle->getInfo();
1754 if (otherInfo->displayId == displayId
1755 && otherInfo->visible && !otherInfo->isTrustedOverlay()
1756 && otherInfo->overlaps(windowInfo)) {
1757 return true;
1758 }
1759 }
1760 return false;
1761}
1762
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001763std::string InputDispatcher::checkWindowReadyForMoreInputLocked(nsecs_t currentTime,
Jeff Brownffb49772014-10-10 19:01:34 -07001764 const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry,
1765 const char* targetType) {
1766 // If the window is paused then keep waiting.
1767 if (windowHandle->getInfo()->paused) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001768 return StringPrintf("Waiting because the %s window is paused.", targetType);
Jeff Brownffb49772014-10-10 19:01:34 -07001769 }
1770
1771 // If the window's connection is not registered then keep waiting.
Robert Carr5c8a0262018-10-03 16:30:44 -07001772 ssize_t connectionIndex = getConnectionIndexLocked(
1773 getInputChannelLocked(windowHandle->getToken()));
Jeff Brownffb49772014-10-10 19:01:34 -07001774 if (connectionIndex < 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001775 return StringPrintf("Waiting because the %s window's input channel is not "
Jeff Brownffb49772014-10-10 19:01:34 -07001776 "registered with the input dispatcher. The window may be in the process "
1777 "of being removed.", targetType);
1778 }
1779
1780 // If the connection is dead then keep waiting.
1781 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
1782 if (connection->status != Connection::STATUS_NORMAL) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001783 return StringPrintf("Waiting because the %s window's input connection is %s."
Jeff Brownffb49772014-10-10 19:01:34 -07001784 "The window may be in the process of being removed.", targetType,
1785 connection->getStatusLabel());
1786 }
1787
1788 // If the connection is backed up then keep waiting.
1789 if (connection->inputPublisherBlocked) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001790 return StringPrintf("Waiting because the %s window's input channel is full. "
Jeff Brownffb49772014-10-10 19:01:34 -07001791 "Outbound queue length: %d. Wait queue length: %d.",
1792 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
1793 }
1794
1795 // Ensure that the dispatch queues aren't too far backed up for this event.
1796 if (eventEntry->type == EventEntry::TYPE_KEY) {
1797 // If the event is a key event, then we must wait for all previous events to
1798 // complete before delivering it because previous events may have the
1799 // side-effect of transferring focus to a different window and we want to
1800 // ensure that the following keys are sent to the new window.
1801 //
1802 // Suppose the user touches a button in a window then immediately presses "A".
1803 // If the button causes a pop-up window to appear then we want to ensure that
1804 // the "A" key is delivered to the new pop-up window. This is because users
1805 // often anticipate pending UI changes when typing on a keyboard.
1806 // To obtain this behavior, we must serialize key events with respect to all
1807 // prior input events.
1808 if (!connection->outboundQueue.isEmpty() || !connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001809 return StringPrintf("Waiting to send key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001810 "finished processing all of the input events that were previously "
1811 "delivered to it. Outbound queue length: %d. Wait queue length: %d.",
1812 targetType, connection->outboundQueue.count(), connection->waitQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 }
Jeff Brownffb49772014-10-10 19:01:34 -07001814 } else {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001815 // Touch events can always be sent to a window immediately because the user intended
1816 // to touch whatever was visible at the time. Even if focus changes or a new
1817 // window appears moments later, the touch event was meant to be delivered to
1818 // whatever window happened to be on screen at the time.
1819 //
1820 // Generic motion events, such as trackball or joystick events are a little trickier.
1821 // Like key events, generic motion events are delivered to the focused window.
1822 // Unlike key events, generic motion events don't tend to transfer focus to other
1823 // windows and it is not important for them to be serialized. So we prefer to deliver
1824 // generic motion events as soon as possible to improve efficiency and reduce lag
1825 // through batching.
1826 //
1827 // The one case where we pause input event delivery is when the wait queue is piling
1828 // up with lots of events because the application is not responding.
1829 // This condition ensures that ANRs are detected reliably.
1830 if (!connection->waitQueue.isEmpty()
1831 && currentTime >= connection->waitQueue.head->deliveryTime
1832 + STREAM_AHEAD_EVENT_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001833 return StringPrintf("Waiting to send non-key event because the %s window has not "
Jeff Brownffb49772014-10-10 19:01:34 -07001834 "finished processing certain input events that were delivered to it over "
1835 "%0.1fms ago. Wait queue length: %d. Wait queue head age: %0.1fms.",
1836 targetType, STREAM_AHEAD_EVENT_TIMEOUT * 0.000001f,
1837 connection->waitQueue.count(),
1838 (currentTime - connection->waitQueue.head->deliveryTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 }
1840 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001841 return "";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842}
1843
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001844std::string InputDispatcher::getApplicationWindowLabel(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 const sp<InputApplicationHandle>& applicationHandle,
1846 const sp<InputWindowHandle>& windowHandle) {
Yi Kong9b14ac62018-07-17 13:48:38 -07001847 if (applicationHandle != nullptr) {
1848 if (windowHandle != nullptr) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001849 std::string label(applicationHandle->getName());
1850 label += " - ";
1851 label += windowHandle->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 return label;
1853 } else {
1854 return applicationHandle->getName();
1855 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001856 } else if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001857 return windowHandle->getName();
1858 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001859 return "<unknown application or window>";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 }
1861}
1862
1863void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
Tiger Huang721e26f2018-07-24 22:26:19 +08001864 int32_t displayId = getTargetDisplayId(eventEntry);
1865 sp<InputWindowHandle> focusedWindowHandle =
1866 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
1867 if (focusedWindowHandle != nullptr) {
1868 const InputWindowInfo* info = focusedWindowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001869 if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
1870#if DEBUG_DISPATCH_CYCLE
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001871 ALOGD("Not poking user activity: disabled by window '%s'.", info->name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872#endif
1873 return;
1874 }
1875 }
1876
1877 int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
1878 switch (eventEntry->type) {
1879 case EventEntry::TYPE_MOTION: {
1880 const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
1881 if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
1882 return;
1883 }
1884
1885 if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
1886 eventType = USER_ACTIVITY_EVENT_TOUCH;
1887 }
1888 break;
1889 }
1890 case EventEntry::TYPE_KEY: {
1891 const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
1892 if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
1893 return;
1894 }
1895 eventType = USER_ACTIVITY_EVENT_BUTTON;
1896 break;
1897 }
1898 }
1899
1900 CommandEntry* commandEntry = postCommandLocked(
1901 & InputDispatcher::doPokeUserActivityLockedInterruptible);
1902 commandEntry->eventTime = eventEntry->eventTime;
1903 commandEntry->userActivityEventType = eventType;
1904}
1905
1906void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
1907 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1908#if DEBUG_DISPATCH_CYCLE
1909 ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
Robert Carre07e1032018-11-26 12:55:53 -08001910 "xOffset=%f, yOffset=%f, globalScaleFactor=%f, "
1911 "windowScaleFactor=(%f, %f), pointerIds=0x%x",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001912 connection->getInputChannelName().c_str(), inputTarget->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913 inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001914 inputTarget->globalScaleFactor,
1915 inputTarget->windowXScale, inputTarget->windowYScale,
1916 inputTarget->pointerIds.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917#endif
1918
1919 // Skip this event if the connection status is not normal.
1920 // We don't want to enqueue additional outbound events if the connection is broken.
1921 if (connection->status != Connection::STATUS_NORMAL) {
1922#if DEBUG_DISPATCH_CYCLE
1923 ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001924 connection->getInputChannelName().c_str(), connection->getStatusLabel());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925#endif
1926 return;
1927 }
1928
1929 // Split a motion event if needed.
1930 if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
1931 ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
1932
1933 MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
1934 if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
1935 MotionEntry* splitMotionEntry = splitMotionEvent(
1936 originalMotionEntry, inputTarget->pointerIds);
1937 if (!splitMotionEntry) {
1938 return; // split event was dropped
1939 }
1940#if DEBUG_FOCUS
1941 ALOGD("channel '%s' ~ Split motion event.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08001942 connection->getInputChannelName().c_str());
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08001943 logOutboundMotionDetails(" ", splitMotionEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944#endif
1945 enqueueDispatchEntriesLocked(currentTime, connection,
1946 splitMotionEntry, inputTarget);
1947 splitMotionEntry->release();
1948 return;
1949 }
1950 }
1951
1952 // Not splitting. Enqueue dispatch entries for the event as is.
1953 enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
1954}
1955
1956void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
1957 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
1958 bool wasEmpty = connection->outboundQueue.isEmpty();
1959
1960 // Enqueue dispatch entries for the requested modes.
chaviw8c9cf542019-03-25 13:02:48 -07001961 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962 InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07001963 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
chaviw8c9cf542019-03-25 13:02:48 -07001965 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966 InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
chaviw8c9cf542019-03-25 13:02:48 -07001967 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 InputTarget::FLAG_DISPATCH_AS_IS);
chaviw8c9cf542019-03-25 13:02:48 -07001969 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
chaviw8c9cf542019-03-25 13:02:48 -07001971 enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972 InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
1973
1974 // If the outbound queue was previously empty, start the dispatch cycle going.
1975 if (wasEmpty && !connection->outboundQueue.isEmpty()) {
1976 startDispatchCycleLocked(currentTime, connection);
1977 }
1978}
1979
chaviw8c9cf542019-03-25 13:02:48 -07001980void InputDispatcher::enqueueDispatchEntryLocked(
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
1982 int32_t dispatchMode) {
1983 int32_t inputTargetFlags = inputTarget->flags;
1984 if (!(inputTargetFlags & dispatchMode)) {
1985 return;
1986 }
1987 inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
1988
1989 // This is a new event.
1990 // Enqueue a new dispatch entry onto the outbound queue for this connection.
1991 DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
1992 inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
Robert Carre07e1032018-11-26 12:55:53 -08001993 inputTarget->globalScaleFactor, inputTarget->windowXScale,
1994 inputTarget->windowYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995
1996 // Apply target flags and update the connection's input state.
1997 switch (eventEntry->type) {
1998 case EventEntry::TYPE_KEY: {
1999 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2000 dispatchEntry->resolvedAction = keyEntry->action;
2001 dispatchEntry->resolvedFlags = keyEntry->flags;
2002
2003 if (!connection->inputState.trackKey(keyEntry,
2004 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2005#if DEBUG_DISPATCH_CYCLE
2006 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002007 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008#endif
2009 delete dispatchEntry;
2010 return; // skip the inconsistent event
2011 }
2012 break;
2013 }
2014
2015 case EventEntry::TYPE_MOTION: {
2016 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2017 if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
2018 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
2019 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
2020 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
2021 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
2022 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2023 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
2024 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
2025 } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
2026 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
2027 } else {
2028 dispatchEntry->resolvedAction = motionEntry->action;
2029 }
2030 if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
2031 && !connection->inputState.isHovering(
2032 motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
2033#if DEBUG_DISPATCH_CYCLE
2034 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002035 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036#endif
2037 dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
2038 }
2039
2040 dispatchEntry->resolvedFlags = motionEntry->flags;
2041 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
2042 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
2043 }
Michael Wrightcdcd8f22016-03-22 16:52:13 -07002044 if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) {
2045 dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
2046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047
2048 if (!connection->inputState.trackMotion(motionEntry,
2049 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
2050#if DEBUG_DISPATCH_CYCLE
2051 ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002052 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053#endif
2054 delete dispatchEntry;
2055 return; // skip the inconsistent event
2056 }
chaviw8c9cf542019-03-25 13:02:48 -07002057
2058 dispatchPointerDownOutsideFocusIfNecessary(motionEntry->source,
2059 dispatchEntry->resolvedAction, inputTarget->inputChannel->getToken());
2060
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 break;
2062 }
2063 }
2064
2065 // Remember that we are waiting for this dispatch to complete.
2066 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002067 incrementPendingForegroundDispatches(eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068 }
2069
2070 // Enqueue the dispatch entry.
2071 connection->outboundQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002072 traceOutboundQueueLength(connection);
chaviw8c9cf542019-03-25 13:02:48 -07002073
2074}
2075
2076void InputDispatcher::dispatchPointerDownOutsideFocusIfNecessary(uint32_t source, int32_t action,
2077 const sp<IBinder>& newToken) {
2078 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2079 if (source != AINPUT_SOURCE_CLASS_POINTER || maskedAction != AMOTION_EVENT_ACTION_DOWN) {
2080 return;
2081 }
2082
2083 sp<InputWindowHandle> inputWindowHandle = getWindowHandleLocked(newToken);
2084 if (inputWindowHandle == nullptr) {
2085 return;
2086 }
2087
2088 int32_t displayId = inputWindowHandle->getInfo()->displayId;
2089 sp<InputWindowHandle> focusedWindowHandle =
2090 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
2091
2092 bool hasFocusChanged = !focusedWindowHandle || focusedWindowHandle->getToken() != newToken;
2093
2094 if (!hasFocusChanged) {
2095 return;
2096 }
2097
2098 // Dispatch onPointerDownOutsideFocus to the policy.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099}
2100
2101void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
2102 const sp<Connection>& connection) {
2103#if DEBUG_DISPATCH_CYCLE
2104 ALOGD("channel '%s' ~ startDispatchCycle",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002105 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106#endif
2107
2108 while (connection->status == Connection::STATUS_NORMAL
2109 && !connection->outboundQueue.isEmpty()) {
2110 DispatchEntry* dispatchEntry = connection->outboundQueue.head;
2111 dispatchEntry->deliveryTime = currentTime;
2112
2113 // Publish the event.
2114 status_t status;
2115 EventEntry* eventEntry = dispatchEntry->eventEntry;
2116 switch (eventEntry->type) {
2117 case EventEntry::TYPE_KEY: {
2118 KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
2119
2120 // Publish the key event.
2121 status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002122 keyEntry->deviceId, keyEntry->source, keyEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002123 dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
2124 keyEntry->keyCode, keyEntry->scanCode,
2125 keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
2126 keyEntry->eventTime);
2127 break;
2128 }
2129
2130 case EventEntry::TYPE_MOTION: {
2131 MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
2132
2133 PointerCoords scaledCoords[MAX_POINTERS];
2134 const PointerCoords* usingCoords = motionEntry->pointerCoords;
2135
2136 // Set the X and Y offset depending on the input source.
Siarhei Vishniakou635cb712017-11-01 16:32:14 -07002137 float xOffset, yOffset;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002138 if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
2139 && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
Robert Carre07e1032018-11-26 12:55:53 -08002140 float globalScaleFactor = dispatchEntry->globalScaleFactor;
2141 float wxs = dispatchEntry->windowXScale;
2142 float wys = dispatchEntry->windowYScale;
2143 xOffset = dispatchEntry->xOffset * wxs;
2144 yOffset = dispatchEntry->yOffset * wys;
2145 if (wxs != 1.0f || wys != 1.0f || globalScaleFactor != 1.0f) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002146 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147 scaledCoords[i] = motionEntry->pointerCoords[i];
Robert Carre07e1032018-11-26 12:55:53 -08002148 scaledCoords[i].scale(globalScaleFactor, wxs, wys);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 }
2150 usingCoords = scaledCoords;
2151 }
2152 } else {
2153 xOffset = 0.0f;
2154 yOffset = 0.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155
2156 // We don't want the dispatch target to know.
2157 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01002158 for (uint32_t i = 0; i < motionEntry->pointerCount; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002159 scaledCoords[i].clear();
2160 }
2161 usingCoords = scaledCoords;
2162 }
2163 }
2164
2165 // Publish the motion event.
2166 status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
Tarandeep Singh58641502017-07-31 10:51:54 -07002167 motionEntry->deviceId, motionEntry->source, motionEntry->displayId,
Michael Wright7b159c92015-05-14 14:48:03 +01002168 dispatchEntry->resolvedAction, motionEntry->actionButton,
2169 dispatchEntry->resolvedFlags, motionEntry->edgeFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002170 motionEntry->metaState, motionEntry->buttonState, motionEntry->classification,
Michael Wright7b159c92015-05-14 14:48:03 +01002171 xOffset, yOffset, motionEntry->xPrecision, motionEntry->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 motionEntry->downTime, motionEntry->eventTime,
2173 motionEntry->pointerCount, motionEntry->pointerProperties,
2174 usingCoords);
2175 break;
2176 }
2177
2178 default:
2179 ALOG_ASSERT(false);
2180 return;
2181 }
2182
2183 // Check the result.
2184 if (status) {
2185 if (status == WOULD_BLOCK) {
2186 if (connection->waitQueue.isEmpty()) {
2187 ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
2188 "This is unexpected because the wait queue is empty, so the pipe "
2189 "should be empty and we shouldn't have any problems writing an "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002190 "event to it, status=%d", connection->getInputChannelName().c_str(),
2191 status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2193 } else {
2194 // Pipe is full and we are waiting for the app to finish process some events
2195 // before sending more events to it.
2196#if DEBUG_DISPATCH_CYCLE
2197 ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
2198 "waiting for the application to catch up",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002199 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002200#endif
2201 connection->inputPublisherBlocked = true;
2202 }
2203 } else {
2204 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002205 "status=%d", connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
2207 }
2208 return;
2209 }
2210
2211 // Re-enqueue the event on the wait queue.
2212 connection->outboundQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002213 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 connection->waitQueue.enqueueAtTail(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002215 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216 }
2217}
2218
2219void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
2220 const sp<Connection>& connection, uint32_t seq, bool handled) {
2221#if DEBUG_DISPATCH_CYCLE
2222 ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002223 connection->getInputChannelName().c_str(), seq, toString(handled));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224#endif
2225
2226 connection->inputPublisherBlocked = false;
2227
2228 if (connection->status == Connection::STATUS_BROKEN
2229 || connection->status == Connection::STATUS_ZOMBIE) {
2230 return;
2231 }
2232
2233 // Notify other system components and prepare to start the next dispatch cycle.
2234 onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
2235}
2236
2237void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
2238 const sp<Connection>& connection, bool notify) {
2239#if DEBUG_DISPATCH_CYCLE
2240 ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002241 connection->getInputChannelName().c_str(), toString(notify));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242#endif
2243
2244 // Clear the dispatch queues.
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002245 drainDispatchQueue(&connection->outboundQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002246 traceOutboundQueueLength(connection);
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002247 drainDispatchQueue(&connection->waitQueue);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002248 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249
2250 // The connection appears to be unrecoverably broken.
2251 // Ignore already broken or zombie connections.
2252 if (connection->status == Connection::STATUS_NORMAL) {
2253 connection->status = Connection::STATUS_BROKEN;
2254
2255 if (notify) {
2256 // Notify other system components.
2257 onDispatchCycleBrokenLocked(currentTime, connection);
2258 }
2259 }
2260}
2261
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002262void InputDispatcher::drainDispatchQueue(Queue<DispatchEntry>* queue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 while (!queue->isEmpty()) {
2264 DispatchEntry* dispatchEntry = queue->dequeueAtHead();
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002265 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 }
2267}
2268
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002269void InputDispatcher::releaseDispatchEntry(DispatchEntry* dispatchEntry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 if (dispatchEntry->hasForegroundTarget()) {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002271 decrementPendingForegroundDispatches(dispatchEntry->eventEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 }
2273 delete dispatchEntry;
2274}
2275
2276int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
2277 InputDispatcher* d = static_cast<InputDispatcher*>(data);
2278
2279 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002280 std::scoped_lock _l(d->mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281
2282 ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
2283 if (connectionIndex < 0) {
2284 ALOGE("Received spurious receive callback for unknown input channel. "
2285 "fd=%d, events=0x%x", fd, events);
2286 return 0; // remove the callback
2287 }
2288
2289 bool notify;
2290 sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
2291 if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
2292 if (!(events & ALOOPER_EVENT_INPUT)) {
2293 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002294 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 return 1;
2296 }
2297
2298 nsecs_t currentTime = now();
2299 bool gotOne = false;
2300 status_t status;
2301 for (;;) {
2302 uint32_t seq;
2303 bool handled;
2304 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
2305 if (status) {
2306 break;
2307 }
2308 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
2309 gotOne = true;
2310 }
2311 if (gotOne) {
2312 d->runCommandsLockedInterruptible();
2313 if (status == WOULD_BLOCK) {
2314 return 1;
2315 }
2316 }
2317
2318 notify = status != DEAD_OBJECT || !connection->monitor;
2319 if (notify) {
2320 ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002321 connection->getInputChannelName().c_str(), status);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 }
2323 } else {
2324 // Monitor channels are never explicitly unregistered.
2325 // We do it automatically when the remote endpoint is closed so don't warn
2326 // about them.
2327 notify = !connection->monitor;
2328 if (notify) {
2329 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002330 "events=0x%x", connection->getInputChannelName().c_str(), events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 }
2332 }
2333
2334 // Unregister the channel.
2335 d->unregisterInputChannelLocked(connection->inputChannel, notify);
2336 return 0; // remove the callback
2337 } // release lock
2338}
2339
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002340void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked (
Michael Wrightd02c5b62014-02-10 15:10:22 -08002341 const CancelationOptions& options) {
2342 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
2343 synthesizeCancelationEventsForConnectionLocked(
2344 mConnectionsByFd.valueAt(i), options);
2345 }
2346}
2347
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002348void InputDispatcher::synthesizeCancelationEventsForMonitorsLocked (
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002349 const CancelationOptions& options) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002350 for (auto& it : mMonitoringChannelsByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002351 const std::vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002352 const size_t numChannels = monitoringChannels.size();
2353 for (size_t i = 0; i < numChannels; i++) {
2354 synthesizeCancelationEventsForInputChannelLocked(monitoringChannels[i], options);
2355 }
Michael Wrightfa13dcf2015-06-12 13:25:11 +01002356 }
2357}
2358
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
2360 const sp<InputChannel>& channel, const CancelationOptions& options) {
2361 ssize_t index = getConnectionIndexLocked(channel);
2362 if (index >= 0) {
2363 synthesizeCancelationEventsForConnectionLocked(
2364 mConnectionsByFd.valueAt(index), options);
2365 }
2366}
2367
2368void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
2369 const sp<Connection>& connection, const CancelationOptions& options) {
2370 if (connection->status == Connection::STATUS_BROKEN) {
2371 return;
2372 }
2373
2374 nsecs_t currentTime = now();
2375
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002376 std::vector<EventEntry*> cancelationEvents;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377 connection->inputState.synthesizeCancelationEvents(currentTime,
2378 cancelationEvents, options);
2379
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002380 if (!cancelationEvents.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002382 ALOGD("channel '%s' ~ Synthesized %zu cancelation events to bring channel back in sync "
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383 "with reality: %s, mode=%d.",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08002384 connection->getInputChannelName().c_str(), cancelationEvents.size(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385 options.reason, options.mode);
2386#endif
2387 for (size_t i = 0; i < cancelationEvents.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002388 EventEntry* cancelationEventEntry = cancelationEvents[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 switch (cancelationEventEntry->type) {
2390 case EventEntry::TYPE_KEY:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002391 logOutboundKeyDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 static_cast<KeyEntry*>(cancelationEventEntry));
2393 break;
2394 case EventEntry::TYPE_MOTION:
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08002395 logOutboundMotionDetails("cancel - ",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 static_cast<MotionEntry*>(cancelationEventEntry));
2397 break;
2398 }
2399
2400 InputTarget target;
chaviwfbe5d9c2018-12-26 12:23:37 -08002401 sp<InputWindowHandle> windowHandle = getWindowHandleLocked(
2402 connection->inputChannel->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07002403 if (windowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 const InputWindowInfo* windowInfo = windowHandle->getInfo();
2405 target.xOffset = -windowInfo->frameLeft;
2406 target.yOffset = -windowInfo->frameTop;
Robert Carre07e1032018-11-26 12:55:53 -08002407 target.globalScaleFactor = windowInfo->globalScaleFactor;
2408 target.windowXScale = windowInfo->windowXScale;
2409 target.windowYScale = windowInfo->windowYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 } else {
2411 target.xOffset = 0;
2412 target.yOffset = 0;
Robert Carre07e1032018-11-26 12:55:53 -08002413 target.globalScaleFactor = 1.0f;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002414 }
2415 target.inputChannel = connection->inputChannel;
2416 target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
2417
chaviw8c9cf542019-03-25 13:02:48 -07002418 enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419 &target, InputTarget::FLAG_DISPATCH_AS_IS);
2420
2421 cancelationEventEntry->release();
2422 }
2423
2424 startDispatchCycleLocked(currentTime, connection);
2425 }
2426}
2427
2428InputDispatcher::MotionEntry*
2429InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
2430 ALOG_ASSERT(pointerIds.value != 0);
2431
2432 uint32_t splitPointerIndexMap[MAX_POINTERS];
2433 PointerProperties splitPointerProperties[MAX_POINTERS];
2434 PointerCoords splitPointerCoords[MAX_POINTERS];
2435
2436 uint32_t originalPointerCount = originalMotionEntry->pointerCount;
2437 uint32_t splitPointerCount = 0;
2438
2439 for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
2440 originalPointerIndex++) {
2441 const PointerProperties& pointerProperties =
2442 originalMotionEntry->pointerProperties[originalPointerIndex];
2443 uint32_t pointerId = uint32_t(pointerProperties.id);
2444 if (pointerIds.hasBit(pointerId)) {
2445 splitPointerIndexMap[splitPointerCount] = originalPointerIndex;
2446 splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
2447 splitPointerCoords[splitPointerCount].copyFrom(
2448 originalMotionEntry->pointerCoords[originalPointerIndex]);
2449 splitPointerCount += 1;
2450 }
2451 }
2452
2453 if (splitPointerCount != pointerIds.count()) {
2454 // This is bad. We are missing some of the pointers that we expected to deliver.
2455 // Most likely this indicates that we received an ACTION_MOVE events that has
2456 // different pointer ids than we expected based on the previous ACTION_DOWN
2457 // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
2458 // in this way.
2459 ALOGW("Dropping split motion event because the pointer count is %d but "
2460 "we expected there to be %d pointers. This probably means we received "
2461 "a broken sequence of pointer ids from the input device.",
2462 splitPointerCount, pointerIds.count());
Yi Kong9b14ac62018-07-17 13:48:38 -07002463 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002464 }
2465
2466 int32_t action = originalMotionEntry->action;
2467 int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
2468 if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2469 || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
2470 int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
2471 const PointerProperties& pointerProperties =
2472 originalMotionEntry->pointerProperties[originalPointerIndex];
2473 uint32_t pointerId = uint32_t(pointerProperties.id);
2474 if (pointerIds.hasBit(pointerId)) {
2475 if (pointerIds.count() == 1) {
2476 // The first/last pointer went down/up.
2477 action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
2478 ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
2479 } else {
2480 // A secondary pointer went down/up.
2481 uint32_t splitPointerIndex = 0;
2482 while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
2483 splitPointerIndex += 1;
2484 }
2485 action = maskedAction | (splitPointerIndex
2486 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2487 }
2488 } else {
2489 // An unrelated pointer changed.
2490 action = AMOTION_EVENT_ACTION_MOVE;
2491 }
2492 }
2493
2494 MotionEntry* splitMotionEntry = new MotionEntry(
Prabir Pradhan42611e02018-11-27 14:04:02 -08002495 originalMotionEntry->sequenceNum,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 originalMotionEntry->eventTime,
2497 originalMotionEntry->deviceId,
2498 originalMotionEntry->source,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002499 originalMotionEntry->displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002500 originalMotionEntry->policyFlags,
2501 action,
Michael Wright7b159c92015-05-14 14:48:03 +01002502 originalMotionEntry->actionButton,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002503 originalMotionEntry->flags,
2504 originalMotionEntry->metaState,
2505 originalMotionEntry->buttonState,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002506 originalMotionEntry->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002507 originalMotionEntry->edgeFlags,
2508 originalMotionEntry->xPrecision,
2509 originalMotionEntry->yPrecision,
2510 originalMotionEntry->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002511 splitPointerCount, splitPointerProperties, splitPointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512
2513 if (originalMotionEntry->injectionState) {
2514 splitMotionEntry->injectionState = originalMotionEntry->injectionState;
2515 splitMotionEntry->injectionState->refCount += 1;
2516 }
2517
2518 return splitMotionEntry;
2519}
2520
2521void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
2522#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002523 ALOGD("notifyConfigurationChanged - eventTime=%" PRId64, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002524#endif
2525
2526 bool needWake;
2527 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002528 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002529
Prabir Pradhan42611e02018-11-27 14:04:02 -08002530 ConfigurationChangedEntry* newEntry =
2531 new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 needWake = enqueueInboundEventLocked(newEntry);
2533 } // release lock
2534
2535 if (needWake) {
2536 mLooper->wake();
2537 }
2538}
2539
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002540/**
2541 * If one of the meta shortcuts is detected, process them here:
2542 * Meta + Backspace -> generate BACK
2543 * Meta + Enter -> generate HOME
2544 * This will potentially overwrite keyCode and metaState.
2545 */
2546void InputDispatcher::accelerateMetaShortcuts(const int32_t deviceId, const int32_t action,
2547 int32_t& keyCode, int32_t& metaState) {
2548 if (metaState & AMETA_META_ON && action == AKEY_EVENT_ACTION_DOWN) {
2549 int32_t newKeyCode = AKEYCODE_UNKNOWN;
2550 if (keyCode == AKEYCODE_DEL) {
2551 newKeyCode = AKEYCODE_BACK;
2552 } else if (keyCode == AKEYCODE_ENTER) {
2553 newKeyCode = AKEYCODE_HOME;
2554 }
2555 if (newKeyCode != AKEYCODE_UNKNOWN) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002556 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002557 struct KeyReplacement replacement = {keyCode, deviceId};
2558 mReplacedKeys.add(replacement, newKeyCode);
2559 keyCode = newKeyCode;
2560 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2561 }
2562 } else if (action == AKEY_EVENT_ACTION_UP) {
2563 // In order to maintain a consistent stream of up and down events, check to see if the key
2564 // going up is one we've replaced in a down event and haven't yet replaced in an up event,
2565 // even if the modifier was released between the down and the up events.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002566 std::scoped_lock _l(mLock);
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002567 struct KeyReplacement replacement = {keyCode, deviceId};
2568 ssize_t index = mReplacedKeys.indexOfKey(replacement);
2569 if (index >= 0) {
2570 keyCode = mReplacedKeys.valueAt(index);
2571 mReplacedKeys.removeItemsAt(index);
2572 metaState &= ~(AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
2573 }
2574 }
2575}
2576
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
2578#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002579 ALOGD("notifyKey - eventTime=%" PRId64
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002580 ", deviceId=%d, source=0x%x, displayId=%" PRId32 "policyFlags=0x%x, action=0x%x, "
Arthur Hung82a4cad2018-11-15 12:10:30 +08002581 "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%" PRId64,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002582 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 args->action, args->flags, args->keyCode, args->scanCode,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002584 args->metaState, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585#endif
2586 if (!validateKeyEvent(args->action)) {
2587 return;
2588 }
2589
2590 uint32_t policyFlags = args->policyFlags;
2591 int32_t flags = args->flags;
2592 int32_t metaState = args->metaState;
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002593 // InputDispatcher tracks and generates key repeats on behalf of
2594 // whatever notifies it, so repeatCount should always be set to 0
2595 constexpr int32_t repeatCount = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
2597 policyFlags |= POLICY_FLAG_VIRTUAL;
2598 flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2599 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002600 if (policyFlags & POLICY_FLAG_FUNCTION) {
2601 metaState |= AMETA_FUNCTION_ON;
2602 }
2603
2604 policyFlags |= POLICY_FLAG_TRUSTED;
2605
Michael Wright78f24442014-08-06 15:55:28 -07002606 int32_t keyCode = args->keyCode;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002607 accelerateMetaShortcuts(args->deviceId, args->action, keyCode, metaState);
Michael Wright78f24442014-08-06 15:55:28 -07002608
Michael Wrightd02c5b62014-02-10 15:10:22 -08002609 KeyEvent event;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002610 event.initialize(args->deviceId, args->source, args->displayId, args->action,
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002611 flags, keyCode, args->scanCode, metaState, repeatCount,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 args->downTime, args->eventTime);
2613
Michael Wright2b3c3302018-03-02 17:19:13 +00002614 android::base::Timer t;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002616 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2617 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2618 std::to_string(t.duration().count()).c_str());
2619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621 bool needWake;
2622 { // acquire lock
2623 mLock.lock();
2624
2625 if (shouldSendKeyToInputFilterLocked(args)) {
2626 mLock.unlock();
2627
2628 policyFlags |= POLICY_FLAG_FILTERED;
2629 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2630 return; // event was consumed by the filter
2631 }
2632
2633 mLock.lock();
2634 }
2635
Prabir Pradhan42611e02018-11-27 14:04:02 -08002636 KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002637 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright78f24442014-08-06 15:55:28 -07002638 args->action, flags, keyCode, args->scanCode,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639 metaState, repeatCount, args->downTime);
2640
2641 needWake = enqueueInboundEventLocked(newEntry);
2642 mLock.unlock();
2643 } // release lock
2644
2645 if (needWake) {
2646 mLooper->wake();
2647 }
2648}
2649
2650bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
2651 return mInputFilterEnabled;
2652}
2653
2654void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
2655#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002656 ALOGD("notifyMotion - eventTime=%" PRId64 ", deviceId=%d, source=0x%x, displayId=%" PRId32
2657 ", policyFlags=0x%x, "
Michael Wright7b159c92015-05-14 14:48:03 +01002658 "action=0x%x, actionButton=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x,"
Arthur Hung82a4cad2018-11-15 12:10:30 +08002659 "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%" PRId64,
2660 args->eventTime, args->deviceId, args->source, args->displayId, args->policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002661 args->action, args->actionButton, args->flags, args->metaState, args->buttonState,
Arthur Hung82a4cad2018-11-15 12:10:30 +08002662 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663 for (uint32_t i = 0; i < args->pointerCount; i++) {
2664 ALOGD(" Pointer %d: id=%d, toolType=%d, "
2665 "x=%f, y=%f, pressure=%f, size=%f, "
2666 "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
2667 "orientation=%f",
2668 i, args->pointerProperties[i].id,
2669 args->pointerProperties[i].toolType,
2670 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
2671 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
2672 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
2673 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
2674 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
2675 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
2676 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
2677 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
2678 args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
2679 }
2680#endif
Michael Wright7b159c92015-05-14 14:48:03 +01002681 if (!validateMotionEvent(args->action, args->actionButton,
2682 args->pointerCount, args->pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683 return;
2684 }
2685
2686 uint32_t policyFlags = args->policyFlags;
2687 policyFlags |= POLICY_FLAG_TRUSTED;
Michael Wright2b3c3302018-03-02 17:19:13 +00002688
2689 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002690 mPolicy->interceptMotionBeforeQueueing(args->displayId, args->eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002691 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2692 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2693 std::to_string(t.duration().count()).c_str());
2694 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695
2696 bool needWake;
2697 { // acquire lock
2698 mLock.lock();
2699
2700 if (shouldSendMotionToInputFilterLocked(args)) {
2701 mLock.unlock();
2702
2703 MotionEvent event;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002704 event.initialize(args->deviceId, args->source, args->displayId,
2705 args->action, args->actionButton,
Michael Wright7b159c92015-05-14 14:48:03 +01002706 args->flags, args->edgeFlags, args->metaState, args->buttonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002707 args->classification, 0, 0, args->xPrecision, args->yPrecision,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 args->downTime, args->eventTime,
2709 args->pointerCount, args->pointerProperties, args->pointerCoords);
2710
2711 policyFlags |= POLICY_FLAG_FILTERED;
2712 if (!mPolicy->filterInputEvent(&event, policyFlags)) {
2713 return; // event was consumed by the filter
2714 }
2715
2716 mLock.lock();
2717 }
2718
2719 // Just enqueue a new motion event.
Prabir Pradhan42611e02018-11-27 14:04:02 -08002720 MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002721 args->deviceId, args->source, args->displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002722 args->action, args->actionButton, args->flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002723 args->metaState, args->buttonState, args->classification,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002724 args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08002725 args->pointerCount, args->pointerProperties, args->pointerCoords, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726
2727 needWake = enqueueInboundEventLocked(newEntry);
2728 mLock.unlock();
2729 } // release lock
2730
2731 if (needWake) {
2732 mLooper->wake();
2733 }
2734}
2735
2736bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
Jackal Guof9696682018-10-05 12:23:23 +08002737 return mInputFilterEnabled;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002738}
2739
2740void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
2741#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002742 ALOGD("notifySwitch - eventTime=%" PRId64 ", policyFlags=0x%x, switchValues=0x%08x, "
2743 "switchMask=0x%08x",
2744 args->eventTime, args->policyFlags, args->switchValues, args->switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745#endif
2746
2747 uint32_t policyFlags = args->policyFlags;
2748 policyFlags |= POLICY_FLAG_TRUSTED;
2749 mPolicy->notifySwitch(args->eventTime,
2750 args->switchValues, args->switchMask, policyFlags);
2751}
2752
2753void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
2754#if DEBUG_INBOUND_EVENT_DETAILS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002755 ALOGD("notifyDeviceReset - eventTime=%" PRId64 ", deviceId=%d",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756 args->eventTime, args->deviceId);
2757#endif
2758
2759 bool needWake;
2760 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002761 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002762
Prabir Pradhan42611e02018-11-27 14:04:02 -08002763 DeviceResetEntry* newEntry =
2764 new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 needWake = enqueueInboundEventLocked(newEntry);
2766 } // release lock
2767
2768 if (needWake) {
2769 mLooper->wake();
2770 }
2771}
2772
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002773int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
2775 uint32_t policyFlags) {
2776#if DEBUG_INBOUND_EVENT_DETAILS
2777 ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002778 "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
2779 event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780#endif
2781
2782 nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
2783
2784 policyFlags |= POLICY_FLAG_INJECTED;
2785 if (hasInjectionPermission(injectorPid, injectorUid)) {
2786 policyFlags |= POLICY_FLAG_TRUSTED;
2787 }
2788
2789 EventEntry* firstInjectedEntry;
2790 EventEntry* lastInjectedEntry;
2791 switch (event->getType()) {
2792 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002793 KeyEvent keyEvent;
2794 keyEvent.initialize(*static_cast<const KeyEvent*>(event));
2795 int32_t action = keyEvent.getAction();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 if (! validateKeyEvent(action)) {
2797 return INPUT_EVENT_INJECTION_FAILED;
2798 }
2799
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002800 int32_t flags = keyEvent.getFlags();
2801 int32_t keyCode = keyEvent.getKeyCode();
2802 int32_t metaState = keyEvent.getMetaState();
2803 accelerateMetaShortcuts(keyEvent.getDeviceId(), action,
2804 /*byref*/ keyCode, /*byref*/ metaState);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002805 keyEvent.initialize(keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Siarhei Vishniakou622bd322018-10-29 18:02:27 -07002806 action, flags, keyCode, keyEvent.getScanCode(), metaState, keyEvent.getRepeatCount(),
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002807 keyEvent.getDownTime(), keyEvent.getEventTime());
2808
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
2810 policyFlags |= POLICY_FLAG_VIRTUAL;
2811 }
2812
2813 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
Michael Wright2b3c3302018-03-02 17:19:13 +00002814 android::base::Timer t;
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002815 mPolicy->interceptKeyBeforeQueueing(&keyEvent, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002816 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2817 ALOGW("Excessive delay in interceptKeyBeforeQueueing; took %s ms",
2818 std::to_string(t.duration().count()).c_str());
2819 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 }
2821
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 mLock.lock();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002823 firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002824 keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 policyFlags, action, flags,
Siarhei Vishniakou61fafdd2018-04-13 11:00:58 -05002826 keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
2827 keyEvent.getRepeatCount(), keyEvent.getDownTime());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 lastInjectedEntry = firstInjectedEntry;
2829 break;
2830 }
2831
2832 case AINPUT_EVENT_TYPE_MOTION: {
2833 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 int32_t action = motionEvent->getAction();
2835 size_t pointerCount = motionEvent->getPointerCount();
2836 const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
Michael Wright7b159c92015-05-14 14:48:03 +01002837 int32_t actionButton = motionEvent->getActionButton();
Charles Chen3611f1f2019-01-29 17:26:18 +08002838 int32_t displayId = motionEvent->getDisplayId();
Michael Wright7b159c92015-05-14 14:48:03 +01002839 if (! validateMotionEvent(action, actionButton, pointerCount, pointerProperties)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840 return INPUT_EVENT_INJECTION_FAILED;
2841 }
2842
2843 if (!(policyFlags & POLICY_FLAG_FILTERED)) {
2844 nsecs_t eventTime = motionEvent->getEventTime();
Michael Wright2b3c3302018-03-02 17:19:13 +00002845 android::base::Timer t;
Charles Chen3611f1f2019-01-29 17:26:18 +08002846 mPolicy->interceptMotionBeforeQueueing(displayId, eventTime, /*byref*/ policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00002847 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
2848 ALOGW("Excessive delay in interceptMotionBeforeQueueing; took %s ms",
2849 std::to_string(t.duration().count()).c_str());
2850 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 }
2852
2853 mLock.lock();
2854 const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
2855 const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
Prabir Pradhan42611e02018-11-27 14:04:02 -08002856 firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002857 motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
2858 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002859 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002861 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002863 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002864 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2865 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 lastInjectedEntry = firstInjectedEntry;
2867 for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
2868 sampleEventTimes += 1;
2869 samplePointerCoords += pointerCount;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002870 MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
2871 *sampleEventTimes,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002872 motionEvent->getDeviceId(), motionEvent->getSource(),
2873 motionEvent->getDisplayId(), policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002874 action, actionButton, motionEvent->getFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002875 motionEvent->getMetaState(), motionEvent->getButtonState(),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08002876 motionEvent->getClassification(), motionEvent->getEdgeFlags(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877 motionEvent->getXPrecision(), motionEvent->getYPrecision(),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002878 motionEvent->getDownTime(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08002879 uint32_t(pointerCount), pointerProperties, samplePointerCoords,
2880 motionEvent->getXOffset(), motionEvent->getYOffset());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881 lastInjectedEntry->next = nextInjectedEntry;
2882 lastInjectedEntry = nextInjectedEntry;
2883 }
2884 break;
2885 }
2886
2887 default:
2888 ALOGW("Cannot inject event of type %d", event->getType());
2889 return INPUT_EVENT_INJECTION_FAILED;
2890 }
2891
2892 InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
2893 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2894 injectionState->injectionIsAsync = true;
2895 }
2896
2897 injectionState->refCount += 1;
2898 lastInjectedEntry->injectionState = injectionState;
2899
2900 bool needWake = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07002901 for (EventEntry* entry = firstInjectedEntry; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902 EventEntry* nextEntry = entry->next;
2903 needWake |= enqueueInboundEventLocked(entry);
2904 entry = nextEntry;
2905 }
2906
2907 mLock.unlock();
2908
2909 if (needWake) {
2910 mLooper->wake();
2911 }
2912
2913 int32_t injectionResult;
2914 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002915 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916
2917 if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
2918 injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
2919 } else {
2920 for (;;) {
2921 injectionResult = injectionState->injectionResult;
2922 if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
2923 break;
2924 }
2925
2926 nsecs_t remainingTimeout = endTime - now();
2927 if (remainingTimeout <= 0) {
2928#if DEBUG_INJECTION
2929 ALOGD("injectInputEvent - Timed out waiting for injection result "
2930 "to become available.");
2931#endif
2932 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2933 break;
2934 }
2935
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002936 mInjectionResultAvailable.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002937 }
2938
2939 if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
2940 && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
2941 while (injectionState->pendingForegroundDispatches != 0) {
2942#if DEBUG_INJECTION
2943 ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
2944 injectionState->pendingForegroundDispatches);
2945#endif
2946 nsecs_t remainingTimeout = endTime - now();
2947 if (remainingTimeout <= 0) {
2948#if DEBUG_INJECTION
2949 ALOGD("injectInputEvent - Timed out waiting for pending foreground "
2950 "dispatches to finish.");
2951#endif
2952 injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
2953 break;
2954 }
2955
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08002956 mInjectionSyncFinished.wait_for(_l, std::chrono::nanoseconds(remainingTimeout));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957 }
2958 }
2959 }
2960
2961 injectionState->release();
2962 } // release lock
2963
2964#if DEBUG_INJECTION
2965 ALOGD("injectInputEvent - Finished with result %d. "
2966 "injectorPid=%d, injectorUid=%d",
2967 injectionResult, injectorPid, injectorUid);
2968#endif
2969
2970 return injectionResult;
2971}
2972
2973bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
2974 return injectorUid == 0
2975 || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
2976}
2977
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08002978void InputDispatcher::setInjectionResult(EventEntry* entry, int32_t injectionResult) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002979 InjectionState* injectionState = entry->injectionState;
2980 if (injectionState) {
2981#if DEBUG_INJECTION
2982 ALOGD("Setting input event injection result to %d. "
2983 "injectorPid=%d, injectorUid=%d",
2984 injectionResult, injectionState->injectorPid, injectionState->injectorUid);
2985#endif
2986
2987 if (injectionState->injectionIsAsync
2988 && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
2989 // Log the outcome since the injector did not wait for the injection result.
2990 switch (injectionResult) {
2991 case INPUT_EVENT_INJECTION_SUCCEEDED:
2992 ALOGV("Asynchronous input event injection succeeded.");
2993 break;
2994 case INPUT_EVENT_INJECTION_FAILED:
2995 ALOGW("Asynchronous input event injection failed.");
2996 break;
2997 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
2998 ALOGW("Asynchronous input event injection permission denied.");
2999 break;
3000 case INPUT_EVENT_INJECTION_TIMED_OUT:
3001 ALOGW("Asynchronous input event injection timed out.");
3002 break;
3003 }
3004 }
3005
3006 injectionState->injectionResult = injectionResult;
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003007 mInjectionResultAvailable.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003008 }
3009}
3010
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003011void InputDispatcher::incrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003012 InjectionState* injectionState = entry->injectionState;
3013 if (injectionState) {
3014 injectionState->pendingForegroundDispatches += 1;
3015 }
3016}
3017
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08003018void InputDispatcher::decrementPendingForegroundDispatches(EventEntry* entry) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003019 InjectionState* injectionState = entry->injectionState;
3020 if (injectionState) {
3021 injectionState->pendingForegroundDispatches -= 1;
3022
3023 if (injectionState->pendingForegroundDispatches == 0) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003024 mInjectionSyncFinished.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003025 }
3026 }
3027}
3028
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003029std::vector<sp<InputWindowHandle>> InputDispatcher::getWindowHandlesLocked(
3030 int32_t displayId) const {
3031 std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>::const_iterator it =
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003032 mWindowHandlesByDisplay.find(displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003033 if(it != mWindowHandlesByDisplay.end()) {
3034 return it->second;
3035 }
3036
3037 // Return an empty one if nothing found.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003038 return std::vector<sp<InputWindowHandle>>();
Arthur Hungb92218b2018-08-14 12:00:21 +08003039}
3040
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
chaviwfbe5d9c2018-12-26 12:23:37 -08003042 const sp<IBinder>& windowHandleToken) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003043 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003044 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3045 for (const sp<InputWindowHandle>& windowHandle : windowHandles) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003046 if (windowHandle->getToken() == windowHandleToken) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003047 return windowHandle;
3048 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003049 }
3050 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003051 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003052}
3053
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003054bool InputDispatcher::hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const {
Arthur Hungb92218b2018-08-14 12:00:21 +08003055 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003056 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
3057 for (const sp<InputWindowHandle>& handle : windowHandles) {
3058 if (handle->getToken() == windowHandle->getToken()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003059 if (windowHandle->getInfo()->displayId != it.first) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003060 ALOGE("Found window %s in display %" PRId32
3061 ", but it should belong to display %" PRId32,
3062 windowHandle->getName().c_str(), it.first,
3063 windowHandle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003064 }
3065 return true;
3066 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003067 }
3068 }
3069 return false;
3070}
3071
Robert Carr5c8a0262018-10-03 16:30:44 -07003072sp<InputChannel> InputDispatcher::getInputChannelLocked(const sp<IBinder>& token) const {
3073 size_t count = mInputChannelsByToken.count(token);
3074 if (count == 0) {
3075 return nullptr;
3076 }
3077 return mInputChannelsByToken.at(token);
3078}
3079
Arthur Hungb92218b2018-08-14 12:00:21 +08003080/**
3081 * Called from InputManagerService, update window handle list by displayId that can receive input.
3082 * A window handle contains information about InputChannel, Touch Region, Types, Focused,...
3083 * If set an empty list, remove all handles from the specific display.
3084 * For focused handle, check if need to change and send a cancel event to previous one.
3085 * For removed handle, check if need to send a cancel event if already in touch.
3086 */
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003087void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
chaviw291d88a2019-02-14 10:33:58 -08003088 int32_t displayId, const sp<ISetInputWindowsListener>& setInputWindowsListener) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003089#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003090 ALOGD("setInputWindows displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003091#endif
3092 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003093 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094
Arthur Hungb92218b2018-08-14 12:00:21 +08003095 // Copy old handles for release if they are no longer present.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003096 const std::vector<sp<InputWindowHandle>> oldWindowHandles =
3097 getWindowHandlesLocked(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098
Tiger Huang721e26f2018-07-24 22:26:19 +08003099 sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003100 bool foundHoveredWindow = false;
Arthur Hungb92218b2018-08-14 12:00:21 +08003101
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003102 if (inputWindowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003103 // Remove all handles on a display if there are no windows left.
3104 mWindowHandlesByDisplay.erase(displayId);
3105 } else {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003106 // Since we compare the pointer of input window handles across window updates, we need
3107 // to make sure the handle object for the same window stays unchanged across updates.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003108 const std::vector<sp<InputWindowHandle>>& oldHandles =
3109 mWindowHandlesByDisplay[displayId];
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003110 std::unordered_map<sp<IBinder>, sp<InputWindowHandle>, IBinderHash> oldHandlesByTokens;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003111 for (const sp<InputWindowHandle>& handle : oldHandles) {
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003112 oldHandlesByTokens[handle->getToken()] = handle;
3113 }
3114
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003115 std::vector<sp<InputWindowHandle>> newHandles;
3116 for (const sp<InputWindowHandle>& handle : inputWindowHandles) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003117 if (!handle->updateInfo() || (getInputChannelLocked(handle->getToken()) == nullptr
3118 && handle->getInfo()->portalToDisplayId == ADISPLAY_ID_NONE)) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003119 ALOGE("Window handle %s has no registered input channel",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003120 handle->getName().c_str());
Arthur Hungb92218b2018-08-14 12:00:21 +08003121 continue;
3122 }
3123
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003124 if (handle->getInfo()->displayId != displayId) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003125 ALOGE("Window %s updated by wrong display %d, should belong to display %d",
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003126 handle->getName().c_str(), displayId,
3127 handle->getInfo()->displayId);
Arthur Hungb92218b2018-08-14 12:00:21 +08003128 continue;
3129 }
3130
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003131 if (oldHandlesByTokens.find(handle->getToken()) != oldHandlesByTokens.end()) {
3132 const sp<InputWindowHandle> oldHandle =
3133 oldHandlesByTokens.at(handle->getToken());
3134 oldHandle->updateFrom(handle);
3135 newHandles.push_back(oldHandle);
3136 } else {
3137 newHandles.push_back(handle);
3138 }
3139 }
3140
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003141 for (const sp<InputWindowHandle>& windowHandle : newHandles) {
Arthur Hung7ab76b12019-01-09 19:17:20 +08003142 // Set newFocusedWindowHandle to the top most focused window instead of the last one
3143 if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus
3144 && windowHandle->getInfo()->visible) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003145 newFocusedWindowHandle = windowHandle;
3146 }
3147 if (windowHandle == mLastHoverWindowHandle) {
3148 foundHoveredWindow = true;
3149 }
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003150 }
Arthur Hungb92218b2018-08-14 12:00:21 +08003151
3152 // Insert or replace
Garfield Tanbd0fbcd2018-11-30 12:45:03 -08003153 mWindowHandlesByDisplay[displayId] = newHandles;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154 }
3155
3156 if (!foundHoveredWindow) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003157 mLastHoverWindowHandle = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 }
3159
Tiger Huang721e26f2018-07-24 22:26:19 +08003160 sp<InputWindowHandle> oldFocusedWindowHandle =
3161 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
3162
3163 if (oldFocusedWindowHandle != newFocusedWindowHandle) {
3164 if (oldFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003166 ALOGD("Focus left window: %s in display %" PRId32,
3167 oldFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168#endif
Robert Carr5c8a0262018-10-03 16:30:44 -07003169 sp<InputChannel> focusedInputChannel = getInputChannelLocked(
3170 oldFocusedWindowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003171 if (focusedInputChannel != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
3173 "focus left window");
3174 synthesizeCancelationEventsForInputChannelLocked(
3175 focusedInputChannel, options);
3176 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003177 mFocusedWindowHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 }
Yi Kong9b14ac62018-07-17 13:48:38 -07003179 if (newFocusedWindowHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003181 ALOGD("Focus entered window: %s in display %" PRId32,
3182 newFocusedWindowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183#endif
Tiger Huang721e26f2018-07-24 22:26:19 +08003184 mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003185 }
Robert Carrf759f162018-11-13 12:57:11 -08003186
3187 if (mFocusedDisplayId == displayId) {
chaviw0c06c6e2019-01-09 13:27:07 -08003188 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003189 }
3190
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 }
3192
Arthur Hungb92218b2018-08-14 12:00:21 +08003193 ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
3194 if (stateIndex >= 0) {
3195 TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
Ivan Lozano96f12992017-11-09 14:45:38 -08003196 for (size_t i = 0; i < state.windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003197 TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003198 if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003200 ALOGD("Touched window was removed: %s in display %" PRId32,
3201 touchedWindow.windowHandle->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003202#endif
Jeff Brownf086ddb2014-02-11 14:28:48 -08003203 sp<InputChannel> touchedInputChannel =
Robert Carr5c8a0262018-10-03 16:30:44 -07003204 getInputChannelLocked(touchedWindow.windowHandle->getToken());
Yi Kong9b14ac62018-07-17 13:48:38 -07003205 if (touchedInputChannel != nullptr) {
Jeff Brownf086ddb2014-02-11 14:28:48 -08003206 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3207 "touched window was removed");
3208 synthesizeCancelationEventsForInputChannelLocked(
3209 touchedInputChannel, options);
3210 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003211 state.windows.erase(state.windows.begin() + i);
Ivan Lozano96f12992017-11-09 14:45:38 -08003212 } else {
3213 ++i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215 }
3216 }
3217
3218 // Release information for windows that are no longer present.
3219 // This ensures that unused input channels are released promptly.
3220 // Otherwise, they might stick around until the window handle is destroyed
3221 // which might not happen until the next GC.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003222 for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
Siarhei Vishniakou9224fba2018-08-13 18:55:08 +00003223 if (!hasWindowHandleLocked(oldWindowHandle)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224#if DEBUG_FOCUS
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003225 ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226#endif
Arthur Hung3b413f22018-10-26 18:05:34 +08003227 oldWindowHandle->releaseChannel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 }
3229 }
3230 } // release lock
3231
3232 // Wake up poll loop since it may need to make new input dispatching choices.
3233 mLooper->wake();
chaviw291d88a2019-02-14 10:33:58 -08003234
3235 if (setInputWindowsListener) {
3236 setInputWindowsListener->onSetInputWindowsFinished();
3237 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238}
3239
3240void InputDispatcher::setFocusedApplication(
Tiger Huang721e26f2018-07-24 22:26:19 +08003241 int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242#if DEBUG_FOCUS
Arthur Hung3b413f22018-10-26 18:05:34 +08003243 ALOGD("setFocusedApplication displayId=%" PRId32, displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244#endif
3245 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003246 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247
Tiger Huang721e26f2018-07-24 22:26:19 +08003248 sp<InputApplicationHandle> oldFocusedApplicationHandle =
3249 getValueByKey(mFocusedApplicationHandlesByDisplay, displayId);
Yi Kong9b14ac62018-07-17 13:48:38 -07003250 if (inputApplicationHandle != nullptr && inputApplicationHandle->updateInfo()) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003251 if (oldFocusedApplicationHandle != inputApplicationHandle) {
3252 if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003254 oldFocusedApplicationHandle->releaseInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003256 mFocusedApplicationHandlesByDisplay[displayId] = inputApplicationHandle;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003258 } else if (oldFocusedApplicationHandle != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003259 resetANRTimeoutsLocked();
Tiger Huang721e26f2018-07-24 22:26:19 +08003260 oldFocusedApplicationHandle->releaseInfo();
3261 oldFocusedApplicationHandle.clear();
3262 mFocusedApplicationHandlesByDisplay.erase(displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263 }
3264
3265#if DEBUG_FOCUS
3266 //logDispatchStateLocked();
3267#endif
3268 } // release lock
3269
3270 // Wake up poll loop since it may need to make new input dispatching choices.
3271 mLooper->wake();
3272}
3273
Tiger Huang721e26f2018-07-24 22:26:19 +08003274/**
3275 * Sets the focused display, which is responsible for receiving focus-dispatched input events where
3276 * the display not specified.
3277 *
3278 * We track any unreleased events for each window. If a window loses the ability to receive the
3279 * released event, we will send a cancel event to it. So when the focused display is changed, we
3280 * cancel all the unreleased display-unspecified events for the focused window on the old focused
3281 * display. The display-specified events won't be affected.
3282 */
3283void InputDispatcher::setFocusedDisplay(int32_t displayId) {
3284#if DEBUG_FOCUS
3285 ALOGD("setFocusedDisplay displayId=%" PRId32, displayId);
3286#endif
3287 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003288 std::scoped_lock _l(mLock);
Tiger Huang721e26f2018-07-24 22:26:19 +08003289
3290 if (mFocusedDisplayId != displayId) {
3291 sp<InputWindowHandle> oldFocusedWindowHandle =
3292 getValueByKey(mFocusedWindowHandlesByDisplay, mFocusedDisplayId);
3293 if (oldFocusedWindowHandle != nullptr) {
Robert Carr5c8a0262018-10-03 16:30:44 -07003294 sp<InputChannel> inputChannel =
3295 getInputChannelLocked(oldFocusedWindowHandle->getToken());
Tiger Huang721e26f2018-07-24 22:26:19 +08003296 if (inputChannel != nullptr) {
3297 CancelationOptions options(
3298 CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS,
3299 "The display which contains this window no longer has focus.");
3300 synthesizeCancelationEventsForInputChannelLocked(inputChannel, options);
3301 }
3302 }
3303 mFocusedDisplayId = displayId;
3304
3305 // Sanity check
3306 sp<InputWindowHandle> newFocusedWindowHandle =
3307 getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
chaviw0c06c6e2019-01-09 13:27:07 -08003308 onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
Robert Carrf759f162018-11-13 12:57:11 -08003309
Tiger Huang721e26f2018-07-24 22:26:19 +08003310 if (newFocusedWindowHandle == nullptr) {
3311 ALOGW("Focused display #%" PRId32 " does not have a focused window.", displayId);
3312 if (!mFocusedWindowHandlesByDisplay.empty()) {
3313 ALOGE("But another display has a focused window:");
3314 for (auto& it : mFocusedWindowHandlesByDisplay) {
3315 const int32_t displayId = it.first;
3316 const sp<InputWindowHandle>& windowHandle = it.second;
3317 ALOGE("Display #%" PRId32 " has focused window: '%s'\n",
3318 displayId, windowHandle->getName().c_str());
3319 }
3320 }
3321 }
3322 }
3323
3324#if DEBUG_FOCUS
3325 logDispatchStateLocked();
3326#endif
3327 } // release lock
3328
3329 // Wake up poll loop since it may need to make new input dispatching choices.
3330 mLooper->wake();
3331}
3332
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
3334#if DEBUG_FOCUS
3335 ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
3336#endif
3337
3338 bool changed;
3339 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003340 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341
3342 if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
3343 if (mDispatchFrozen && !frozen) {
3344 resetANRTimeoutsLocked();
3345 }
3346
3347 if (mDispatchEnabled && !enabled) {
3348 resetAndDropEverythingLocked("dispatcher is being disabled");
3349 }
3350
3351 mDispatchEnabled = enabled;
3352 mDispatchFrozen = frozen;
3353 changed = true;
3354 } else {
3355 changed = false;
3356 }
3357
3358#if DEBUG_FOCUS
Tiger Huang721e26f2018-07-24 22:26:19 +08003359 logDispatchStateLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360#endif
3361 } // release lock
3362
3363 if (changed) {
3364 // Wake up poll loop since it may need to make new input dispatching choices.
3365 mLooper->wake();
3366 }
3367}
3368
3369void InputDispatcher::setInputFilterEnabled(bool enabled) {
3370#if DEBUG_FOCUS
3371 ALOGD("setInputFilterEnabled: enabled=%d", enabled);
3372#endif
3373
3374 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003375 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376
3377 if (mInputFilterEnabled == enabled) {
3378 return;
3379 }
3380
3381 mInputFilterEnabled = enabled;
3382 resetAndDropEverythingLocked("input filter is being enabled or disabled");
3383 } // release lock
3384
3385 // Wake up poll loop since there might be work to do to drop everything.
3386 mLooper->wake();
3387}
3388
chaviwfbe5d9c2018-12-26 12:23:37 -08003389bool InputDispatcher::transferTouchFocus(const sp<IBinder>& fromToken, const sp<IBinder>& toToken) {
3390 if (fromToken == toToken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391#if DEBUG_FOCUS
chaviwfbe5d9c2018-12-26 12:23:37 -08003392 ALOGD("Trivial transfer to same window.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393#endif
chaviwfbe5d9c2018-12-26 12:23:37 -08003394 return true;
3395 }
3396
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003398 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399
chaviwfbe5d9c2018-12-26 12:23:37 -08003400 sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromToken);
3401 sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toToken);
Yi Kong9b14ac62018-07-17 13:48:38 -07003402 if (fromWindowHandle == nullptr || toWindowHandle == nullptr) {
chaviwfbe5d9c2018-12-26 12:23:37 -08003403 ALOGW("Cannot transfer focus because from or to window not found.");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404 return false;
3405 }
chaviw4f2dd402018-12-26 15:30:27 -08003406#if DEBUG_FOCUS
3407 ALOGD("transferTouchFocus: fromWindowHandle=%s, toWindowHandle=%s",
3408 fromWindowHandle->getName().c_str(), toWindowHandle->getName().c_str());
3409#endif
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
3411#if DEBUG_FOCUS
3412 ALOGD("Cannot transfer focus because windows are on different displays.");
3413#endif
3414 return false;
3415 }
3416
3417 bool found = false;
Jeff Brownf086ddb2014-02-11 14:28:48 -08003418 for (size_t d = 0; d < mTouchStatesByDisplay.size(); d++) {
3419 TouchState& state = mTouchStatesByDisplay.editValueAt(d);
3420 for (size_t i = 0; i < state.windows.size(); i++) {
3421 const TouchedWindow& touchedWindow = state.windows[i];
3422 if (touchedWindow.windowHandle == fromWindowHandle) {
3423 int32_t oldTargetFlags = touchedWindow.targetFlags;
3424 BitSet32 pointerIds = touchedWindow.pointerIds;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003426 state.windows.erase(state.windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427
Jeff Brownf086ddb2014-02-11 14:28:48 -08003428 int32_t newTargetFlags = oldTargetFlags
3429 & (InputTarget::FLAG_FOREGROUND
3430 | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
3431 state.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432
Jeff Brownf086ddb2014-02-11 14:28:48 -08003433 found = true;
3434 goto Found;
3435 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 }
3437 }
Jeff Brownf086ddb2014-02-11 14:28:48 -08003438Found:
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439
3440 if (! found) {
3441#if DEBUG_FOCUS
3442 ALOGD("Focus transfer failed because from window did not have focus.");
3443#endif
3444 return false;
3445 }
3446
chaviwfbe5d9c2018-12-26 12:23:37 -08003447
3448 sp<InputChannel> fromChannel = getInputChannelLocked(fromToken);
3449 sp<InputChannel> toChannel = getInputChannelLocked(toToken);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
3451 ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
3452 if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
3453 sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
3454 sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
3455
3456 fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
3457 CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
3458 "transferring touch focus from this window to another window");
3459 synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
3460 }
3461
3462#if DEBUG_FOCUS
3463 logDispatchStateLocked();
3464#endif
3465 } // release lock
3466
3467 // Wake up poll loop since it may need to make new input dispatching choices.
3468 mLooper->wake();
3469 return true;
3470}
3471
3472void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
3473#if DEBUG_FOCUS
3474 ALOGD("Resetting and dropping all events (%s).", reason);
3475#endif
3476
3477 CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
3478 synthesizeCancelationEventsForAllConnectionsLocked(options);
3479
3480 resetKeyRepeatLocked();
3481 releasePendingEventLocked();
3482 drainInboundQueueLocked();
3483 resetANRTimeoutsLocked();
3484
Jeff Brownf086ddb2014-02-11 14:28:48 -08003485 mTouchStatesByDisplay.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 mLastHoverWindowHandle.clear();
Michael Wright78f24442014-08-06 15:55:28 -07003487 mReplacedKeys.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488}
3489
3490void InputDispatcher::logDispatchStateLocked() {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003491 std::string dump;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492 dumpDispatchStateLocked(dump);
3493
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003494 std::istringstream stream(dump);
3495 std::string line;
3496
3497 while (std::getline(stream, line, '\n')) {
3498 ALOGD("%s", line.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499 }
3500}
3501
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003502void InputDispatcher::dumpDispatchStateLocked(std::string& dump) {
3503 dump += StringPrintf(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
3504 dump += StringPrintf(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
Tiger Huang721e26f2018-07-24 22:26:19 +08003505 dump += StringPrintf(INDENT "FocusedDisplayId: %" PRId32 "\n", mFocusedDisplayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506
Tiger Huang721e26f2018-07-24 22:26:19 +08003507 if (!mFocusedApplicationHandlesByDisplay.empty()) {
3508 dump += StringPrintf(INDENT "FocusedApplications:\n");
3509 for (auto& it : mFocusedApplicationHandlesByDisplay) {
3510 const int32_t displayId = it.first;
3511 const sp<InputApplicationHandle>& applicationHandle = it.second;
3512 dump += StringPrintf(
3513 INDENT2 "displayId=%" PRId32 ", name='%s', dispatchingTimeout=%0.3fms\n",
3514 displayId,
3515 applicationHandle->getName().c_str(),
3516 applicationHandle->getDispatchingTimeout(
3517 DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
3518 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519 } else {
Tiger Huang721e26f2018-07-24 22:26:19 +08003520 dump += StringPrintf(INDENT "FocusedApplications: <none>\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521 }
Tiger Huang721e26f2018-07-24 22:26:19 +08003522
3523 if (!mFocusedWindowHandlesByDisplay.empty()) {
3524 dump += StringPrintf(INDENT "FocusedWindows:\n");
3525 for (auto& it : mFocusedWindowHandlesByDisplay) {
3526 const int32_t displayId = it.first;
3527 const sp<InputWindowHandle>& windowHandle = it.second;
3528 dump += StringPrintf(INDENT2 "displayId=%" PRId32 ", name='%s'\n",
3529 displayId, windowHandle->getName().c_str());
3530 }
3531 } else {
3532 dump += StringPrintf(INDENT "FocusedWindows: <none>\n");
3533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534
Jeff Brownf086ddb2014-02-11 14:28:48 -08003535 if (!mTouchStatesByDisplay.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003536 dump += StringPrintf(INDENT "TouchStatesByDisplay:\n");
Jeff Brownf086ddb2014-02-11 14:28:48 -08003537 for (size_t i = 0; i < mTouchStatesByDisplay.size(); i++) {
3538 const TouchState& state = mTouchStatesByDisplay.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003539 dump += StringPrintf(INDENT2 "%d: down=%s, split=%s, deviceId=%d, source=0x%08x\n",
Jeff Brownf086ddb2014-02-11 14:28:48 -08003540 state.displayId, toString(state.down), toString(state.split),
3541 state.deviceId, state.source);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003542 if (!state.windows.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003543 dump += INDENT3 "Windows:\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003544 for (size_t i = 0; i < state.windows.size(); i++) {
3545 const TouchedWindow& touchedWindow = state.windows[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003546 dump += StringPrintf(INDENT4 "%zu: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
3547 i, touchedWindow.windowHandle->getName().c_str(),
Jeff Brownf086ddb2014-02-11 14:28:48 -08003548 touchedWindow.pointerIds.value,
3549 touchedWindow.targetFlags);
3550 }
3551 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003552 dump += INDENT3 "Windows: <none>\n";
Jeff Brownf086ddb2014-02-11 14:28:48 -08003553 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003554 if (!state.portalWindows.empty()) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003555 dump += INDENT3 "Portal windows:\n";
3556 for (size_t i = 0; i < state.portalWindows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003557 const sp<InputWindowHandle> portalWindowHandle = state.portalWindows[i];
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003558 dump += StringPrintf(INDENT4 "%zu: name='%s'\n",
3559 i, portalWindowHandle->getName().c_str());
3560 }
3561 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562 }
3563 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003564 dump += INDENT "TouchStates: <no displays touched>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 }
3566
Arthur Hungb92218b2018-08-14 12:00:21 +08003567 if (!mWindowHandlesByDisplay.empty()) {
3568 for (auto& it : mWindowHandlesByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003569 const std::vector<sp<InputWindowHandle>> windowHandles = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003570 dump += StringPrintf(INDENT "Display: %" PRId32 "\n", it.first);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003571 if (!windowHandles.empty()) {
Arthur Hungb92218b2018-08-14 12:00:21 +08003572 dump += INDENT2 "Windows:\n";
3573 for (size_t i = 0; i < windowHandles.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003574 const sp<InputWindowHandle>& windowHandle = windowHandles[i];
Arthur Hungb92218b2018-08-14 12:00:21 +08003575 const InputWindowInfo* windowInfo = windowHandle->getInfo();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003576
Arthur Hungb92218b2018-08-14 12:00:21 +08003577 dump += StringPrintf(INDENT3 "%zu: name='%s', displayId=%d, "
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003578 "portalToDisplayId=%d, paused=%s, hasFocus=%s, hasWallpaper=%s, "
Arthur Hungb92218b2018-08-14 12:00:21 +08003579 "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
Riddle Hsu39d4aa52018-11-30 20:46:53 +08003580 "frame=[%d,%d][%d,%d], globalScale=%f, windowScale=(%f,%f), "
Arthur Hungb92218b2018-08-14 12:00:21 +08003581 "touchableRegion=",
3582 i, windowInfo->name.c_str(), windowInfo->displayId,
Tiger Huang85b8c5e2019-01-17 18:34:54 +08003583 windowInfo->portalToDisplayId,
Arthur Hungb92218b2018-08-14 12:00:21 +08003584 toString(windowInfo->paused),
3585 toString(windowInfo->hasFocus),
3586 toString(windowInfo->hasWallpaper),
3587 toString(windowInfo->visible),
3588 toString(windowInfo->canReceiveKeys),
3589 windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
3590 windowInfo->layer,
3591 windowInfo->frameLeft, windowInfo->frameTop,
3592 windowInfo->frameRight, windowInfo->frameBottom,
Robert Carre07e1032018-11-26 12:55:53 -08003593 windowInfo->globalScaleFactor,
3594 windowInfo->windowXScale, windowInfo->windowYScale);
Arthur Hungb92218b2018-08-14 12:00:21 +08003595 dumpRegion(dump, windowInfo->touchableRegion);
3596 dump += StringPrintf(", inputFeatures=0x%08x", windowInfo->inputFeatures);
3597 dump += StringPrintf(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
3598 windowInfo->ownerPid, windowInfo->ownerUid,
3599 windowInfo->dispatchingTimeout / 1000000.0);
3600 }
3601 } else {
3602 dump += INDENT2 "Windows: <none>\n";
3603 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 }
3605 } else {
Arthur Hungb92218b2018-08-14 12:00:21 +08003606 dump += INDENT "Displays: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003607 }
3608
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003609 if (!mMonitoringChannelsByDisplay.empty()) {
3610 for (auto& it : mMonitoringChannelsByDisplay) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003611 const std::vector<sp<InputChannel>>& monitoringChannels = it.second;
Arthur Hung3b413f22018-10-26 18:05:34 +08003612 dump += StringPrintf(INDENT "MonitoringChannels in display %" PRId32 ":\n", it.first);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003613 const size_t numChannels = monitoringChannels.size();
3614 for (size_t i = 0; i < numChannels; i++) {
3615 const sp<InputChannel>& channel = monitoringChannels[i];
3616 dump += StringPrintf(INDENT2 "%zu: '%s'\n", i, channel->getName().c_str());
3617 }
3618 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003620 dump += INDENT "MonitoringChannels: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003621 }
3622
3623 nsecs_t currentTime = now();
3624
3625 // Dump recently dispatched or dropped events from oldest to newest.
3626 if (!mRecentQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003627 dump += StringPrintf(INDENT "RecentQueue: length=%u\n", mRecentQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 for (EventEntry* entry = mRecentQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003629 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003630 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003631 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003632 (currentTime - entry->eventTime) * 0.000001f);
3633 }
3634 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003635 dump += INDENT "RecentQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 }
3637
3638 // Dump event currently being dispatched.
3639 if (mPendingEvent) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003640 dump += INDENT "PendingEvent:\n";
3641 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 mPendingEvent->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003643 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 (currentTime - mPendingEvent->eventTime) * 0.000001f);
3645 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003646 dump += INDENT "PendingEvent: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003647 }
3648
3649 // Dump inbound events from oldest to newest.
3650 if (!mInboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003651 dump += StringPrintf(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003652 for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003653 dump += INDENT2;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003654 entry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003655 dump += StringPrintf(", age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656 (currentTime - entry->eventTime) * 0.000001f);
3657 }
3658 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003659 dump += INDENT "InboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 }
3661
Michael Wright78f24442014-08-06 15:55:28 -07003662 if (!mReplacedKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003663 dump += INDENT "ReplacedKeys:\n";
Michael Wright78f24442014-08-06 15:55:28 -07003664 for (size_t i = 0; i < mReplacedKeys.size(); i++) {
3665 const KeyReplacement& replacement = mReplacedKeys.keyAt(i);
3666 int32_t newKeyCode = mReplacedKeys.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003667 dump += StringPrintf(INDENT2 "%zu: originalKeyCode=%d, deviceId=%d, newKeyCode=%d\n",
Michael Wright78f24442014-08-06 15:55:28 -07003668 i, replacement.keyCode, replacement.deviceId, newKeyCode);
3669 }
3670 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003671 dump += INDENT "ReplacedKeys: <empty>\n";
Michael Wright78f24442014-08-06 15:55:28 -07003672 }
3673
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 if (!mConnectionsByFd.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003675 dump += INDENT "Connections:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003676 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3677 const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003678 dump += StringPrintf(INDENT2 "%zu: channelName='%s', windowName='%s', "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003679 "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003680 i, connection->getInputChannelName().c_str(),
3681 connection->getWindowName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003682 connection->getStatusLabel(), toString(connection->monitor),
3683 toString(connection->inputPublisherBlocked));
3684
3685 if (!connection->outboundQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003686 dump += StringPrintf(INDENT3 "OutboundQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003687 connection->outboundQueue.count());
3688 for (DispatchEntry* entry = connection->outboundQueue.head; entry;
3689 entry = entry->next) {
3690 dump.append(INDENT4);
3691 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003692 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003693 entry->targetFlags, entry->resolvedAction,
3694 (currentTime - entry->eventEntry->eventTime) * 0.000001f);
3695 }
3696 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003697 dump += INDENT3 "OutboundQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003698 }
3699
3700 if (!connection->waitQueue.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003701 dump += StringPrintf(INDENT3 "WaitQueue: length=%u\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003702 connection->waitQueue.count());
3703 for (DispatchEntry* entry = connection->waitQueue.head; entry;
3704 entry = entry->next) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003705 dump += INDENT4;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 entry->eventEntry->appendDescription(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003707 dump += StringPrintf(", targetFlags=0x%08x, resolvedAction=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003708 "age=%0.1fms, wait=%0.1fms\n",
3709 entry->targetFlags, entry->resolvedAction,
3710 (currentTime - entry->eventEntry->eventTime) * 0.000001f,
3711 (currentTime - entry->deliveryTime) * 0.000001f);
3712 }
3713 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003714 dump += INDENT3 "WaitQueue: <empty>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 }
3716 }
3717 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003718 dump += INDENT "Connections: <none>\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003719 }
3720
3721 if (isAppSwitchPendingLocked()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003722 dump += StringPrintf(INDENT "AppSwitch: pending, due in %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 (mAppSwitchDueTime - now()) / 1000000.0);
3724 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003725 dump += INDENT "AppSwitch: not pending\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003726 }
3727
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003728 dump += INDENT "Configuration:\n";
3729 dump += StringPrintf(INDENT2 "KeyRepeatDelay: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 mConfig.keyRepeatDelay * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003731 dump += StringPrintf(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003732 mConfig.keyRepeatTimeout * 0.000001f);
3733}
3734
Robert Carr803535b2018-08-02 16:38:15 -07003735status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, int32_t displayId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003736#if DEBUG_REGISTRATION
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003737 ALOGD("channel '%s' ~ registerInputChannel - displayId=%" PRId32,
3738 inputChannel->getName().c_str(), displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739#endif
3740
3741 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003742 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003743
Robert Carr4e670e52018-08-15 13:26:12 -07003744 // If InputWindowHandle is null and displayId is not ADISPLAY_ID_NONE,
3745 // treat inputChannel as monitor channel for displayId.
3746 bool monitor = inputChannel->getToken() == nullptr && displayId != ADISPLAY_ID_NONE;
3747 if (monitor) {
3748 inputChannel->setToken(new BBinder());
3749 }
3750
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 if (getConnectionIndexLocked(inputChannel) >= 0) {
3752 ALOGW("Attempted to register already registered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003753 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 return BAD_VALUE;
3755 }
3756
Robert Carr803535b2018-08-02 16:38:15 -07003757 sp<Connection> connection = new Connection(inputChannel, monitor);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758
3759 int fd = inputChannel->getFd();
3760 mConnectionsByFd.add(fd, connection);
Robert Carr5c8a0262018-10-03 16:30:44 -07003761 mInputChannelsByToken[inputChannel->getToken()] = inputChannel;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003763 // Store monitor channel by displayId.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003764 if (monitor) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003765 std::vector<sp<InputChannel>>& monitoringChannels =
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003766 mMonitoringChannelsByDisplay[displayId];
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003767 monitoringChannels.push_back(inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003768 }
3769
3770 mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
3771 } // release lock
3772
3773 // Wake the looper because some connections have changed.
3774 mLooper->wake();
3775 return OK;
3776}
3777
3778status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
3779#if DEBUG_REGISTRATION
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003780 ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003781#endif
3782
3783 { // acquire lock
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08003784 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003785
3786 status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
3787 if (status) {
3788 return status;
3789 }
3790 } // release lock
3791
3792 // Wake the poll loop because removing the connection may have changed the current
3793 // synchronization state.
3794 mLooper->wake();
3795 return OK;
3796}
3797
3798status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
3799 bool notify) {
3800 ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
3801 if (connectionIndex < 0) {
3802 ALOGW("Attempted to unregister already unregistered input channel '%s'",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003803 inputChannel->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003804 return BAD_VALUE;
3805 }
3806
3807 sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
3808 mConnectionsByFd.removeItemsAt(connectionIndex);
3809
Robert Carr5c8a0262018-10-03 16:30:44 -07003810 mInputChannelsByToken.erase(inputChannel->getToken());
3811
Michael Wrightd02c5b62014-02-10 15:10:22 -08003812 if (connection->monitor) {
3813 removeMonitorChannelLocked(inputChannel);
3814 }
3815
3816 mLooper->removeFd(inputChannel->getFd());
3817
3818 nsecs_t currentTime = now();
3819 abortBrokenDispatchCycleLocked(currentTime, connection, notify);
3820
3821 connection->status = Connection::STATUS_ZOMBIE;
3822 return OK;
3823}
3824
3825void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003826 for (auto it = mMonitoringChannelsByDisplay.begin();
3827 it != mMonitoringChannelsByDisplay.end(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003828 std::vector<sp<InputChannel>>& monitoringChannels = it->second;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003829 const size_t numChannels = monitoringChannels.size();
3830 for (size_t i = 0; i < numChannels; i++) {
3831 if (monitoringChannels[i] == inputChannel) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003832 monitoringChannels.erase(monitoringChannels.begin() + i);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003833 break;
3834 }
3835 }
3836 if (monitoringChannels.empty()) {
3837 it = mMonitoringChannelsByDisplay.erase(it);
3838 } else {
3839 ++it;
3840 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003841 }
3842}
3843
3844ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
Robert Carr4e670e52018-08-15 13:26:12 -07003845 if (inputChannel == nullptr) {
Arthur Hung3b413f22018-10-26 18:05:34 +08003846 return -1;
3847 }
3848
Robert Carr4e670e52018-08-15 13:26:12 -07003849 for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
3850 sp<Connection> connection = mConnectionsByFd.valueAt(i);
3851 if (connection->inputChannel->getToken() == inputChannel->getToken()) {
3852 return i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853 }
3854 }
Robert Carr4e670e52018-08-15 13:26:12 -07003855
Michael Wrightd02c5b62014-02-10 15:10:22 -08003856 return -1;
3857}
3858
3859void InputDispatcher::onDispatchCycleFinishedLocked(
3860 nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
3861 CommandEntry* commandEntry = postCommandLocked(
3862 & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
3863 commandEntry->connection = connection;
3864 commandEntry->eventTime = currentTime;
3865 commandEntry->seq = seq;
3866 commandEntry->handled = handled;
3867}
3868
3869void InputDispatcher::onDispatchCycleBrokenLocked(
3870 nsecs_t currentTime, const sp<Connection>& connection) {
3871 ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08003872 connection->getInputChannelName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873
3874 CommandEntry* commandEntry = postCommandLocked(
3875 & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
3876 commandEntry->connection = connection;
3877}
3878
chaviw0c06c6e2019-01-09 13:27:07 -08003879void InputDispatcher::onFocusChangedLocked(const sp<InputWindowHandle>& oldFocus,
3880 const sp<InputWindowHandle>& newFocus) {
3881 sp<IBinder> oldToken = oldFocus != nullptr ? oldFocus->getToken() : nullptr;
3882 sp<IBinder> newToken = newFocus != nullptr ? newFocus->getToken() : nullptr;
Robert Carrf759f162018-11-13 12:57:11 -08003883 CommandEntry* commandEntry = postCommandLocked(
3884 & InputDispatcher::doNotifyFocusChangedLockedInterruptible);
chaviw0c06c6e2019-01-09 13:27:07 -08003885 commandEntry->oldToken = oldToken;
3886 commandEntry->newToken = newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003887}
3888
Michael Wrightd02c5b62014-02-10 15:10:22 -08003889void InputDispatcher::onANRLocked(
3890 nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
3891 const sp<InputWindowHandle>& windowHandle,
3892 nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
3893 float dispatchLatency = (currentTime - eventTime) * 0.000001f;
3894 float waitDuration = (currentTime - waitStartTime) * 0.000001f;
3895 ALOGI("Application is not responding: %s. "
3896 "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003897 getApplicationWindowLabel(applicationHandle, windowHandle).c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 dispatchLatency, waitDuration, reason);
3899
3900 // Capture a record of the InputDispatcher state at the time of the ANR.
Yi Kong9b14ac62018-07-17 13:48:38 -07003901 time_t t = time(nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003902 struct tm tm;
3903 localtime_r(&t, &tm);
3904 char timestr[64];
3905 strftime(timestr, sizeof(timestr), "%F %T", &tm);
3906 mLastANRState.clear();
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003907 mLastANRState += INDENT "ANR:\n";
3908 mLastANRState += StringPrintf(INDENT2 "Time: %s\n", timestr);
3909 mLastANRState += StringPrintf(INDENT2 "Window: %s\n",
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003910 getApplicationWindowLabel(applicationHandle, windowHandle).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003911 mLastANRState += StringPrintf(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
3912 mLastANRState += StringPrintf(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
3913 mLastANRState += StringPrintf(INDENT2 "Reason: %s\n", reason);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914 dumpDispatchStateLocked(mLastANRState);
3915
3916 CommandEntry* commandEntry = postCommandLocked(
3917 & InputDispatcher::doNotifyANRLockedInterruptible);
3918 commandEntry->inputApplicationHandle = applicationHandle;
Robert Carr5c8a0262018-10-03 16:30:44 -07003919 commandEntry->inputChannel = windowHandle != nullptr ?
3920 getInputChannelLocked(windowHandle->getToken()) : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921 commandEntry->reason = reason;
3922}
3923
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08003924void InputDispatcher::doNotifyConfigurationChangedLockedInterruptible (
Michael Wrightd02c5b62014-02-10 15:10:22 -08003925 CommandEntry* commandEntry) {
3926 mLock.unlock();
3927
3928 mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
3929
3930 mLock.lock();
3931}
3932
3933void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
3934 CommandEntry* commandEntry) {
3935 sp<Connection> connection = commandEntry->connection;
3936
3937 if (connection->status != Connection::STATUS_ZOMBIE) {
3938 mLock.unlock();
3939
Robert Carr803535b2018-08-02 16:38:15 -07003940 mPolicy->notifyInputChannelBroken(connection->inputChannel->getToken());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941
3942 mLock.lock();
3943 }
3944}
3945
Robert Carrf759f162018-11-13 12:57:11 -08003946void InputDispatcher::doNotifyFocusChangedLockedInterruptible(
3947 CommandEntry* commandEntry) {
chaviw0c06c6e2019-01-09 13:27:07 -08003948 sp<IBinder> oldToken = commandEntry->oldToken;
3949 sp<IBinder> newToken = commandEntry->newToken;
Robert Carrf759f162018-11-13 12:57:11 -08003950 mLock.unlock();
chaviw0c06c6e2019-01-09 13:27:07 -08003951 mPolicy->notifyFocusChanged(oldToken, newToken);
Robert Carrf759f162018-11-13 12:57:11 -08003952 mLock.lock();
3953}
3954
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955void InputDispatcher::doNotifyANRLockedInterruptible(
3956 CommandEntry* commandEntry) {
3957 mLock.unlock();
3958
3959 nsecs_t newTimeout = mPolicy->notifyANR(
Robert Carr803535b2018-08-02 16:38:15 -07003960 commandEntry->inputApplicationHandle,
3961 commandEntry->inputChannel ? commandEntry->inputChannel->getToken() : nullptr,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962 commandEntry->reason);
3963
3964 mLock.lock();
3965
3966 resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
Robert Carr803535b2018-08-02 16:38:15 -07003967 commandEntry->inputChannel);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968}
3969
3970void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
3971 CommandEntry* commandEntry) {
3972 KeyEntry* entry = commandEntry->keyEntry;
3973
3974 KeyEvent event;
3975 initializeKeyEvent(&event, entry);
3976
3977 mLock.unlock();
3978
Michael Wright2b3c3302018-03-02 17:19:13 +00003979 android::base::Timer t;
Robert Carr803535b2018-08-02 16:38:15 -07003980 sp<IBinder> token = commandEntry->inputChannel != nullptr ?
3981 commandEntry->inputChannel->getToken() : nullptr;
3982 nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(token,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 &event, entry->policyFlags);
Michael Wright2b3c3302018-03-02 17:19:13 +00003984 if (t.duration() > SLOW_INTERCEPTION_THRESHOLD) {
3985 ALOGW("Excessive delay in interceptKeyBeforeDispatching; took %s ms",
3986 std::to_string(t.duration().count()).c_str());
3987 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003988
3989 mLock.lock();
3990
3991 if (delay < 0) {
3992 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
3993 } else if (!delay) {
3994 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
3995 } else {
3996 entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
3997 entry->interceptKeyWakeupTime = now() + delay;
3998 }
3999 entry->release();
4000}
4001
4002void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
4003 CommandEntry* commandEntry) {
4004 sp<Connection> connection = commandEntry->connection;
4005 nsecs_t finishTime = commandEntry->eventTime;
4006 uint32_t seq = commandEntry->seq;
4007 bool handled = commandEntry->handled;
4008
4009 // Handle post-event policy actions.
4010 DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
4011 if (dispatchEntry) {
4012 nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
4013 if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004014 std::string msg =
4015 StringPrintf("Window '%s' spent %0.1fms processing the last input event: ",
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004016 connection->getWindowName().c_str(), eventDuration * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004017 dispatchEntry->eventEntry->appendDescription(msg);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004018 ALOGI("%s", msg.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004019 }
4020
4021 bool restartEvent;
4022 if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
4023 KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
4024 restartEvent = afterKeyEventLockedInterruptible(connection,
4025 dispatchEntry, keyEntry, handled);
4026 } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
4027 MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
4028 restartEvent = afterMotionEventLockedInterruptible(connection,
4029 dispatchEntry, motionEntry, handled);
4030 } else {
4031 restartEvent = false;
4032 }
4033
4034 // Dequeue the event and start the next cycle.
4035 // Note that because the lock might have been released, it is possible that the
4036 // contents of the wait queue to have been drained, so we need to double-check
4037 // a few things.
4038 if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
4039 connection->waitQueue.dequeue(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004040 traceWaitQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004041 if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
4042 connection->outboundQueue.enqueueAtHead(dispatchEntry);
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004043 traceOutboundQueueLength(connection);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004044 } else {
Siarhei Vishniakou62683e82019-03-06 17:59:56 -08004045 releaseDispatchEntry(dispatchEntry);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046 }
4047 }
4048
4049 // Start the next dispatch cycle for this connection.
4050 startDispatchCycleLocked(now(), connection);
4051 }
4052}
4053
4054bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
4055 DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004056 if (keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK) {
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004057 if (!handled) {
4058 // Report the key as unhandled, since the fallback was not handled.
4059 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
4060 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004061 return false;
4062 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004063
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004064 // Get the fallback key state.
4065 // Clear it out after dispatching the UP.
4066 int32_t originalKeyCode = keyEntry->keyCode;
4067 int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
4068 if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
4069 connection->inputState.removeFallbackKey(originalKeyCode);
4070 }
4071
4072 if (handled || !dispatchEntry->hasForegroundTarget()) {
4073 // If the application handles the original key for which we previously
4074 // generated a fallback or if the window is not a foreground window,
4075 // then cancel the associated fallback key, if any.
4076 if (fallbackKeyCode != -1) {
4077 // Dispatch the unhandled key to the policy with the cancel flag.
Michael Wrightd02c5b62014-02-10 15:10:22 -08004078#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004079 ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004080 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4081 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4082 keyEntry->policyFlags);
4083#endif
4084 KeyEvent event;
4085 initializeKeyEvent(&event, keyEntry);
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004086 event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004087
4088 mLock.unlock();
4089
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004090 mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4091 &event, keyEntry->policyFlags, &event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004092
4093 mLock.lock();
4094
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004095 // Cancel the fallback key.
4096 if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004098 "application handled the original non-fallback key "
4099 "or is no longer a foreground target, "
4100 "canceling previously dispatched fallback key");
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101 options.keyCode = fallbackKeyCode;
4102 synthesizeCancelationEventsForConnectionLocked(connection, options);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004104 connection->inputState.removeFallbackKey(originalKeyCode);
4105 }
4106 } else {
4107 // If the application did not handle a non-fallback key, first check
4108 // that we are in a good state to perform unhandled key event processing
4109 // Then ask the policy what to do with it.
4110 bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
4111 && keyEntry->repeatCount == 0;
4112 if (fallbackKeyCode == -1 && !initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004113#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004114 ALOGD("Unhandled key event: Skipping unhandled key event processing "
4115 "since this is not an initial down. "
4116 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4117 originalKeyCode, keyEntry->action, keyEntry->repeatCount,
4118 keyEntry->policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119#endif
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004120 return false;
4121 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004123 // Dispatch the unhandled key to the policy.
4124#if DEBUG_OUTBOUND_EVENT_DETAILS
4125 ALOGD("Unhandled key event: Asking policy to perform fallback action. "
4126 "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
4127 keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
4128 keyEntry->policyFlags);
4129#endif
4130 KeyEvent event;
4131 initializeKeyEvent(&event, keyEntry);
4132
4133 mLock.unlock();
4134
4135 bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel->getToken(),
4136 &event, keyEntry->policyFlags, &event);
4137
4138 mLock.lock();
4139
4140 if (connection->status != Connection::STATUS_NORMAL) {
4141 connection->inputState.removeFallbackKey(originalKeyCode);
4142 return false;
4143 }
4144
4145 // Latch the fallback keycode for this key on an initial down.
4146 // The fallback keycode cannot change at any other point in the lifecycle.
4147 if (initialDown) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 if (fallback) {
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004149 fallbackKeyCode = event.getKeyCode();
4150 } else {
4151 fallbackKeyCode = AKEYCODE_UNKNOWN;
4152 }
4153 connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
4154 }
4155
4156 ALOG_ASSERT(fallbackKeyCode != -1);
4157
4158 // Cancel the fallback key if the policy decides not to send it anymore.
4159 // We will continue to dispatch the key to the policy but we will no
4160 // longer dispatch a fallback key to the application.
4161 if (fallbackKeyCode != AKEYCODE_UNKNOWN
4162 && (!fallback || fallbackKeyCode != event.getKeyCode())) {
4163#if DEBUG_OUTBOUND_EVENT_DETAILS
4164 if (fallback) {
4165 ALOGD("Unhandled key event: Policy requested to send key %d"
4166 "as a fallback for %d, but on the DOWN it had requested "
4167 "to send %d instead. Fallback canceled.",
4168 event.getKeyCode(), originalKeyCode, fallbackKeyCode);
4169 } else {
4170 ALOGD("Unhandled key event: Policy did not request fallback for %d, "
4171 "but on the DOWN it had requested to send %d. "
4172 "Fallback canceled.",
4173 originalKeyCode, fallbackKeyCode);
4174 }
4175#endif
4176
4177 CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
4178 "canceling fallback, policy no longer desires it");
4179 options.keyCode = fallbackKeyCode;
4180 synthesizeCancelationEventsForConnectionLocked(connection, options);
4181
4182 fallback = false;
4183 fallbackKeyCode = AKEYCODE_UNKNOWN;
4184 if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
4185 connection->inputState.setFallbackKey(originalKeyCode,
4186 fallbackKeyCode);
4187 }
4188 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189
4190#if DEBUG_OUTBOUND_EVENT_DETAILS
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004191 {
4192 std::string msg;
4193 const KeyedVector<int32_t, int32_t>& fallbackKeys =
4194 connection->inputState.getFallbackKeys();
4195 for (size_t i = 0; i < fallbackKeys.size(); i++) {
4196 msg += StringPrintf(", %d->%d", fallbackKeys.keyAt(i),
4197 fallbackKeys.valueAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 }
Prabir Pradhanf557dcf2018-12-18 16:38:14 -08004199 ALOGD("Unhandled key event: %zu currently tracked fallback keys%s.",
4200 fallbackKeys.size(), msg.c_str());
4201 }
4202#endif
4203
4204 if (fallback) {
4205 // Restart the dispatch cycle using the fallback key.
4206 keyEntry->eventTime = event.getEventTime();
4207 keyEntry->deviceId = event.getDeviceId();
4208 keyEntry->source = event.getSource();
4209 keyEntry->displayId = event.getDisplayId();
4210 keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
4211 keyEntry->keyCode = fallbackKeyCode;
4212 keyEntry->scanCode = event.getScanCode();
4213 keyEntry->metaState = event.getMetaState();
4214 keyEntry->repeatCount = event.getRepeatCount();
4215 keyEntry->downTime = event.getDownTime();
4216 keyEntry->syntheticRepeat = false;
4217
4218#if DEBUG_OUTBOUND_EVENT_DETAILS
4219 ALOGD("Unhandled key event: Dispatching fallback key. "
4220 "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
4221 originalKeyCode, fallbackKeyCode, keyEntry->metaState);
4222#endif
4223 return true; // restart the event
4224 } else {
4225#if DEBUG_OUTBOUND_EVENT_DETAILS
4226 ALOGD("Unhandled key event: No fallback key.");
4227#endif
Prabir Pradhanf93562f2018-11-29 12:13:37 -08004228
4229 // Report the key as unhandled, since there is no fallback key.
4230 mReporter->reportUnhandledKey(keyEntry->sequenceNum);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 }
4232 }
4233 return false;
4234}
4235
4236bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
4237 DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
4238 return false;
4239}
4240
4241void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
4242 mLock.unlock();
4243
4244 mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
4245
4246 mLock.lock();
4247}
4248
4249void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004250 event->initialize(entry->deviceId, entry->source, entry->displayId, entry->action, entry->flags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
4252 entry->downTime, entry->eventTime);
4253}
4254
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004255void InputDispatcher::updateDispatchStatistics(nsecs_t currentTime, const EventEntry* entry,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
4257 // TODO Write some statistics about how long we spend waiting.
4258}
4259
4260void InputDispatcher::traceInboundQueueLengthLocked() {
4261 if (ATRACE_ENABLED()) {
4262 ATRACE_INT("iq", mInboundQueue.count());
4263 }
4264}
4265
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004266void InputDispatcher::traceOutboundQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 if (ATRACE_ENABLED()) {
4268 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004269 snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 ATRACE_INT(counterName, connection->outboundQueue.count());
4271 }
4272}
4273
Siarhei Vishniakou61291d42019-02-11 18:13:20 -08004274void InputDispatcher::traceWaitQueueLength(const sp<Connection>& connection) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 if (ATRACE_ENABLED()) {
4276 char counterName[40];
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004277 snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 ATRACE_INT(counterName, connection->waitQueue.count());
4279 }
4280}
4281
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004282void InputDispatcher::dump(std::string& dump) {
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004283 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004285 dump += "Input Dispatcher State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 dumpDispatchStateLocked(dump);
4287
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004288 if (!mLastANRState.empty()) {
4289 dump += "\nInput Dispatcher State at time of last ANR:\n";
4290 dump += mLastANRState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 }
4292}
4293
4294void InputDispatcher::monitor() {
4295 // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004296 std::unique_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 mLooper->wake();
Siarhei Vishniakou443ad902019-03-06 17:25:41 -08004298 mDispatcherIsAlive.wait(_l);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299}
4300
4301
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302// --- InputDispatcher::InjectionState ---
4303
4304InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
4305 refCount(1),
4306 injectorPid(injectorPid), injectorUid(injectorUid),
4307 injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
4308 pendingForegroundDispatches(0) {
4309}
4310
4311InputDispatcher::InjectionState::~InjectionState() {
4312}
4313
4314void InputDispatcher::InjectionState::release() {
4315 refCount -= 1;
4316 if (refCount == 0) {
4317 delete this;
4318 } else {
4319 ALOG_ASSERT(refCount > 0);
4320 }
4321}
4322
4323
4324// --- InputDispatcher::EventEntry ---
4325
Prabir Pradhan42611e02018-11-27 14:04:02 -08004326InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
4327 nsecs_t eventTime, uint32_t policyFlags) :
4328 sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
4329 policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330}
4331
4332InputDispatcher::EventEntry::~EventEntry() {
4333 releaseInjectionState();
4334}
4335
4336void InputDispatcher::EventEntry::release() {
4337 refCount -= 1;
4338 if (refCount == 0) {
4339 delete this;
4340 } else {
4341 ALOG_ASSERT(refCount > 0);
4342 }
4343}
4344
4345void InputDispatcher::EventEntry::releaseInjectionState() {
4346 if (injectionState) {
4347 injectionState->release();
Yi Kong9b14ac62018-07-17 13:48:38 -07004348 injectionState = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 }
4350}
4351
4352
4353// --- InputDispatcher::ConfigurationChangedEntry ---
4354
Prabir Pradhan42611e02018-11-27 14:04:02 -08004355InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
4356 uint32_t sequenceNum, nsecs_t eventTime) :
4357 EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358}
4359
4360InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
4361}
4362
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004363void InputDispatcher::ConfigurationChangedEntry::appendDescription(std::string& msg) const {
4364 msg += StringPrintf("ConfigurationChangedEvent(), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004365}
4366
4367
4368// --- InputDispatcher::DeviceResetEntry ---
4369
Prabir Pradhan42611e02018-11-27 14:04:02 -08004370InputDispatcher::DeviceResetEntry::DeviceResetEntry(
4371 uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
4372 EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004373 deviceId(deviceId) {
4374}
4375
4376InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
4377}
4378
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004379void InputDispatcher::DeviceResetEntry::appendDescription(std::string& msg) const {
4380 msg += StringPrintf("DeviceResetEvent(deviceId=%d), policyFlags=0x%08x",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 deviceId, policyFlags);
4382}
4383
4384
4385// --- InputDispatcher::KeyEntry ---
4386
Prabir Pradhan42611e02018-11-27 14:04:02 -08004387InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004388 int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389 int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
4390 int32_t repeatCount, nsecs_t downTime) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004391 EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004392 deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 keyCode(keyCode), scanCode(scanCode), metaState(metaState),
4394 repeatCount(repeatCount), downTime(downTime),
4395 syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
4396 interceptKeyWakeupTime(0) {
4397}
4398
4399InputDispatcher::KeyEntry::~KeyEntry() {
4400}
4401
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004402void InputDispatcher::KeyEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004403 msg += StringPrintf("KeyEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32 ", action=%s, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004404 "flags=0x%08x, keyCode=%d, scanCode=%d, metaState=0x%08x, "
4405 "repeatCount=%d), policyFlags=0x%08x",
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004406 deviceId, source, displayId, keyActionToString(action).c_str(), flags, keyCode,
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004407 scanCode, metaState, repeatCount, policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408}
4409
4410void InputDispatcher::KeyEntry::recycle() {
4411 releaseInjectionState();
4412
4413 dispatchInProgress = false;
4414 syntheticRepeat = false;
4415 interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
4416 interceptKeyWakeupTime = 0;
4417}
4418
4419
4420// --- InputDispatcher::MotionEntry ---
4421
Prabir Pradhan42611e02018-11-27 14:04:02 -08004422InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004423 uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
4424 int32_t actionButton,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004425 int32_t flags, int32_t metaState, int32_t buttonState, MotionClassification classification,
4426 int32_t edgeFlags, float xPrecision, float yPrecision, nsecs_t downTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004427 uint32_t pointerCount,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004428 const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
4429 float xOffset, float yOffset) :
Prabir Pradhan42611e02018-11-27 14:04:02 -08004430 EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004431 eventTime(eventTime),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004432 deviceId(deviceId), source(source), displayId(displayId), action(action),
4433 actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004434 classification(classification), edgeFlags(edgeFlags),
4435 xPrecision(xPrecision), yPrecision(yPrecision),
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004436 downTime(downTime), pointerCount(pointerCount) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437 for (uint32_t i = 0; i < pointerCount; i++) {
4438 this->pointerProperties[i].copyFrom(pointerProperties[i]);
4439 this->pointerCoords[i].copyFrom(pointerCoords[i]);
Jeff Brownf086ddb2014-02-11 14:28:48 -08004440 if (xOffset || yOffset) {
4441 this->pointerCoords[i].applyOffset(xOffset, yOffset);
4442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004443 }
4444}
4445
4446InputDispatcher::MotionEntry::~MotionEntry() {
4447}
4448
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004449void InputDispatcher::MotionEntry::appendDescription(std::string& msg) const {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004450 msg += StringPrintf("MotionEvent(deviceId=%d, source=0x%08x, displayId=%" PRId32
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004451 ", action=%s, actionButton=0x%08x, flags=0x%08x, metaState=0x%08x, buttonState=0x%08x, "
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004452 "classification=%s, edgeFlags=0x%08x, xPrecision=%.1f, yPrecision=%.1f, pointers=[",
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004453 deviceId, source, displayId, motionActionToString(action).c_str(), actionButton, flags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004454 metaState, buttonState, motionClassificationToString(classification), edgeFlags,
4455 xPrecision, yPrecision);
Siarhei Vishniakoub48188a2018-03-01 20:55:47 -08004456
Michael Wrightd02c5b62014-02-10 15:10:22 -08004457 for (uint32_t i = 0; i < pointerCount; i++) {
4458 if (i) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004459 msg += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004461 msg += StringPrintf("%d: (%.1f, %.1f)", pointerProperties[i].id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004462 pointerCoords[i].getX(), pointerCoords[i].getY());
4463 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004464 msg += StringPrintf("]), policyFlags=0x%08x", policyFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004465}
4466
4467
4468// --- InputDispatcher::DispatchEntry ---
4469
4470volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
4471
4472InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
Robert Carre07e1032018-11-26 12:55:53 -08004473 int32_t targetFlags, float xOffset, float yOffset, float globalScaleFactor,
4474 float windowXScale, float windowYScale) :
Michael Wrightd02c5b62014-02-10 15:10:22 -08004475 seq(nextSeq()),
4476 eventEntry(eventEntry), targetFlags(targetFlags),
Robert Carre07e1032018-11-26 12:55:53 -08004477 xOffset(xOffset), yOffset(yOffset), globalScaleFactor(globalScaleFactor),
4478 windowXScale(windowXScale), windowYScale(windowYScale),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004479 deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
4480 eventEntry->refCount += 1;
4481}
4482
4483InputDispatcher::DispatchEntry::~DispatchEntry() {
4484 eventEntry->release();
4485}
4486
4487uint32_t InputDispatcher::DispatchEntry::nextSeq() {
4488 // Sequence number 0 is reserved and will never be returned.
4489 uint32_t seq;
4490 do {
4491 seq = android_atomic_inc(&sNextSeqAtomic);
4492 } while (!seq);
4493 return seq;
4494}
4495
4496
4497// --- InputDispatcher::InputState ---
4498
4499InputDispatcher::InputState::InputState() {
4500}
4501
4502InputDispatcher::InputState::~InputState() {
4503}
4504
4505bool InputDispatcher::InputState::isNeutral() const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004506 return mKeyMementos.empty() && mMotionMementos.empty();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507}
4508
4509bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
4510 int32_t displayId) const {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004511 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004512 if (memento.deviceId == deviceId
4513 && memento.source == source
4514 && memento.displayId == displayId
4515 && memento.hovering) {
4516 return true;
4517 }
4518 }
4519 return false;
4520}
4521
4522bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
4523 int32_t action, int32_t flags) {
4524 switch (action) {
4525 case AKEY_EVENT_ACTION_UP: {
4526 if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
4527 for (size_t i = 0; i < mFallbackKeys.size(); ) {
4528 if (mFallbackKeys.valueAt(i) == entry->keyCode) {
4529 mFallbackKeys.removeItemsAt(i);
4530 } else {
4531 i += 1;
4532 }
4533 }
4534 }
4535 ssize_t index = findKeyMemento(entry);
4536 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004537 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538 return true;
4539 }
4540 /* FIXME: We can't just drop the key up event because that prevents creating
4541 * popup windows that are automatically shown when a key is held and then
4542 * dismissed when the key is released. The problem is that the popup will
4543 * not have received the original key down, so the key up will be considered
4544 * to be inconsistent with its observed state. We could perhaps handle this
4545 * by synthesizing a key down but that will cause other problems.
4546 *
4547 * So for now, allow inconsistent key up events to be dispatched.
4548 *
4549#if DEBUG_OUTBOUND_EVENT_DETAILS
4550 ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
4551 "keyCode=%d, scanCode=%d",
4552 entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
4553#endif
4554 return false;
4555 */
4556 return true;
4557 }
4558
4559 case AKEY_EVENT_ACTION_DOWN: {
4560 ssize_t index = findKeyMemento(entry);
4561 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004562 mKeyMementos.erase(mKeyMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004563 }
4564 addKeyMemento(entry, flags);
4565 return true;
4566 }
4567
4568 default:
4569 return true;
4570 }
4571}
4572
4573bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
4574 int32_t action, int32_t flags) {
4575 int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
4576 switch (actionMasked) {
4577 case AMOTION_EVENT_ACTION_UP:
4578 case AMOTION_EVENT_ACTION_CANCEL: {
4579 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4580 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004581 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004582 return true;
4583 }
4584#if DEBUG_OUTBOUND_EVENT_DETAILS
4585 ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004586 "displayId=%" PRId32 ", actionMasked=%d",
4587 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588#endif
4589 return false;
4590 }
4591
4592 case AMOTION_EVENT_ACTION_DOWN: {
4593 ssize_t index = findMotionMemento(entry, false /*hovering*/);
4594 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004595 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 }
4597 addMotionMemento(entry, flags, false /*hovering*/);
4598 return true;
4599 }
4600
4601 case AMOTION_EVENT_ACTION_POINTER_UP:
4602 case AMOTION_EVENT_ACTION_POINTER_DOWN:
4603 case AMOTION_EVENT_ACTION_MOVE: {
Michael Wright38dcdff2014-03-19 12:06:10 -07004604 if (entry->source & AINPUT_SOURCE_CLASS_NAVIGATION) {
4605 // Trackballs can send MOVE events with a corresponding DOWN or UP. There's no need to
4606 // generate cancellation events for these since they're based in relative rather than
4607 // absolute units.
4608 return true;
4609 }
4610
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 ssize_t index = findMotionMemento(entry, false /*hovering*/);
Michael Wright38dcdff2014-03-19 12:06:10 -07004612
4613 if (entry->source & AINPUT_SOURCE_CLASS_JOYSTICK) {
4614 // Joysticks can send MOVE events without a corresponding DOWN or UP. Since all
4615 // joystick axes are normalized to [-1, 1] we can trust that 0 means it's neutral. Any
4616 // other value and we need to track the motion so we can send cancellation events for
4617 // anything generating fallback events (e.g. DPad keys for joystick movements).
4618 if (index >= 0) {
4619 if (entry->pointerCoords[0].isEmpty()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004620 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wright38dcdff2014-03-19 12:06:10 -07004621 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004622 MotionMemento& memento = mMotionMementos[index];
Michael Wright38dcdff2014-03-19 12:06:10 -07004623 memento.setPointers(entry);
4624 }
4625 } else if (!entry->pointerCoords[0].isEmpty()) {
4626 addMotionMemento(entry, flags, false /*hovering*/);
4627 }
4628
4629 // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
4630 return true;
4631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004633 MotionMemento& memento = mMotionMementos[index];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 memento.setPointers(entry);
4635 return true;
4636 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637#if DEBUG_OUTBOUND_EVENT_DETAILS
4638 ALOGD("Dropping inconsistent motion pointer up/down or move event: "
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004639 "deviceId=%d, source=%08x, displayId=%" PRId32 ", actionMasked=%d",
4640 entry->deviceId, entry->source, entry->displayId, actionMasked);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004641#endif
4642 return false;
4643 }
4644
4645 case AMOTION_EVENT_ACTION_HOVER_EXIT: {
4646 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4647 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004648 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004649 return true;
4650 }
4651#if DEBUG_OUTBOUND_EVENT_DETAILS
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004652 ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x, "
4653 "displayId=%" PRId32,
4654 entry->deviceId, entry->source, entry->displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655#endif
4656 return false;
4657 }
4658
4659 case AMOTION_EVENT_ACTION_HOVER_ENTER:
4660 case AMOTION_EVENT_ACTION_HOVER_MOVE: {
4661 ssize_t index = findMotionMemento(entry, true /*hovering*/);
4662 if (index >= 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004663 mMotionMementos.erase(mMotionMementos.begin() + index);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004664 }
4665 addMotionMemento(entry, flags, true /*hovering*/);
4666 return true;
4667 }
4668
4669 default:
4670 return true;
4671 }
4672}
4673
4674ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
4675 for (size_t i = 0; i < mKeyMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004676 const KeyMemento& memento = mKeyMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677 if (memento.deviceId == entry->deviceId
4678 && memento.source == entry->source
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004679 && memento.displayId == entry->displayId
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680 && memento.keyCode == entry->keyCode
4681 && memento.scanCode == entry->scanCode) {
4682 return i;
4683 }
4684 }
4685 return -1;
4686}
4687
4688ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
4689 bool hovering) const {
4690 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004691 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 if (memento.deviceId == entry->deviceId
4693 && memento.source == entry->source
4694 && memento.displayId == entry->displayId
4695 && memento.hovering == hovering) {
4696 return i;
4697 }
4698 }
4699 return -1;
4700}
4701
4702void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004703 KeyMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704 memento.deviceId = entry->deviceId;
4705 memento.source = entry->source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004706 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 memento.keyCode = entry->keyCode;
4708 memento.scanCode = entry->scanCode;
4709 memento.metaState = entry->metaState;
4710 memento.flags = flags;
4711 memento.downTime = entry->downTime;
4712 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004713 mKeyMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714}
4715
4716void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
4717 int32_t flags, bool hovering) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004718 MotionMemento memento;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719 memento.deviceId = entry->deviceId;
4720 memento.source = entry->source;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004721 memento.displayId = entry->displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722 memento.flags = flags;
4723 memento.xPrecision = entry->xPrecision;
4724 memento.yPrecision = entry->yPrecision;
4725 memento.downTime = entry->downTime;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 memento.setPointers(entry);
4727 memento.hovering = hovering;
4728 memento.policyFlags = entry->policyFlags;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004729 mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730}
4731
4732void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
4733 pointerCount = entry->pointerCount;
4734 for (uint32_t i = 0; i < entry->pointerCount; i++) {
4735 pointerProperties[i].copyFrom(entry->pointerProperties[i]);
4736 pointerCoords[i].copyFrom(entry->pointerCoords[i]);
4737 }
4738}
4739
4740void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004741 std::vector<EventEntry*>& outEvents, const CancelationOptions& options) {
4742 for (KeyMemento& memento : mKeyMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 if (shouldCancelKey(memento, options)) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004744 outEvents.push_back(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004745 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746 AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
4747 memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
4748 }
4749 }
4750
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004751 for (const MotionMemento& memento : mMotionMementos) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752 if (shouldCancelMotion(memento, options)) {
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004753 const int32_t action = memento.hovering ?
4754 AMOTION_EVENT_ACTION_HOVER_EXIT : AMOTION_EVENT_ACTION_CANCEL;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004755 outEvents.push_back(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08004756 memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004757 action, 0 /*actionButton*/, memento.flags, AMETA_NONE, 0 /*buttonState*/,
4758 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759 memento.xPrecision, memento.yPrecision, memento.downTime,
Jeff Brownf086ddb2014-02-11 14:28:48 -08004760 memento.pointerCount, memento.pointerProperties, memento.pointerCoords,
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -08004761 0 /*xOffset*/, 0 /*yOffset*/));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762 }
4763 }
4764}
4765
4766void InputDispatcher::InputState::clear() {
4767 mKeyMementos.clear();
4768 mMotionMementos.clear();
4769 mFallbackKeys.clear();
4770}
4771
4772void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
4773 for (size_t i = 0; i < mMotionMementos.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004774 const MotionMemento& memento = mMotionMementos[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
4776 for (size_t j = 0; j < other.mMotionMementos.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004777 const MotionMemento& otherMemento = other.mMotionMementos[j];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004778 if (memento.deviceId == otherMemento.deviceId
4779 && memento.source == otherMemento.source
4780 && memento.displayId == otherMemento.displayId) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004781 other.mMotionMementos.erase(other.mMotionMementos.begin() + j);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 } else {
4783 j += 1;
4784 }
4785 }
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004786 other.mMotionMementos.push_back(memento);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787 }
4788 }
4789}
4790
4791int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
4792 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4793 return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
4794}
4795
4796void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
4797 int32_t fallbackKeyCode) {
4798 ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
4799 if (index >= 0) {
4800 mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
4801 } else {
4802 mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
4803 }
4804}
4805
4806void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
4807 mFallbackKeys.removeItem(originalKeyCode);
4808}
4809
4810bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
4811 const CancelationOptions& options) {
4812 if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
4813 return false;
4814 }
4815
4816 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4817 return false;
4818 }
4819
4820 switch (options.mode) {
4821 case CancelationOptions::CANCEL_ALL_EVENTS:
4822 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4823 return true;
4824 case CancelationOptions::CANCEL_FALLBACK_EVENTS:
4825 return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
Tiger Huang721e26f2018-07-24 22:26:19 +08004826 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4827 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828 default:
4829 return false;
4830 }
4831}
4832
4833bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
4834 const CancelationOptions& options) {
4835 if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
4836 return false;
4837 }
4838
4839 switch (options.mode) {
4840 case CancelationOptions::CANCEL_ALL_EVENTS:
4841 return true;
4842 case CancelationOptions::CANCEL_POINTER_EVENTS:
4843 return memento.source & AINPUT_SOURCE_CLASS_POINTER;
4844 case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
4845 return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
Tiger Huang721e26f2018-07-24 22:26:19 +08004846 case CancelationOptions::CANCEL_DISPLAY_UNSPECIFIED_EVENTS:
4847 return memento.displayId == ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 default:
4849 return false;
4850 }
4851}
4852
4853
4854// --- InputDispatcher::Connection ---
4855
Robert Carr803535b2018-08-02 16:38:15 -07004856InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel, bool monitor) :
4857 status(STATUS_NORMAL), inputChannel(inputChannel),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004858 monitor(monitor),
4859 inputPublisher(inputChannel), inputPublisherBlocked(false) {
4860}
4861
4862InputDispatcher::Connection::~Connection() {
4863}
4864
Siarhei Vishniakou587c3f02018-01-04 11:46:44 -08004865const std::string InputDispatcher::Connection::getWindowName() const {
Robert Carr803535b2018-08-02 16:38:15 -07004866 if (inputChannel != nullptr) {
4867 return inputChannel->getName();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 }
4869 if (monitor) {
4870 return "monitor";
4871 }
4872 return "?";
4873}
4874
4875const char* InputDispatcher::Connection::getStatusLabel() const {
4876 switch (status) {
4877 case STATUS_NORMAL:
4878 return "NORMAL";
4879
4880 case STATUS_BROKEN:
4881 return "BROKEN";
4882
4883 case STATUS_ZOMBIE:
4884 return "ZOMBIE";
4885
4886 default:
4887 return "UNKNOWN";
4888 }
4889}
4890
4891InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
Yi Kong9b14ac62018-07-17 13:48:38 -07004892 for (DispatchEntry* entry = waitQueue.head; entry != nullptr; entry = entry->next) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004893 if (entry->seq == seq) {
4894 return entry;
4895 }
4896 }
Yi Kong9b14ac62018-07-17 13:48:38 -07004897 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898}
4899
4900
4901// --- InputDispatcher::CommandEntry ---
4902
4903InputDispatcher::CommandEntry::CommandEntry(Command command) :
Yi Kong9b14ac62018-07-17 13:48:38 -07004904 command(command), eventTime(0), keyEntry(nullptr), userActivityEventType(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905 seq(0), handled(false) {
4906}
4907
4908InputDispatcher::CommandEntry::~CommandEntry() {
4909}
4910
4911
4912// --- InputDispatcher::TouchState ---
4913
4914InputDispatcher::TouchState::TouchState() :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004915 down(false), split(false), deviceId(-1), source(0), displayId(ADISPLAY_ID_NONE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916}
4917
4918InputDispatcher::TouchState::~TouchState() {
4919}
4920
4921void InputDispatcher::TouchState::reset() {
4922 down = false;
4923 split = false;
4924 deviceId = -1;
4925 source = 0;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004926 displayId = ADISPLAY_ID_NONE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927 windows.clear();
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004928 portalWindows.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929}
4930
4931void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
4932 down = other.down;
4933 split = other.split;
4934 deviceId = other.deviceId;
4935 source = other.source;
4936 displayId = other.displayId;
4937 windows = other.windows;
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004938 portalWindows = other.portalWindows;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004939}
4940
4941void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
4942 int32_t targetFlags, BitSet32 pointerIds) {
4943 if (targetFlags & InputTarget::FLAG_SPLIT) {
4944 split = true;
4945 }
4946
4947 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004948 TouchedWindow& touchedWindow = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949 if (touchedWindow.windowHandle == windowHandle) {
4950 touchedWindow.targetFlags |= targetFlags;
4951 if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
4952 touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
4953 }
4954 touchedWindow.pointerIds.value |= pointerIds.value;
4955 return;
4956 }
4957 }
4958
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004959 TouchedWindow touchedWindow;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960 touchedWindow.windowHandle = windowHandle;
4961 touchedWindow.targetFlags = targetFlags;
4962 touchedWindow.pointerIds = pointerIds;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004963 windows.push_back(touchedWindow);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964}
4965
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004966void InputDispatcher::TouchState::addPortalWindow(const sp<InputWindowHandle>& windowHandle) {
4967 size_t numWindows = portalWindows.size();
4968 for (size_t i = 0; i < numWindows; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004969 if (portalWindows[i] == windowHandle) {
Tiger Huang85b8c5e2019-01-17 18:34:54 +08004970 return;
4971 }
4972 }
4973 portalWindows.push_back(windowHandle);
4974}
4975
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
4977 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004978 if (windows[i].windowHandle == windowHandle) {
4979 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004980 return;
4981 }
4982 }
4983}
4984
Robert Carr803535b2018-08-02 16:38:15 -07004985void InputDispatcher::TouchState::removeWindowByToken(const sp<IBinder>& token) {
4986 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004987 if (windows[i].windowHandle->getToken() == token) {
4988 windows.erase(windows.begin() + i);
Robert Carr803535b2018-08-02 16:38:15 -07004989 return;
4990 }
4991 }
4992}
4993
Michael Wrightd02c5b62014-02-10 15:10:22 -08004994void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
4995 for (size_t i = 0 ; i < windows.size(); ) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004996 TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997 if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
4998 | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
4999 window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
5000 window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
5001 i += 1;
5002 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005003 windows.erase(windows.begin() + i);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004 }
5005 }
5006}
5007
5008sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
5009 for (size_t i = 0; i < windows.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005010 const TouchedWindow& window = windows[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5012 return window.windowHandle;
5013 }
5014 }
Yi Kong9b14ac62018-07-17 13:48:38 -07005015 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005016}
5017
5018bool InputDispatcher::TouchState::isSlippery() const {
5019 // Must have exactly one foreground window.
5020 bool haveSlipperyForegroundWindow = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08005021 for (const TouchedWindow& window : windows) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
5023 if (haveSlipperyForegroundWindow
5024 || !(window.windowHandle->getInfo()->layoutParamsFlags
5025 & InputWindowInfo::FLAG_SLIPPERY)) {
5026 return false;
5027 }
5028 haveSlipperyForegroundWindow = true;
5029 }
5030 }
5031 return haveSlipperyForegroundWindow;
5032}
5033
5034
5035// --- InputDispatcherThread ---
5036
5037InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
5038 Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
5039}
5040
5041InputDispatcherThread::~InputDispatcherThread() {
5042}
5043
5044bool InputDispatcherThread::threadLoop() {
5045 mDispatcher->dispatchOnce();
5046 return true;
5047}
5048
5049} // namespace android